-
Notifications
You must be signed in to change notification settings - Fork 4
/
MeshRemodelCmd.py
8391 lines (7322 loc) · 360 KB
/
MeshRemodelCmd.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
# -*- coding: utf-8 -*-
###################################################################################
#
# MeshRemodelCmd.py
#
# Copyright 2019 Mark Ganson <TheMarkster> mwganson at gmail
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
#
###################################################################################
__title__ = "MeshRemodel"
__author__ = "Mark Ganson <TheMarkster>"
__url__ = "https://github.com/mwganson/MeshRemodel"
__date__ = "2024.10.15"
__version__ = "1.10.32"
import FreeCAD, FreeCADGui, Part, os, math
from PySide import QtCore, QtGui
try:
from PySide import QtWidgets
except:
QtWidgets = QtGui
import Draft, DraftGeomUtils, DraftVecUtils, Mesh, MeshPart
import time
import numpy as np
import shiboken2 as shiboken
if FreeCAD.GuiUp:
from FreeCAD import Gui
__dir__ = os.path.dirname(__file__)
iconPath = os.path.join( __dir__, 'Resources', 'icons' )
keepToolbar = False
windowFlags = QtCore.Qt.WindowTitleHint | QtCore.Qt.WindowCloseButtonHint #no ? in title bar
global_picked = [] #picked points list for use with selection by preselection observer
FC_VERSION = float(FreeCAD.Version()[0]) + float(FreeCAD.Version()[1]) #e.g. 0.20, 0.18, 1.??
epsilon = Part.Precision.confusion() #1e-07
def fixTip(tip):
if FC_VERSION >= 0.20:
return tip.replace("\n","<br/>")
else:
return tip
######################################################################################
# geometry utilities
class MeshRemodelGeomUtils(object):
"""Geometry Utilities"""
#progress bar on status bar with cancel button
class MRProgress:
def __init__(self, total=0, txt = ""):
self.pb = None
self.btn = None
self.bar = None
self.bCanceled = False
self.value = 0
self.total = 0
self.mw = FreeCADGui.getMainWindow()
self.lastUpdate = time.time()
if total:
return self.makeProgressBar(total, buttonText = txt if txt else "Cancel")
def makeProgressBar(self,total=0,buttonText = "Cancel",tooltip = "Cancel current operation",updateInterval = .5):
"""total is max value for progress bar, mod = number of updates you want"""
self.btn = QtGui.QPushButton(buttonText)
self.btn.setToolTip(tooltip)
self.btn.clicked.connect(self.on_clicked)
self.pb = QtGui.QProgressBar()
self.bar = self.mw.statusBar()
self.bar.addWidget(self.pb)
self.bar.addWidget(self.btn)
self.btn.show()
self.pb.show()
self.pb.reset()
self.value = 0
self.pb.setMinimum(0)
self.updateInterval = updateInterval
self.pb.setMaximum(total);
self.total = total
self.pb.setFormat("%v/%m")
self.bAlive = True #hasn't been killed yet
self.bCanceled = False
def on_clicked(self):
self.bCanceled = True
self.killProgressBar()
def isCanceled(self):
self.value += 1
timeNow = time.time()
if timeNow - self.lastUpdate >= self.updateInterval:
self.lastUpdate = timeNow
self.pb.setValue(self.value)
FreeCADGui.updateGui()
if self.mw.isHidden() or self.value >= self.total:
self.bCanceled = True
self.killProgressBar()
return self.bCanceled
def killProgressBar(self):
if self.bAlive: #check if it has already been removed before removing
self.bar.removeWidget(self.pb)
self.bar.removeWidget(self.btn)
self.bAlive = False
self.pb.hide()
self.btn.hide()
self.value = 0
self.total = 0
#### end progress bar class
def getFloatFromUser(self, title, msg, value, min=-float("inf"), max=float("inf"), flags=None, step=0.1):
"""Open a dialog and get a floating point value from the user"""
val,ok = QtGui.QInputDialog.getDouble(FreeCADGui.getMainWindow(), title,
msg, value, min, max, 8,FreeCADGui.getMainWindow().windowFlags(), step)
return val if ok else None
def getFacetsFromFacetIndices(self, facet_indices, mesh):
"""getFacetsFromFacetIndices(self, facet_indices, mesh)"""
return [mesh.Facets[idx] for idx in facet_indices]
def getFacetIndicesFromPointIndices(self, point_indices, mesh):
"""getFacetIndicesFromPointINdices(self, point_indices, mesh)
return the facet indices given the point indices and the mesh"""
return [facet.Index for facet in mesh.Facets \
if self.facetIsInList(facet, point_indices)]
def getPointIndicesInMesh(self, pts, mesh):
"""gets the point indices of the points in the mesh"""
return [self.findPointInMesh(mesh, pt) for pt in pts]
def facetIsInList(self, facet, point_indices):
"""all 3 of the facet's points must be in the point_indices"""
for idx in facet.PointIndices:
if not idx in point_indices:
return False
return True
def findPointInMesh(self, mesh, pt):
"""find the point in the mesh, return the index of the point in
the points list"""
topology = mesh.Topology
# topology is a tuple ([vectorlist],[facetlist])
# facet list is a list of tuples
# each tuple of the form (pt1_idx, pt2_idx, pt3_idx)
indices = []
points = mesh.Points
for point in points:
if gu.isSamePoint(pt, point.Vector, 1e-5):
if not point.Index in indices:
indices.append(point.Index)
if len(indices) == 1:
return indices[0]
return []
def checkComponents(self,mesh):
"""check for multiple components in a mesh and warn user"""
if mesh.countComponents() > 1:
FreeCAD.Console.PrintWarning("\
MeshRemodel: selected mesh has multiple components. Consider using \
Split by components operation in Mesh workbench to separate these into \
component objects before attempting modifications.\n")
def getBaseAndNormal(self, trio):
"""return base,normal of plane defined by trio, list of Vector"""
trio = np.array([np.array(v.Point) for v in trio[:3]])
normal = np.cross(trio[1] - trio[0], trio[2] - trio[0])
if not any(normal): #all 0's
return (None,None)
divisor = np.linalg.norm(normal)
normal /= np.linalg.norm(normal) #normalize
norm = FreeCAD.Vector(normal[0], normal[1], normal[2])
return trio[0], norm
def wireIsPlanar(self, wire):
"""check if the wire is planar and return bool"""
pts = wire.discretize(5)
pts = [Part.Vertex(p.x,p.y,p.z) for p in pts[:4]]
return self.isCoplanar(pts[:3], pts[3].Point, tol=Part.Precision.confusion())
def isCoplanar(self, trio, pt, tol=1e-5):
""" check if pt is one the same plane as the one defined by
trio, a trio of points. pt is considered to be on the plane if
its distance to the plane <= tol"""
def distance_to_plane(point, plane_point, plane_normal):
point = np.array(point)
plane_point = np.array(plane_point)
plane_normal = np.array(plane_normal)
vector_to_point = point - plane_point
distance = np.abs(np.dot(vector_to_point, plane_normal)) / np.linalg.norm(plane_normal)
return distance
trio = np.array([np.array(v.Point) for v in trio])
pt = np.array(pt)
normal = np.cross(trio[1] - trio[0], trio[2] - trio[0])
normal /= np.linalg.norm(normal) #normalize
return distance_to_plane(pt, trio[0], normal) <= tol
def hasPoint(self,pt,lis,tol):
"""hasPoint(pt,lis,tol)"""
for l in lis:
if self.isSamePoint(pt,l,tol):
return True
return False
def hasLine(self, line, lis, tol=1e-6):
"""hasLine(self, line, lis, tol=1e-6)"""
for l in lis:
if self.isSameLine(line, l, tol):
return True
return False
def isSamePoint(self,A,B,tol):
"""isSamePoint(A,B,tol)"""
dis = self.dist(A,B)
if dis < tol:
return True
return False
def isSameLine(self, A, B, tol=1e-6):
"""isSameLine(self, A, B, tol)"""
if abs(A.Length - B.Length) > tol:
return False
if self.isSamePoint(A.Vertex1.Point, B.Vertex1.Point, tol):
if self.isSamePoint(A.Vertex2.Point, B.Vertex2.Point, tol):
return True
if self.isSamePoint(A.Vertex1.Point, B.Vertex2.Point, tol):
if self.isSamePoint(A.Vertex2.Point, B.Vertex1.Point, tol):
return True
return False
def midpoint(self, A, B):
""" midpoint(A, B)
A,B are vectors, return midpoint"""
mid = FreeCAD.Base.Vector()
mid.x = (A.x + B.x)/2.0
mid.y = (A.y + B.y)/2.0
mid.z = (A.z + B.z)/2.0
return mid
def dist(self, p1, p2):
""" dist (p1, p2)
3d distance between vectors p1 and p2"""
return self.getDistance3d(p1[0],p1[1],p1[2],p2[0],p2[1],p2[2])
def getDistance3d(self, x1, y1, z1, x2, y2, z2):
""" getDistance3d(x1, y1, z1, x2, y2, z2)
3d distance between x1,y1,z1 and x2,y2,z2 float parameters"""
return math.sqrt((x1 - x2)**2 + (y1 - y2)**2 + (z1 - z2)**2)
def sortPoints(self,pts):
""" sortPoints(pts)
sort pts, a list of vectors, according to distance from one point to the next
pts[0] is taken first, then the nearest point to it is placed at pts[1]
then pts[1] is used to find the nearest point to it and placed at pts[2], and so on
"""
newList = [pts[0]]
for ii in range(0, len(pts)):
newList.extend([self.nearestPoint(newList[ii],pts,newList)])
return newList
def planeFromPoints(self, pts):
"""returns (base,normal) of pts by using pts[0], pts[mid], and pts[-1]
to find the plane defined by those 3 points"""
if len(pts) < 3:
raise Exception("planeFromPoints requires 3 or more points")
points = np.array([[v.x, v.y, v.z] for v in pts])
# Define the plane using the three points: first, mid, last
mid = int(len(pts)/2)
#print(f"points used: {points[0], points[mid], points[-1]}")
plane_origin = points[0]
plane_normal = np.cross(np.array(points[mid]) - np.array(points[0]), np.array(points[-1]) - np.array(points[0]))
plane_normal /= np.linalg.norm(plane_normal)
base = FreeCAD.Vector(plane_origin[0], plane_origin[1], plane_origin[2])
normal = FreeCAD.Vector(plane_normal[0], plane_normal[1], plane_normal[2])
return (base,normal)
def projectVectorToPlane(self, point, base, normal):
"""uses FreeCAD.Vectors, which are converted to numpy and returned as FreeCAD.Vector"""
pt = np.array(point)
b = np.array(base)
n = np.array(normal)
#print(f"point:{point},base:{base},normal:{normal}")
projected = self.projectPointToPlane(pt, b, n)
#print(f"projected: {projected}")
return FreeCAD.Vector(projected[0], projected[1], projected[2])
def projectPointToPlane(self, point, plane_origin, plane_normal):
"""project np point to np plane, return np array"""
# Calculate vector from the plane origin to the point
v = np.array(point) - np.array(plane_origin)
# Project the vector onto the plane
projected_v = v - np.dot(v, plane_normal) * plane_normal
# Calculate the new position of the point on the plane
projected_point = np.array(plane_origin) + projected_v
return projected_point.tolist()
def projectPointsToPlane(self, pts):
"""find the plane defined by the first 3 points in the points list, and then
project all remaining points to that plane using numpy"""
points = np.array([[v.x, v.y, v.z] for v in pts])
# Define the plane using the three points: first, mid, last
mid = int(len(pts)/2)
plane_origin = points[0]
plane_normal = np.cross(np.array(points[mid]) - np.array(points[0]), np.array(points[-1]) - np.array(points[0]))
plane_normal /= np.linalg.norm(plane_normal)
# Project all points onto the plane
projected_points = [self.projectPointToPlane(point, plane_origin, plane_normal) for point in points]
FCPoints = [FreeCAD.Vector(x,y,z) for x,y,z in projected_points]
return FCPoints
def flattenPoints(self, pts, align_plane):
""" project points to align_plane.
pts is list of Part.Vertex objects
align_plane is part::plane object or
can be any object with a face (face1 will be used)
returns: new list of Part.Vertex objects on the plane"""
plane = align_plane.Shape.Faces[0]
normal = plane.normalAt(0,0)
base = align_plane.Shape.Vertexes[0].Point
verts = []
flatPts = [] #eliminate duplicate points
pb = gu.MRProgress()
pb.makeProgressBar(len(pts),buttonText = "Cancel Phase1/2",tooltip="Cancel projecting points to plane")
for p in pts:
fpt = p.Point.projectToPlane(base,normal)
if not self.hasPoint(fpt,flatPts,epsilon):
flatPts.append(fpt)
if pb.isCanceled():
FreeCAD.Console.PrintWarning("Phase 1 / 2 canceled, object may be incomplete.\n")
break
pb.killProgressBar()
pb.makeProgressBar(len(flatPts),"Cancel Phase2/2")
for p in flatPts:
verts.append(Part.Vertex(p))
if pb.isCanceled():
FreeCAD.Console.PrintWarning("Phase 2 / 2 canceled, object may be incomplete.\n")
break
pb.killProgressBar()
return verts
def nearestPoint(self, pt, pts, exclude, skipOne = False):
""" nearestPoint(pt, pts, exclude)
pt is a vector, pts a list of vectors
exclude is a list of vectors to exclude from process
return nearest point to pt in pts and not in exclude
if skipOne is true, return 2nd closest point"""
if len(pts) == 0: #should never happen
raise Exception("MeshRemodel GeomUtils Error: nearestPoint() pts length = 0\n")
nearest = pts[0]
nextNearest = nearest
d = 10**100
for p in pts:
if p in exclude:
continue
dis = self.dist(pt, p)
if dis < d:
d = dis
nextNearest = nearest
nearest = p
return nearest if not skipOne else nextNearest
def isColinear(self,A,B,C):
""" isColinear(A, B, C)
determine whether vectors A,B,C are colinear """
return DraftVecUtils.isColinear([A,B,C])
def incenter(A,B,C):
""" incenter(A, B, C)
return incenter (vector) of triangle at vectors A,B,C
incenter is center of circle fitting inside the triangle
tangent to all 3 sides
raises exception if A,B,C are colinear
"""
if self.isColinear(A,B,C):
raise Exception("MeshRemodel Error: incenter() A,B,C are colinear")
Ax,Ay,Az = A[0],A[1],A[2]
Bx,By,Bz = B[0],B[1],B[2]
Cx,Cy,Cz = C[0],C[1],C[2]
a = self.dist(B,C)
b = self.dist(C,A)
c = self.dist(A,B)
s = a+b+c
Ix = (a*Ax+b*Bx+c*Cx)/s
Iy = (a*Ay+b*By+c*Cy)/s
Iz = (a*Az+b*Bz+c*Cz)/s
I = FreeCAD.Base.Vector(Ix,Iy,Iz)
return I
def inradius(A,B,C):
""" inradius(A, B, C)
return inradius of triangle A,B,C
this is radius of incircle, the circle that
fits inside the triangle, tangent to all 3 sides
"""
return self.dist(A, self.incenter(A,B,C))
#python code below was adapted from this javascript code
#from here: https://gamedev.stackexchange.com/questions/60630/how-do-i-find-the-circumcenter-of-a-triangle-in-3d
#in a question answered by user greenthings
#function circumcenter(A,B,C) {
# var z = crossprod(subv(C,B),subv(A,B));
# var a=vlen(subv(A,B)),b=vlen(subv(B,C)),c=vlen(subv(C,A));
# var r = ((b*b + c*c - a*a)/(2*b*c)) * outeradius(a,b,c);
# return addv(midpoint(A,B),multv(normaliz(crossprod(subv(A,B),z)),r));
#}
#function outeradius(a,b,c) { /// 3 lens
# return (a*b*c) / (4*sss_area(a,b,c));
#}
#function sss_area(a,b,c) {
# var sp = (a+b+c)*0.5;
# return Math.sqrt(sp*(sp-a)*(sp-b)*(sp-c));
# //semi perimeter
#}
def circumcenter(self,A,B,C):
""" circumcenter(A, B, C)
return the circumcenter of triangle A,B,C
the circumcenter is the circle that passes through
all 3 of the triangle's vertices
raises exception if A,B,C are colinear
"""
if self.isColinear(A,B,C):
raise Exception("MeshRemodel Error: circumcenter() A,B,C are colinear")
z = C.sub(B).cross(A.sub(B))
a = A.sub(B).Length
b = B.sub(C).Length
c = C.sub(A).Length
r = ((b*b + c*c - a*a)/(2*b*c)) * self.outerradius(a,b,c)
return A.sub(B).cross(z).normalize().multiply(r).add(self.midpoint(A,B))
def outerradius(self, a, b, c):
""" helper for circumcenter()"""
return (a*b*c) / (4*self.sss_area(a,b,c))
def sss_area(self,a,b,c): #semiperimeter
""" helper for circumcenter()"""
sp = (a+b+c)*0.5;
return math.sqrt(sp*(sp-a)*(sp-b)*(sp-c))
def circumradius(self, A,B,C):
""" circumradius(A, B, C)
returns the radius of circumcircle of triangle A,B,C
A,B,C are vectors
the circumcircle is the circle passing through A, B, and C
"""
return self.dist(A, self.circumcenter(A,B,C))
gu = MeshRemodelGeomUtils()
#######################################################################################
# Settings
class MeshRemodelSettingsCommandClass(object):
"""Settings"""
def __init__(self):
pass
def GetResources(self):
return {'Pixmap' : os.path.join( iconPath , 'Settings.svg') , # the name of an icon file available in the resources
'MenuText': "&Settings" ,
'ToolTip' : "Workbench settings dialog"}
def Activated(self):
doc = FreeCAD.ActiveDocument
from PySide import QtGui
window = QtGui.QApplication.activeWindow()
pg = FreeCAD.ParamGet("User parameter:Plugins/MeshRemodel")
pg.RemInt("SketchRadiusPrecision") #no longer used
keep = pg.GetBool('KeepToolbar',False)
point_size = pg.GetFloat("PointSize", 4.0)
line_width = pg.GetFloat("LineWidth", 5.0)
checkUpdates = pg.GetBool("CheckForUpdates", True)
pg.SetBool("CheckForUpdates", checkUpdates)
coplanar_tol = pg.GetFloat("CoplanarTolerance",.01)
wireframe_tol = pg.GetFloat("WireFrameTolerance",.01)
items=[("","*")[keep]+"Keep the toolbar active",
("","*")[not keep]+"Do not keep the toolbar active",
("","*")[checkUpdates]+"Check for updates",
("","*")[not checkUpdates]+"Do not check for updates",
"Change point size ("+str(point_size)+")",
"Change line width ("+str(line_width)+")",
"Change coplanar tolerance ("+str(coplanar_tol)+")",
"Change wireframe tolerance("+str(wireframe_tol)+")",
"Cancel"]
item,ok = QtGui.QInputDialog.getItem(window,'Mesh Remodel v'+__version__,'Settings\n\nSelect the settings option\n',items,0,False,windowFlags)
if ok and item == items[-1]:
return
elif ok and item == items[0]:
keep = True
pg.SetBool('KeepToolbar', keep)
elif ok and item==items[1]:
keep = False
pg.SetBool('KeepToolbar', keep)
elif ok and item==items[4]:
new_point_size,ok = QtGui.QInputDialog.getDouble(window,"Point size", "Enter point size", point_size,1,50,2)
if ok:
pg.SetFloat("PointSize", new_point_size)
elif ok and item==items[5]:
new_line_width,ok = QtGui.QInputDialog.getDouble(window,"Line width", "Enter line width", line_width,1,50,2)
if ok:
pg.SetFloat("LineWidth", new_line_width)
elif ok and item==items[2]:
checkUpdates = True
pg.SetBool("CheckForUpdates", True)
elif ok and item==items[3]:
checkUpdates = True
pg.SetBool("CheckForUpdates", False)
elif ok and item==items[5]:
new_coplanar_tol, ok = QtGui.QInputDialog.getDouble(window,"Coplanar tolerance", "Enter coplanar tolerance\n(Used when creating coplanar points. Increase if some points are missing.)", coplanar_tol,.0000001,1,8)
if ok:
pg.SetFloat("CoplanarTolerance", new_coplanar_tol)
elif ok and item==items[6]:
new_wireframe_tol, ok = QtGui.QInputDialog.getDouble(window,"Wireframe tolerance", "Enter wireframe tolerance\n(Used when creating wireframes to check if 2 points are the same.)", wireframe_tol,.0000001,1,8)
if ok:
pg.SetFloat("WireFrameTolerance", new_wireframe_tol)
return
def IsActive(self):
return True
#end settings class
####################################################################################
# Create the Mesh Remodel Points Object
class PointsObject:
"""Part::FeaturePython object to serve as proxy for mesh object so we can have
selectable points to work with"""
def __init__(self, obj, meshObj=None, className="PointsObject"):
obj.Proxy = self
obj.addProperty("App::PropertyLink","Source",className,"Source mesh document object").Source = meshObj
obj.addProperty("App::PropertyString", "OriginalDisplayMode",className,\
"Used to restore mesh to original display mode upon deleting points object").OriginalDisplayMode=\
meshObj.ViewObject.DisplayMode if meshObj else "Shaded"
obj.addProperty("App::PropertyBool", "OriginalSelectable", className, \
"Used to restore mesh to original Selectable status after deleting points object")\
.OriginalSelectable = meshObj.ViewObject.Selectable if meshObj else True
obj.setEditorMode("OriginalDisplayMode", 2) #hidden
obj.setEditorMode("OriginalSelectable", 2)
obj.addProperty("App::PropertyBool","FlatLines",className,\
"Whether to show mesh object in Flat Lines mode").FlatLines = True
obj.addProperty("App::PropertyBool","OneSideLighting",className,\
"Whether to set mesh object Lighting to 'One side'").OneSideLighting = True
obj.addProperty("App::PropertyFloat","PointSize", className,\
"Size of the points in pixels, changing also changes value in settings"\
).PointSize=self.PointSize
obj.addProperty("App::PropertyInteger","Transparency",className,\
"Transparency of Source object").Transparency = 25
obj.addProperty("App::PropertyBool", "Selectable", className, \
"Toggle to false to make the mesh object non-selectable").Selectable = False
@property
def PointSize(self):
"""manage parameter"""
pg = FreeCAD.ParamGet("User parameter:Plugins/MeshRemodel")
point_size = pg.GetFloat("PointSize",4.0)
return point_size
@PointSize.setter
def PointSize(self, psize):
"""manager parameter"""
pg = FreeCAD.ParamGet("User parameter:Plugins/MeshRemodel")
pg.SetFloat("PointSize", psize)
def onChanged(self, fp, prop):
if prop == "OneSideLighting" and fp.Source != None:
if fp.OneSideLighting:
fp.Source.ViewObject.Lighting = "One side"
else:
fp.Source.ViewObject.Lighting = "Two side"
elif prop == "FlatLines" and fp.Source != None:
if fp.FlatLines:
fp.Source.ViewObject.DisplayMode = "Flat Lines"
else:
fp.Source.ViewObject.DisplayMode = "Shaded"
elif prop == "PointSize":
fp.ViewObject.PointSize = fp.PointSize
self.PointSize = fp.PointSize
elif prop == "Selectable":
if hasattr(fp,"Source"):
fp.Source.ViewObject.Selectable = fp.Selectable
def execute(self, fp):
if not fp.Source:
fp.Shape = Part.Shape()
return
doc = fp.Document
pts=[]
if hasattr(fp.Source,"Mesh"):
meshpts =fp.Source.Mesh.Points
for m in meshpts:
p = Part.Point(m.Vector)
pts.append(p.toShape())
#print(f"pts = {pts}")
fp.Shape = Part.makeCompound(pts)
fp.ViewObject.PointSize = fp.PointSize
fp.Source.ViewObject.Transparency = fp.Transparency
def refresh(self, fp):
"""when the mesh changes we don't always get the usual touched notification,
such as when a point is moved or a facet is added. This is good because if
a point is accidentally removed when removing facets the point structure will
still be there in the points object proxy, at least until the user manually
refreshes via this function
"""
if not fp.Source:
return
fp.Source.touch()
fp.Document.openTransaction("Recompute points object")
fp.Document.recompute()
fp.Document.commitTransaction()
def evaluate(self, fp):
"""evaluate the Source object in mesh workbench"""
curWB = Gui.activeWorkbench().name()
Gui.activateWorkbench("MeshWorkbench")
Gui.activateWorkbench(curWB)
Gui.Selection.clearSelection()
Gui.Selection.addSelection(fp.Source)
Gui.runCommand("Mesh_Evaluation", 0)
def harmonizeNormals(self, fp):
"""harmonize normals of source object"""
copy = fp.Source.Mesh.copy()
copy.rebuildNeighbourHood()
copy.fixIndices()
copy.harmonizeNormals()
fp.Document.openTransaction("Harmonize normals")
fp.Source.Mesh = copy
fp.Document.commitTransaction()
def flipNormals(self, fp):
"""flip the normals of the source mesh object"""
copy = fp.Source.Mesh.copy()
copy.flipNormals()
fp.Document.openTransaction("Flip normals")
fp.Source.Mesh = copy
fp.Document.commitTransaction()
class PointsObjectVP:
"""view provider for PointsObject object"""
def __init__(self, vobj):
vobj.Proxy = self
def getIcon(self):
return os.path.join( iconPath , 'CreatePointsObject.svg')
def attach(self, vobj):
self.Object = vobj.Object
def claimChildren(self):
return [self.Object.Source]
def setupContextMenu(self, vobj, menu):
refresh_action = menu.addAction(f"Recompute {vobj.Object.Label}")
refresh_action.triggered.connect(lambda: vobj.Object.Proxy.refresh(vobj.Object))
evaluate_action = menu.addAction(f"Evaluate {vobj.Object.Source.Label} for defects")
evaluate_action.triggered.connect(lambda: vobj.Object.Proxy.evaluate(vobj.Object))
harmonize_action = menu.addAction(f"Harmonize Normals")
harmonize_action.triggered.connect(lambda: vobj.Object.Proxy.harmonizeNormals(vobj.Object))
flip_action = menu.addAction(f"Flip Normals")
flip_action.triggered.connect(lambda: vobj.Object.Proxy.flipNormals(vobj.Object))
def onDelete(self, vobj, subelements):
vobj.Object.Source.ViewObject.DisplayMode = vobj.Object.OriginalDisplayMode
vobj.Object.Source.ViewObject.Selectable = vobj.Object.OriginalSelectable
return True
def setEdit(self, vobj, modNum):
pass
def __getstate__(self):
'''When saving the document this object gets stored using Python's json module.\
Since we have some un-serializable parts here -- the Coin stuff -- we must define this method\
to return a tuple of all serializable objects or None.'''
return {"name": self.Object.Name}
def __setstate__(self,state):
'''When restoring the serialized object from document we have the chance to set some internals here.\
Since no data were serialized nothing needs to be done here.'''
self.Object = FreeCAD.ActiveDocument.getObject(state["name"])
return None
class MeshRemodelCreatePointsObjectCommandClass(object):
"""Create Points Object command"""
def __init__(self):
self.mesh = None
def GetResources(self):
return {'Pixmap' : os.path.join( iconPath , 'CreatePointsObject.svg') ,
'MenuText': "Create points &object" ,
'ToolTip' :
"""Create a parametric PointsObject linked to the selected mesh object. The points
object serves as a proxy for the mesh object. We can easily select the points of
the points object whereas selecting directly the points of a mesh object is not
supported in FreeCAD. See also the WireFrame object, which serves a similar role,
but that also has selectable edges that can be used in conjunction with the add or
remove facet tool.
The advantage of the points object over the wireframe object is it is much faster
to recompute when working with complex meshes with many points and facets. Also,
the way the WireFrame selection of edges works is the 2 vertices of the edge are
added to the points list kept in memory, but the order the vertices are added is
undefined, meaning you have less control over the order of selection for the vertices
when using the wireframe edge selection for adding multiple facets in one go. For
that operation it is highly recommended to select the vertices.
Tip: Select the vertices in counter-clockwise fashion to get the facet oriented
with the normal side outward when adding new facets to a mesh object.
"""}
def Activated(self):
doc = self.mesh.Document
if hasattr(self.mesh,"Mesh"): #might be a points workbench object
gu.checkComponents(self.mesh.Mesh)
elif hasattr(self.mesh,"Points") and hasattr(self.mesh.Points,"Points"):
#for a points cloud we just create the old non-parametric object
meshpts = self.mesh.Points.Points
pts = []
for m in meshpts:
p = Part.Point(m)
pts.append(p.toShape())
doc.openTransaction("Create points object")
ptsobj = doc.addObject("Part::Feature","PointsObject")
ptsobj.Shape = Part.Compound(pts)
pg = FreeCAD.ParamGet("User parameter:Plugins/MeshRemodel")
point_size = pg.GetFloat("PointSize",4.0)
ptsobj.ViewObject.PointSize = point_size
self.mesh.ViewObject.Visibility = False
doc.commitTransaction()
#create new empty mesh
doc.openTransaction("Make empty mesh")
meshobj = doc.addObject("Mesh::Feature", self.mesh.Label)
meshobj.Mesh = Mesh.Mesh()
meshobj.ViewObject.DisplayMode = "Flat Lines"
meshobj.ViewObject.Lighting = "One side"
doc.commitTransaction()
return
doc.openTransaction("Create points object")
fp = doc.addObject("Part::FeaturePython","PointsObject")
PointsObject(fp, self.mesh)
PointsObjectVP(fp.ViewObject)
doc.commitTransaction()
doc.recompute()
return
def IsActive(self):
if not FreeCAD.ActiveDocument:
return False
sel = Gui.Selection.getSelection()
if len(sel) == 0:
return False
if not bool(sel[0].isDerivedFrom("Mesh::Feature") or sel[0].isDerivedFrom("Points::Feature")):
return False
self.mesh = sel[0]
return True
# end create points class
####################################################################################
# Create the Mesh Remodel WireFrame Object
class WireFrameObject(PointsObject):
def __init__(self, obj, meshObj, className):
super(WireFrameObject, self).__init__(obj, meshObj, className)
obj.FlatLines = False
def execute(self, fp):
if not fp.Source:
return
mesh = fp.Source.Mesh.copy()
lines = []
for facet in mesh.Facets:
pt1 = FreeCAD.Vector(facet.Points[0])
pt2 = FreeCAD.Vector(facet.Points[1])
pt3 = FreeCAD.Vector(facet.Points[2])
try:
line1 = Part.LineSegment(pt1, pt2).toShape()
line2 = Part.LineSegment(pt2, pt3).toShape()
line3 = Part.LineSegment(pt3, pt1).toShape()
lines.extend([line1, line2, line3])
except:
pass
# this works, but takes too long, and if we multiFuse
# then that resolves the self-intersections, anyway
# if not gu.hasLine(line1, lines, 1e-6):
# lines.append(line1)
# if not gu.hasLine(line2, lines, 1e-6):
# lines.append(line2)
# if not gu.hasLine(line3, lines, 1e-6):
# lines.append(line3)
if len(lines) > 1 and len(lines) < 10000:
fp.Shape = lines[0].multiFuse(lines[1:])
elif len(lines) > 1 and len(lines) > 10000:
FreeCAD.Console.PrintWarning(\
"""Compounding WireFrame rather than fusing since there are more than 10,000 edges.
""")
fp.Shape = Part.Compound(lines)
else:
fp.Shape = Part.Shape()
class WireFrameObjectVP(PointsObjectVP):
def __init__(self, vobj):
super(WireFrameObjectVP, self).__init__(vobj)
def getIcon(self):
return os.path.join( iconPath , 'CreateWireFrameObject.svg')
class MeshRemodelCreateWireFrameObjectCommandClass(object):
"""Create WireFrame Object command"""
def __init__(self):
self.mesh = None
self.pb = None
self.btn = None
self.bar = None
self.bCanceled = False
def GetResources(self):
return {'Pixmap' : os.path.join( iconPath , 'CreateWireFrameObject.svg') ,
'MenuText': "Create Wire&Frame object" ,
'ToolTip' : \
"""Create a parametric WireFrame object. The wireframe will be bound to the mesh
object and can be used as a proxy for the mesh object's edges and vertices, which
can be selected for use with the various mesh editing tools in MeshRemodel:
Add or remove facet(s)
Move point
Remove point
Note that the wire frame object does not automatically recompute when changes are
made to the underlying mesh object. You can do a manual recompute via the wire frame
object's context menu. Recomputing can take a long time depending on the complexity
of the mesh and it can also be useful to have the points and edges available after
removing them from the mesh object in order to add them back as a means of curing
defects.
"""}
def Activated(self):
gu.checkComponents(self.mesh.Mesh)
doc = self.mesh.Document
doc.openTransaction("Create WireFrame object")
fp = doc.addObject("Part::FeaturePython","WireFrameObject")
WireFrameObject(fp, self.mesh,"WireFrameObject")
WireFrameObjectVP(fp.ViewObject)
doc.commitTransaction()
doc.recompute()
return
def IsActive(self):
if not FreeCAD.ActiveDocument:
return False
sel = Gui.Selection.getSelection()
if len(sel) == 0:
return False
if not sel[0].isDerivedFrom("Mesh::Feature"):
return False
self.mesh = sel[0]
return True
# end create WireFrame class
################################################################################
#MeshBoundaryWires
class MeshRemodelMeshBoundaryWiresCommandClass(object):
def __init__(self):
self.mesh = None
def GetResources(self):
return {'Pixmap' : os.path.join( iconPath , 'MeshBoundaryWires.svg'),
'MenuText': "Makes boundary wire objects from meshes with holes in them" ,
'ToolTip' : \
"""Makes boundary wire objects from meshes with holes in them. The wires produced
are not parametric and might or might not be planar. A mesh without any holes,
meaning no missing facets, will not produce any wires.
This tool can be used to detect holes that might not be easily visible upon brief
inspection. Can also aid in diagnosing otherwise difficult to find problem areas,
such as 2 points in very close proximity that are causing self-intersections.
If you have trimmed a mesh with a plane in Mesh workbench, then this can help to
fill the hole that was created by that process.
If a planar wire can be produced, then a mesh face will also be created from it
and added as a new document object. You can merge the face with the mesh in the
Mesh workbench. After merging use the analyze, evaluate, and repair tool to remove
the duplicated points and to check for any additional defects that might exist.
Shift+Click to attempt to make faces out of nonplanar wires. (This can sometimes
take a long time, so save your work first in case you have to force restart.)
"""}
def Activated(self):
copy = self.mesh.Mesh.copy()
wires = MeshPart.wireFromMesh(copy)
FreeCAD.Console.PrintMessage(f"MeshRemodel: {len(wires)} wires created\n")
doc = self.mesh.Document
modifiers = QtGui.QApplication.keyboardModifiers()
if modifiers & QtCore.Qt.ShiftModifier:
makeFilledFaces = True
else:
makeFilledFaces = False
if not wires:
return
doc.openTransaction("Mesh boundary wires")
for idx,wire in enumerate(wires):
FreeCAD.Console.PrintMessage(f"Making face from wire {idx+1} of {len(wires)}\n")
FreeCADGui.updateGui()
obj = doc.addObject("Part::Feature", f"{self.mesh.Label}_BoundaryWire")
obj.Shape = wire
plane = wire.findPlane()
face = None
if plane:
face = Part.makeFace(wire,"Part::FaceMakerBullseye")
elif makeFilledFaces:
try:
face = Part.makeFilledFace(wire.Edges)
except:
face = None
else:
FreeCAD.Console.PrintMessage(f"skipping wire {idx+1} of {len(wires)} because it is nonplanar, Shift+CLick to force trying to make filled face (might take a long time, so save your work first.)\n")
if face:
mface = MeshPart.meshFromShape(face, 0.25, 50)
mobj = doc.addObject("Mesh::Feature",f"{self.mesh.Label}_MeshFace")
mobj.Mesh = mface
doc.commitTransaction()
doc.recompute()
FreeCAD.Console.PrintMessage("Done with Boundary Wires command\n")
def IsActive(self):
if not FreeCAD.ActiveDocument:
return False
self.mesh = None
sel = Gui.Selection.getSelection()
self.mesh = sel[0] if len(sel) == 1 else None
if self.mesh and self.mesh.isDerivedFrom("Mesh::Feature"):
return True
return False
################################################################################
#create a simple copy of a mesh object
class MeshRemodelMeshSimpleCopyCommandClass(object):
"""creates a simple copy of a mesh object"""
def __init__(self):
self.mesh = None
def GetResources(self):
return {'Pixmap' : os.path.join( iconPath , 'MeshSimpleCopy.svg'),
'MenuText': "Create a simple copy of a mesh object or a new empty mesh" ,
'ToolTip' : \
"""Create a simple copy of a mesh object. If no mesh is selected, then a new