-
Notifications
You must be signed in to change notification settings - Fork 5
/
Design456_2Ddrawing.py
999 lines (874 loc) · 40.6 KB
/
Design456_2Ddrawing.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
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
#
# ***************************************************************************
# * *
# * This file is a part of the Open Source Design456 Workbench - FreeCAD. *
# * *
# * Copyright (C) 2022 *
# * *
# * *
# * This library is free software; you can redistribute it and/or *
# * modify it under the terms of the GNU Lesser General Public *
# * License as published by the Free Software Foundation; either *
# * version 2 of the License, or (at your option) any later version. *
# * *
# * This library 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 *
# * Lesser General Public License for more details. *
# * *
# * You should have received a copy of the GNU Lesser General Public *
# * License along with this library; if not, If not, see *
# * <http://www.gnu.org/licenses/>. *
# * *
# * Author : Mariwan Jalal mariwan.jalal@gmail.com *
# **************************************************************************
import os
import sys
import FreeCAD as App
import FreeCADGui as Gui
import Draft
import Part
import Design456Init
from pivy import coin
import FACE_D as faced
import math
from PySide import QtGui, QtCore
from PySide.QtCore import QT_TRANSLATE_NOOP
from draftobjects.base import DraftObject
import Design456_Paint
import Design456_Hole
from draftutils.translate import translate # for translation
__updated__ = '2022-07-10 17:54:25'
# Move an object to the location of the mouse click on another surface
# ***************************************************************************
# * Modified by: Mariwan Jalal mariwan.jalal@gmail.com 04/03/2021 *
# *
# *__title__ = "Macro_Make_Arc_3_points" *
# *__author__ = "Mario52" *
# *__url__ = "https://www.freecadweb.org/index-fr.html" *
# *__version__ = "00.01" *
# *__date__ = "14/07/2016" *
# ***************************************************************************
class Design456_Arc3Points:
def Activated(self):
try:
App.ActiveDocument.openTransaction(
translate("Design456", "Arc3points"))
selected = Gui.Selection.getSelectionEx()
if (not(selected[0].HasSubObjects and len(selected) == 1)) and ((len(selected) < 3 or len(selected) > 3) ):
# Three object must be selected
errMessage = "Select three Vertexes to use Arc3Points Tool"
faced.errorDialog(errMessage)
return
allSelected = []
if selected[0].HasSubObjects and len(selected) == 1:
# We have only one object that we take vertices from
subObjects = selected[0].SubObjects
for n in subObjects:
allSelected.append(n.Point)
elif len(selected) == 3:
for t in selected:
if t.HasSubObjects:
n=t.SubObjects[0]
allSelected.append(n.Point)
else:
#Must be a Vertex object with only one vertex
allSelected.append(
App.Vector(t.Object.Shape.Vertexes[0].Point))
else:
print("A combination of objects")
print("Not implemented")
return
C1 = Part.Arc(App.Vector(allSelected[0]), App.Vector(
allSelected[1]), App.Vector(allSelected[2]))
S1 = Part.Shape([C1])
W = Part.Wire(S1.Edges)
Part.show(W)
App.ActiveDocument.recompute()
App.ActiveDocument.ActiveObject.Label = "Arc_3_Points"
del allSelected[:]
App.ActiveDocument.recompute()
App.ActiveDocument.commitTransaction() # undo
except Exception as err:
App.Console.PrintError("'Arc3Points' Failed. "
"{err}\n".format(err=str(err)))
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
def GetResources(self):
return {
'Pixmap': Design456Init.ICON_PATH + 'Arc3Points.svg',
'MenuText': 'Arc3Points',
'ToolTip': 'Arc 3Points'
}
Gui.addCommand('Design456_Arc3Points', Design456_Arc3Points())
class Design456_MultiPointsToWire:
def __init__(self, _type):
self._type = _type
def Activated(self):
try:
App.ActiveDocument.openTransaction(
translate("Design456", "MultipointsToWire"))
selected = Gui.Selection.getSelectionEx()
if (len(selected) < 2):
# Two object must be selected
if (not selected[0].HasSubObjects):
errMessage = "Select two or more objects to use MultiPointsToLineOpen Tool"
faced.errorDialog(errMessage)
return
allSelected = []
for t in selected:
if type(t) == list:
for tt in t:
allSelected.append(App.Vector(
tt.Shape.Vertexes[0].Point))
else:
if t.HasSubObjects and hasattr(t.SubObjects[0], "Vertexes"):
for v in t.SubObjects:
allSelected.append(App.Vector(v.Point))
elif t.HasSubObjects and hasattr(t.SubObjects[0], "Surface"):
errMessage = "Only Vertexes are allowed. You selected a face"
faced.errorDialog(errMessage)
return
else:
allSelected.append(App.Vector(t.Object.Shape.Point))
f=0
if self._type == 0:
W=Part.makePolygon([*allSelected,allSelected[0]])
f=Part.Face(W)
Part.show(f,"MultiPointsToWire")
else:
W=Part.makePolygon(allSelected)
Part.show(W,"MultiPointsToWire")
del allSelected[:]
App.ActiveDocument.recompute()
App.ActiveDocument.commitTransaction() # undo
except Exception as err:
App.Console.PrintError("'MultiPointsToWire' Failed. "
"{err}\n".format(err=str(err)))
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
class Design456_MultiPointsToWireClose:
def Activated(self):
try:
newObj = Design456_MultiPointsToWire(0)
newObj.Activated()
except Exception as err:
App.Console.PrintError("'MultiPointsToWireClose' Failed. "
"{err}\n".format(err=str(err)))
def GetResources(self):
return {
'Pixmap': Design456Init.ICON_PATH + 'MultiPointsToWireClosed.svg',
'MenuText': 'Multi-Points To Wire Closed',
'ToolTip': 'Multi-Points To Wire Closed'
}
class Design456_MultiPointsToWireOpen:
def Activated(self):
try:
newObj = Design456_MultiPointsToWire(1)
newObj.Activated()
except Exception as err:
App.Console.PrintError("'MultiPointsToWireOpen' Failed. "
"{err}\n".format(err=str(err)))
def GetResources(self):
return {
'Pixmap': Design456Init.ICON_PATH + 'MultiPointsToWireOpen.svg',
'MenuText': 'Multi-Points To Wire Open',
'ToolTip': 'Multi-Points To Wire Open'
}
Gui.addCommand('Design456_MultiPointsToWireOpen',
Design456_MultiPointsToWireOpen())
Gui.addCommand('Design456_MultiPointsToWireClose',
Design456_MultiPointsToWireClose())
# Trim all selected lines/vertices, and leave the object open
# Warning: This command destroys the 2D shape and will loose the face.
class Design456_2DTrim:
def Activated(self):
try:
sel = Gui.Selection.getSelectionEx()
if len(sel) < 1:
# several selections - Error
errMessage = "Select one or more edges to trim"
faced.errorDialog(errMessage)
return
SelectedPoints = []
sel1 = sel[0]
if sel1.HasSubObjects:
# We have several objects that has subobject(Edges) that should be trimmed
# Save position and angle
_placement = sel1.Object.Placement
_placement.Rotation.Q = sel1.Object.Placement.Rotation.Q
# = App.ActiveDocument.getObject(sel1.Object.Name)
SelectedPoints.clear() # points in the targeted line to be trimmed
_edg = sel1.SubObjects[0]
# TODO: trim only 2 points at the moment
Vert = _edg.Vertexes
# Save all points we have in the edge or line/wire which should be trimmed
for n in Vert:
SelectedPoints.append(App.Vector(n.Point))
WireOrEdgeMadeOfPoints = []
# Bring all points from the object
for item in sel1.Object.Shape.Vertexes:
WireOrEdgeMadeOfPoints.append(App.Vector(item.Point))
totalPoints = len(WireOrEdgeMadeOfPoints)
position1 = position2 = None
count = 0
# First find their locations
for j in range(totalPoints):
if SelectedPoints[0] == WireOrEdgeMadeOfPoints[j]:
position1 = count
elif (SelectedPoints[1] == WireOrEdgeMadeOfPoints[j]):
position2 = count
count = count+1
# Try to reconstruct the shape/wire
#TestTwoObjectCreate = False
_all_points2 = []
objType = selectedObjectType(sel1)
closedShape = None
EndPoint = StartPoint = None
if (objType == 'Wire' or objType == 'Line'):
closedShape = sel1.Object.Closed
elif objType == 'Unknown':
closedShape = False
return # We don't know what the shape is
elif objType == 'Arc':
App.ActiveDocument.removeObject(sel1.Object.Name)
return
else:
closedShape = True
if closedShape is True:
# We have a shape with closed lines
# Here we need to do 2 things, 1 remove closed, 2 rearrange start-end
scan1 = min(position1, position2)
scan2 = max(position1, position2)
sortAll = 0
Index = scan2
EndPoint = WireOrEdgeMadeOfPoints[scan1]
StartPoint = WireOrEdgeMadeOfPoints[scan2]
while(sortAll < totalPoints):
_all_points2.append(WireOrEdgeMadeOfPoints[Index])
Index = Index+1
if Index >= totalPoints:
Index = 0
sortAll = sortAll+1
WireOrEdgeMadeOfPoints.clear()
WireOrEdgeMadeOfPoints = _all_points2
elif(abs(position2-position1) == 1):
# It must be a line and not closed
if position1 != 0 and position2 != totalPoints-1:
# In the middle of the array.
# Two objects must be created.
_all_points2.clear()
#plusOrMinus = 0
scan1 = min(position1, position2)
scan2 = max(position1, position2)
#SaveValue = None
index = 0
while (index <= scan1):
_all_points2.append(WireOrEdgeMadeOfPoints[index])
index = index+1
index = 0
StartPoint = WireOrEdgeMadeOfPoints[scan2]
EndPoint = WireOrEdgeMadeOfPoints[len(
WireOrEdgeMadeOfPoints)-1]
for index in range(0, scan2):
WireOrEdgeMadeOfPoints.pop(index)
pnew2DObject1 = Draft.makeWire(
_all_points2, placement=None, closed=False, face=False, support=None)
pnew2DObject1.Label = 'Wire'
pnew2DObject1.Start = _all_points2[0]
pnew2DObject1.End = _all_points2[len(_all_points2)-1]
elif position1 == 0 and position2 != totalPoints-1:
# First Points, remove 'closed' and start = pos+1
StartPoint = WireOrEdgeMadeOfPoints[position2]
WireOrEdgeMadeOfPoints.pop(position1)
EndPoint = WireOrEdgeMadeOfPoints[len(
WireOrEdgeMadeOfPoints)-1]
# don't add first point
elif position2 == totalPoints-1:
# point 2 is the last point in the shape
StartPoint = WireOrEdgeMadeOfPoints[0]
EndPoint = WireOrEdgeMadeOfPoints[position2-1]
WireOrEdgeMadeOfPoints.pop(position2-1)
# don't add last point
pnew2DObject2 = Draft.makeWire(
WireOrEdgeMadeOfPoints, placement=None, closed=False, face=False, support=None)
App.ActiveDocument.removeObject(sel1.ObjectName)
App.ActiveDocument.recompute()
pnew2DObject2.Label = 'Wire'
pnew2DObject2.End = EndPoint
pnew2DObject2.Start = StartPoint
# If nothing left, remove the object
if len(pnew2DObject2.Shape.Vertexes) == 0:
App.ActiveDocument.removeObject(pnew2DObject2.Label)
App.ActiveDocument.recompute()
else:
# No Edges found
errMessage = "Select one or more edges to trim"
faced.errorDialog(errMessage)
return
except Exception as err:
App.Console.PrintError("'Trim 2D' Failed. "
"{err}\n".format(err=str(err)))
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
def GetResources(self):
import Design456Init
return {
'Pixmap': Design456Init.ICON_PATH + '2D_TrimLine.svg',
'MenuText': 'Trim Line',
'ToolTip': 'Trim Line or edge in a 2D shape'
}
Gui.addCommand('Design456_2DTrim', Design456_2DTrim())
def selectedObjectType(obj):
if isinstance(obj.Object, Part.Shape):
return "Shape"
if hasattr(obj.Object, 'Proxy'):
if hasattr(obj.Object.Proxy, "Type"):
return obj.Object.Proxy.Type
if hasattr(obj.Object, 'TypeId'):
return obj.Object.TypeId
return "Unknown"
class ViewProviderStar:
obj_name = "Star"
def __init__(self, obj, obj_name):
self.obj_name = ViewProviderStar.obj_name
obj.Proxy = self
def attach(self, obj):
return
def updateData(self, fp, prop):
return
def getDisplayModes(self, obj):
return "As Is"
def getDefaultDisplayMode(self):
return "As Is"
def setDisplayMode(self, mode):
return "As Is"
def onChanged(self, vobj, prop):
pass
def getIcon(self):
return (Design456Init.ICON_PATH + 'Design456_Star.svg')
def __getstate__(self):
return None
def __setstate__(self, state):
return None
# ===========================================================================
# Create 2D Star
class Star:
"""
Create a 2D Star based on the Inner radius outer radius, corners and the angle.
"""
def __init__(self, obj, _InnerRadius=10, _OuterRadius=20, _Angle=2*math.pi, _Corners=40):
_tip = QT_TRANSLATE_NOOP("App::Property", "Star Angel")
obj.addProperty("App::PropertyAngle", "Angle",
"Star", _tip).Angle = _Angle
_tip = QT_TRANSLATE_NOOP("App::Property", "Inner Radius of the star")
obj.addProperty("App::PropertyLength", "InnerRadius",
"Star", _tip).InnerRadius = _InnerRadius
_tip = QT_TRANSLATE_NOOP("App::Property", "Outer Radius of the star")
obj.addProperty("App::PropertyLength", "OuterRadius",
"Star", _tip).OuterRadius = _OuterRadius
_tip = QT_TRANSLATE_NOOP("App::Property", "Corners of the star")
obj.addProperty("App::PropertyInteger", "Corners",
"Star", _tip).Corners = _Corners
_tip = QT_TRANSLATE_NOOP("App::Property", "Make Face")
obj.addProperty("App::PropertyBool", "MakeFace",
"Star", _tip).MakeFace = True
_tip = QT_TRANSLATE_NOOP("App::Property", "The area of this object")
obj.addProperty("App::PropertyArea", "Area", "Star", _tip).Area
obj.Proxy = self
def execute(self, obj):
try:
if obj.OuterRadius < obj.InnerRadius:
# you cannot have it smaller
obj.OuterRadius = obj.InnerRadius
self.points = []
for i in range(0, obj.Corners):
alpha = math.pi * (2 * i + 2 - obj.Corners % 2)/(obj.Corners)
if i % 2 == 1:
radius = obj.InnerRadius
else:
radius = obj.OuterRadius
x = math.cos(alpha) * radius
y = math.sin(alpha) * radius
self.points.append(App.Vector(x, y, 0.0))
if i == 0:
saveFirstPoint = App.Vector(x, y, 0.0)
if alpha > obj.Angle:
break
self.points.append(saveFirstPoint)
test = Part.makePolygon(self.points)
obj.Shape = Part.Face(test)
if hasattr(obj, "Area") and hasattr(obj.Shape, "Area"):
obj.Area = obj.Shape.Area
return obj # Allow getting the
except Exception as err:
App.Console.PrintError("'Star' Failed. "
"{err}\n".format(err=str(err)))
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
return
class Design456_Star:
def Activated(self):
try:
App.ActiveDocument.openTransaction(translate("Design456","Star"))
newObj = App.ActiveDocument.addObject(
"Part::FeaturePython", "Star")
ViewProviderStar(newObj.ViewObject, "Star")
f = Star(newObj)
plc = App.Placement()
f.Placement = plc
App.ActiveDocument.recompute()
App.ActiveDocument.commitTransaction() # undo
return newObj
except Exception as err:
App.Console.PrintError("'StarCommand' Failed. "
"{err}\n".format(err=str(err)))
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
return
def GetResources(self):
return {'Pixmap': Design456Init.ICON_PATH + 'Design456_Star.svg',
'MenuText': "Star",
'ToolTip': "Draw a Star"}
Gui.addCommand('Design456_Star', Design456_Star())
class Design456_joinTwoLines:
"""[Join two lines, edges or a series of edges to one edge
This is useful when you want to simplify an edge or a line.
]
"""
def Activated(self):
import DraftGeomUtils
try:
s = Gui.Selection.getSelectionEx()
if hasattr(s, "Point"):
return
e1 = None
e2 = None
if len(s) > 2:
# Two objects must be selected
errMessage = "Select only two vertices "
faced.errorDialog(errMessage)
return
elif len(s) == 1:
errMessage = "Not implemented "
faced.errorDialog(errMessage)
return
elif len(s) == 2:
s1 = s[0]
s2 = s[1]
if ( 'Vertex' in str(s1.SubElementNames)):
# Vertexes are selected
p1 = s1.SubObjects[0].Vertexes[0].Point
p2 = s2.SubObjects[0].Vertexes[0].Point
elif ( 'Edge' in str(s1.SubElementNames)):
# Edges are selected
# We have to find the nearest two vector.
# Joining here means inner vertices will be removed.
vert1=[]
for e in s1.Object.Shape.OrderedEdges:
for v in e.Vertexes:
vert1.append(v.Point)
vert2 = []
for e in s2.Object.Shape.OrderedEdges:
for v in e.Vertexes:
vert2.append(v.Point)
# Now we need to find one point from each edge
# that are nearest to each other
index1=DraftGeomUtils.findClosest(vert1[0],vert2)
index2=DraftGeomUtils.findClosest(vert1[len(vert1)-1],vert2)
dist1 = math.sqrt( pow((vert1[0].x-vert2[index1].x),2)+
pow((vert1[0].y-vert2[index1].y),2)+
pow((vert1[0].z-vert2[index1].z),2))
dist2 = math.sqrt( pow((vert1[len(vert1)-1].x-vert2[index2].x),2)+
pow((vert1[len(vert1)-1].y-vert2[index2].y),2)+
pow((vert1[len(vert1)-1].y-vert2[index2].z),2))
if dist1 == dist2 or dist1 < dist2:
p1=vert1[0]
p2=vert2[index1]
elif dist2 < dist1:
p1=vert1[len(vert1)-1]
p2=vert2[index2]
if hasattr(s1.Object.Shape, "OrderedEdges"):
Edges1 = s1.Object.Shape.OrderedEdges
else:
Edges1 = s1.Object.Shape.Edges
if hasattr(s2.Object.Shape, "OrderedEdges"):
Edges2 = s2.Object.Shape.OrderedEdges
else:
Edges2 = s2.Object.Shape.Edges
if len(Edges1) > 1:
for ed in Edges1:
for v in ed.Vertexes:
if v.Point == p1:
e1 = ed
Edges1.remove(e1)
break
else:
e1 = Edges1[0]
Edges1 = []
# We have the edges and the points
if e1 is not None:
if (e1.Vertexes[0].Point != p1):
p1 = e1.Vertexes[0].Point
else:
p1 = e1.Vertexes[1].Point
p1 = App.Vector(p1.x, p1.y, p1.z)
p2 = App.Vector(p2.x, p2.y, p2.z)
App.ActiveDocument.openTransaction(
translate("Design456", "Join2Lines"))
l1 = Draft.makeLine(p1, p2)
App.ActiveDocument.recompute()
newEdg = l1.Shape.Edges[0]
if type(Edges1) == list and type(Edges2) == list:
totalE = Edges1 + Edges2 + [newEdg]
elif type(Edges1) == list and type(Edges2) != list:
totalE = Edges1 + [Edges2]+[newEdg]
elif type(Edges1) != list and type(Edges2) == list:
# Only one edge in the first line, so not included
totalE = Edges2 + [newEdg]
else:
# None of them is multiple edges. so only new edge should be use
totalE = [Edges2]+[newEdg]
newList = []
for e in totalE:
newList.append(e.copy())
sortEdg = Part.sortEdges(newList)
W = [Part.Wire(e) for e in sortEdg]
for wire in W:
newobj = App.ActiveDocument.addObject("Part::Feature", "Wire")
newobj.Shape = wire
App.ActiveDocument.removeObject(l1.Name)
App.ActiveDocument.removeObject(s1.Object.Name)
App.ActiveDocument.removeObject(s2.Object.Name)
App.ActiveDocument.recompute()
App.ActiveDocument.commitTransaction() # undo reg.de here
except Exception as err:
App.Console.PrintError("'Part Surface' Failed. "
"{err}\n".format(err=str(err)))
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
def GetResources(self):
from PySide.QtCore import QT_TRANSLATE_NOOP
"""Set icon, menu and tooltip."""
_tooltip = ("Join two lines")
return {'Pixmap': Design456Init.ICON_PATH + 'Design456_JoinLines.svg',
'MenuText': QT_TRANSLATE_NOOP("Design456", "joinTwoLines"),
'ToolTip': QT_TRANSLATE_NOOP("Design456", _tooltip)}
Gui.addCommand('Design456_joinTwoLines', Design456_joinTwoLines())
class Design456_SimplifyEdges:
"""[Simplify a list of line, wire, or edges to one edge.
This is useful if you want to repair a shape that has
multiple complex edges that not make sense.
]
"""
def Activated(self):
try:
nEdgeObj=None
s = Gui.Selection.getSelectionEx()
if len(s) > 1:
# TODO: FIXME: Should we accept more than one object?
errMessage = "Select edges from one object"
faced.errorDialog(errMessage)
return
App.ActiveDocument.openTransaction(
translate("Design456", "SimplifyEdges"))
selObj = s[0]
#selEdges = selObj.Object.Shape.OrderedEdges
selEdges = selObj.Object.Shape.Edges
selVertexes = []
for e in selEdges:
for v in e.Vertexes:
if len(selVertexes)==0:
selVertexes.append(v.Point)
else:
for p in selVertexes:
if v.Point!=p:#//skip what is inside the list
selVertexes.append(v.Point)
break
else:
continue
if hasattr(selObj.Object.Shape.Edges[0], "Curve") or hasattr(selObj.Object.Shape.Edges[1], "Curve"):
#We have a curve, must be treated differently from line
#Whenever there is a curve+curve, or curve+line, the result will be only curve.
#Otherwise there is no reason to simplify
if len(selVertexes)>3:
v1=selVertexes[0]
v2=selVertexes[2]
v3=selVertexes[3]
else:
v1=selVertexes[0]
v2=selVertexes[1]
v3=selVertexes[2]
nEdgeObj=(Part.Arc(v1,v2,v3)).toShape()
else:
# To eliminate multiple vertices
# inside the same edge, we take only
# first and last entities and then
# we make a line and convert it to
# an edge. which should replace the
# old edge
v1 = selVertexes[0]
v2 = selVertexes[len(selVertexes)-1]
nEdgeObj = Part.makePolygon([v1, v2])
App.ActiveDocument.recompute()
newobj = App.ActiveDocument.addObject("Part::Feature", "Wire")
sh = nEdgeObj
newobj.Shape = sh.copy()
App.ActiveDocument.recompute()
#Preserve color and other properties of the old obj
faced.PreserveColorTexture(s[0].Object,newobj)
App.ActiveDocument.removeObject(selObj.Object.Name)
App.ActiveDocument.commitTransaction() # undo
except Exception as err:
App.Console.PrintError("'Design456_SimplifyEdges' Failed. "
"{err}\n".format(err=str(err)))
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
def GetResources(self):
import Design456Init
from PySide.QtCore import QT_TRANSLATE_NOOP
"""Set icon, menu and tooltip."""
_tooltip = ("Simplify Edges")
return {'Pixmap': Design456Init.ICON_PATH + 'SimplifyEdge.svg',
'MenuText': QT_TRANSLATE_NOOP("Design456", "SimplifyEdges"),
'ToolTip': QT_TRANSLATE_NOOP("Design456", _tooltip)}
Gui.addCommand('Design456_SimplifyEdges', Design456_SimplifyEdges())
class Design456_DivideCircleFace:
def findEdgeHavingCurve(self):
edges=self.selected.SubObjects[0].Edges
result=[]
for edg in edges:
if hasattr(edg, 'Curve'):
result.append(edg)
return result
#circle = make_circle(radius, placement=None, face=None,
# startangle=None, endangle=None,
# support=None)
def recreateEdges(self,edges,dividedTo):
try:
newObjs=[]
for edge in edges:
newObj = None
Radius = edge.Curve.Radius
center = edge.Curve.Center
firstP = math.degrees(edge.Curve.FirstParameter)
lastP = math.degrees(edge.Curve.LastParameter)
AnglePart = (lastP - firstP)/dividedTo
for i in range(0,dividedTo):
initial = firstP+(i*AnglePart)
plc= self.selected.Object.Placement
circle = Draft.make_circle(Radius, plc,True,initial,initial+AnglePart)
App.ActiveDocument.recompute()
line1 = Draft.makeLine(circle.Shape.Vertexes[0].Point,center)
line2 =Draft.makeLine(circle.Shape.Vertexes[1].Point,center)
App.ActiveDocument.recompute()
# Convert it to a wire
Obj=Draft.upgrade([circle,line1,line2],True)
# Create face
Obj=Draft.upgrade(Obj[0],True)
App.ActiveDocument.recompute()
newObjs=newObjs+Obj[0]
tobj = Draft.upgrade(newObjs, True)
newObjs = tobj[0]
return newObjs
except Exception as err:
App.Console.PrintError("'Design456_DivideCircleFace' Failed. "
"{err}\n".format(err=str(err)))
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
def Activated(self):
try:
s = Gui.Selection.getSelectionEx()
if len(s) > 1 or len(s)<1:
# TODO: FIXME: Should we accept more than one object?
errMessage = "Select one object"
faced.errorDialog(errMessage)
return
DivideBy = QtGui.QInputDialog.getInt(
None, "Divide by", "Input:", 0, 1, 50.0, 1)[0]
if(DivideBy <=1):
return # nothing to do here
self.selected = s[0]
App.ActiveDocument.openTransaction(
translate("Design456", "Divide Circle"))
edgesToRecreate=self.findEdgeHavingCurve()
#We have the edges that needs to be divided
newObjects=self.recreateEdges(edgesToRecreate,DivideBy)
App.ActiveDocument.removeObject(self.selected.Object.Name)
App.ActiveDocument.commitTransaction() # undo
return newObjects
except Exception as err:
App.Console.PrintError("'Design456_DivideCircleFace' Failed. "
"{err}\n".format(err=str(err)))
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
def GetResources(self):
import Design456Init
from PySide.QtCore import QT_TRANSLATE_NOOP
"""Set icon, menu and tooltip."""
_tooltip = ("Divide Circle Face")
return {'Pixmap': Design456Init.ICON_PATH + 'DivideCircleFace.svg',
'MenuText': QT_TRANSLATE_NOOP("Design456", "DivideCircleFace"),
'ToolTip': QT_TRANSLATE_NOOP("Design456", _tooltip)}
Gui.addCommand('Design456_DivideCircleFace', Design456_DivideCircleFace())
class Design456_RemoveEdge:
def Activated(self):
result=[]
try:
s = Gui.Selection.getSelectionEx()
if len(s) > 1:
errMessage = "Select edges from one object"
faced.errorDialog(errMessage)
return
if hasattr(s[0],"SubObjects"):
if s[0].HasSubObjects:
selectedObj=s[0].SubObjects
else:
selectedObj=s[0].Object.Shape.Edges[0]
else:
return
edges=[]
_resultFaces=[]
AllFaces=s[0].Object.Shape.Faces
for i in range(0,len(AllFaces)):
edges.clear()
edges=(AllFaces[i].OuterWire.OrderedEdges)
temp=[]
temp.clear()
for j in range(0,len(edges)):
found=False
for obj in selectedObj:
if ( (edges[j]).isEqual(obj)):
found=True
print ("found")
else:
temp.append(edges[j].copy())
if (len(temp)> 0 ):
#recreate the shape
#Register undo
App.ActiveDocument.openTransaction(
translate("Design456", "RemoveEdge"))
nFace=None
nWire=Part.Wire(temp)
if nWire.isClosed():
try:
nFace=Part.makeFilledFace(temp)
except:
pass
if (nFace is None) or (nFace.isNull()):
print("failed")
nF = App.ActiveDocument.addObject("Part::Feature", "nWire")
nF.Shape=nWire
else:
_resultFaces.append(nFace)
App.ActiveDocument.recompute()
shell=Part.makeShell(_resultFaces)
App.ActiveDocument.recompute()
final = App.ActiveDocument.addObject("Part::Feature", "RemoveEdge")
final.Shape = shell
App.ActiveDocument.recompute()
App.ActiveDocument.removeObject(s[0].Object.Name)
except Exception as err:
App.Console.PrintError("'Design456_RemoveEdge' Failed. "
"{err}\n".format(err=str(err)))
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
def GetResources(self):
"""Set icon, menu and tooltip."""
_tooltip = ("Remove Edge")
return {'Pixmap': Design456Init.ICON_PATH + 'RemoveEdge.svg',
'MenuText': QT_TRANSLATE_NOOP("Design456", "RemoveEdge"),
'ToolTip': QT_TRANSLATE_NOOP("Design456", _tooltip)}
Gui.addCommand('Design456_RemoveEdge', Design456_RemoveEdge())
class Design456_SimplifiedFace:
"""
Simplify any object (2D) by removing embedded edges
"""
def Activated(self):
try:
s = Gui.Selection.getSelectionEx()
if len(s) < 1:
errMessage = "Select Simplified Face"
faced.errorDialog(errMessage)
return
# if len(s)>1:
# #We have several faces. Make them compound.
# ss=Part.makeShell(s)
# newFace = App.ActiveDocument.addObject("Part::Feature", "Shell")
# newFace.Shape=ss
# for o in s:
# App.ActiveDocument.removeObject(o.Name)
# s=newFace
AllEdges=[]
App.ActiveDocument.openTransaction(
translate("Design456", "SimplifiedFace"))
for obj in s:
shp=obj.Object.Shape
obj.Object.Visibility=False
for edg in shp.Edges:
#if the edges are shared between faces, don't add
if faced.findFaceSHavingTheSameEdge(edg,shp) is None:
AllEdges.append(edg)
AllEdges=Part.__sortEdges__(AllEdges)
newFace=Part.makeFilledFace(AllEdges)
App.ActiveDocument.recompute()
newObj=App.ActiveDocument.addObject('Part::Feature', 'SimplifiedFace')
newObj.Placement=s[0].Object.Placement
newObj.Shape=newFace
App.ActiveDocument.recompute()
App.ActiveDocument.commitTransaction() # undo
except Exception as err:
App.Console.PrintError("'Design456_SimplifiedFace' Failed. "
"{err}\n".format(err=str(err)))
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
def GetResources(self):
"""Set icon, menu and tooltip."""
_tooltip = ("SimplifiedFace")
return {'Pixmap': Design456Init.ICON_PATH + 'SimplifiedFace.svg',
'MenuText': QT_TRANSLATE_NOOP("Design456", "SimplifiedFace"),
'ToolTip': QT_TRANSLATE_NOOP("Design456", _tooltip)}
Gui.addCommand('Design456_SimplifiedFace', Design456_SimplifiedFace())
##################################################################################
# Toolbar group definition
class Design456_2Ddrawing:
list = ["Design456_Arc3Points",
"Design456_MultiPointsToWireOpen",
"Design456_MultiPointsToWireClose",
"Design456_2DTrim",
"Design456_joinTwoLines",
"Design456_SimplifyEdges",
"Design456_SimplifiedFace",
"Design456_Star",
"Design456_Paint",
"Design456_Hole",
"Design456_DivideCircleFace",
"Design456_RemoveEdge",
]
"""Design456 Design456_2Ddrawing Toolbar"""
def GetResources(self):
return{
'Pixmap': Design456Init.ICON_PATH + '2D_Drawing.svg',
'MenuText': '2Ddrawing',
'ToolTip': '2Ddrawing'
}
def IsActive(self):
if App.ActiveDocument is None:
return False
else:
return True
def Activated(self):
self.appendToolbar("Design456_2Ddrawing", self.list)