-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMatrixTransformer.py
352 lines (295 loc) · 14.1 KB
/
MatrixTransformer.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
import vedo as v
import vtk
import numpy as np
from PyQt6 import QtCore
from PyQt6.QtCore import QObject, QThread, pyqtSignal
MODE_GUI = False
def debug(str):
if MODE_GUI:
main.console(str)
else:
print(str)
from Transformation import *
from RenderContainer import *
class MatrixTransformer(QtCore.QObject):
def __init__(self, rcFP=None, rcRender=None):
super().__init__()
if rcFP is None:
rcFP = RenderContainer()
elif type(rcFP) is v.Plotter:
rcFP = RenderContainer(rcFP)
if rcRender is None:
rcRender = RenderContainer()
elif type(rcFP) is v.Plotter:
rcRender = RenderContainer(rcRender)
self.rcFP = rcFP
self.rcRender = rcRender
self.points = []
self.layers = []
self.nlayers = 0
self.transformations = []
self.mel = None
self.debugOutput = []
self.fixed_scope = None
self.fixed_mesh = []
self.fixedPts = []
self.transformedPts = []
self.xmin, self.xmax = (0, 0)
self.ymin, self.ymax = (0, 0)
self.zmin, self.zmax = (0, 0)
progress = QtCore.pyqtSignal(int)
status = QtCore.pyqtSignal(str)
def update_progress(self, cur, max):
self.progress.emit(int(cur / max * 100))
def add_transformation(self, tr):
trId = len(self.transformations)
self.transformations.append(tr)
tr.parent = self
if tr.addResidual:
res = tr.getResidualTransformation()
debug(" - adding Residual {}".format(res))
self.add_transformation(res)
def add_layer(self, layer):
self.layers.append(layer)
xmin, xmax = layer.mesh.xbounds()
ymin, ymax = layer.mesh.ybounds()
zmin, zmax = layer.mesh.zbounds()
self.xmin = min(self.xmin, xmin)
self.xmax = max(self.xmax, xmax)
self.ymin = min(self.ymin, ymin)
self.ymax = max(self.ymax, ymax)
self.zmin = min(self.zmin, zmin)
self.zmax = max(self.zmax, zmax)
self.nlayers += 1
def visualize(self):
debug("\n-------------------------\n----- VISUALIZING -----\n-------------------------")
self.status.emit("Visualizing...")
self.progress.emit(0)
meshes = [l.mesh for l in self.layers]
for layer in self.layers:
self.rcFP.add_layer(layer.name, layer.mesh.clone().c("grey"))
trId = 0
if len(self.transformations) > 0:
while trId < len(self.transformations):
tr = self.transformations[trId]
debug(tr)
self.status.emit("Visualizing Transformation {}/{}".format(trId, len(self.transformations)))
self.update_progress(trId + 1, len(self.transformations))
debug("{} meshes found".format(len(tr.meshes)))
area = tr.getArea().extrude(3).z(-1.5).c("green").alpha(0.2)
self.rcFP.add_transformation(tr.name + "_outline", tr.getOutline().c("yellow7"))
self.rcFP.add_transformation(tr.name + "_area", area.clone(), False)
self.rcRender.add_transformation(tr.name + "_area", area.clone(), True)
if len(tr.meshes) > 0:
self.rcRender.add_layer(tr.name + "_slice", v.merge(tr.meshes).alpha(1).c("blue"), False)
if tr.addResidual:
if len(self.transformations[trId + 1].meshes) > 0:
self.rcRender.add_layer(tr.name + "-Res_slice",
v.merge(self.transformations[trId + 1].meshes).alpha(1).c("green"), False)
trId += 2 # skip next transformation as we did it as a residual here
else:
trId += 1 # next transformation
else:
print("No Transformations found to visualize.")
if len(self.fixed_mesh) > 0:
self.rcRender.add_layer("Mesh_Fixed", v.merge(self.fixed_mesh).alpha(1).c("red"), True)
def calculate_assignments(self, onlybaselayer=False):
scope_residual = None
for layerId, layer in enumerate(self.layers):
if layerId == 0:
debug("\nCalculating assignments. Layer #0 seen as substrate to generate transformation scopes...")
part = layer.mesh.clone()
trId = 0
while trId < len(self.transformations):
tr = self.transformations[trId]
debug("-> Transformation #{}: {}".format(trId, tr))
self.status.emit("Calculating Assignments... Layer {}/{}, Transformation {}/{}".format(layerId + 1,
len(self.layers),
trId + 1,
len(self.transformations)))
self.update_progress(layerId * len(self.layers) + trId, len(self.transformations))
outline = tr.getOutline()
mesh_transformed, part = cut_with_line(part, outline, closed=True)
v.write(mesh_transformed, "_mesh_transformed.stl")
v.write(part, "_part.stl")
ol_gop = tr.getOutlinePts()
scope_transformed = get_contour_scope(mesh_transformed)
tr.scope = scope_transformed
tr.meshes.append(mesh_transformed.clone())
tr.mel.append(layer.mel_trans)
self.rcFP.add_transformation(tr.name + "_mesh", scope_transformed.clone().c("blue").alpha(0.2),
False)
fixedMeshes = []
residualMeshes = []
split = part.split()
p0, p1 = tr.getBorderlinePts()
self.rcFP.add_debug(tr.name + "_borderline", v.Line(tr.getBorderlinePts()).lw(2).c("red"), False)
for prt in split:
if prt.intersect_with_line(p0, p1).any():
fixedMeshes.append(prt)
else:
residualMeshes.append(prt)
part = v.merge(fixedMeshes)
#TODO: if fixedmesh is Null, there might be a problem with geometries
if tr.addResidual and len(residualMeshes) > 0:
residual = v.merge(residualMeshes)
scope_residual = get_contour_scope(residual)
self.transformations[trId + 1].scope = scope_residual
self.transformations[trId + 1].meshes.append(residual)
self.transformations[trId + 1].mel.append(layer.mel_residual)
if tr.addResidual:
debug(" Skipping residual Transformation #{}: {}\n".format(trId + 1,
self.transformations[trId + 1]))
trId += 2 # skip next transformation as we did it as a residual here
else:
trId += 1 # next transformation
self.fixed_mesh.append(part)
self.fixed_scope = get_contour_scope(part)
# TODO accessing fixed_scope causes error
debug("Base layer done.\n")
continue
if onlybaselayer:
break
debug("Calculating {} assignments for layer #{}".format(len(self.transformations), layerId))
mesh_fixed = layer.mesh.clone()
trId = 0
while trId < len(self.transformations):
tr = self.transformations[trId]
debug("-> Transformation #{}: {}".format(trId, tr))
mesh_transformed, mesh_fixed, mesh_residual = split_with_transformation(self, mesh_fixed, tr)
self.debugOutput.append(mesh_transformed.clone().z(20).c("blue"))
debug(" -> Slice successful.")
tr.meshes.append(mesh_transformed.clone())
tr.mel.append(layer.mel_trans)
self.debugOutput.append(v.Line(tr.getBorderlinePts()).lw(2).c("red"))
if tr.addResidual and mesh_residual is not None and mesh_residual.npoints > 0:
debug(" -> Adding residual....")
self.transformations[trId + 1].meshes.append(mesh_residual)
self.transformations[trId + 1].mel.append(layer.mel_residual)
self.debugOutput.append(scope_residual.clone().c("green").alpha(0.2))
if tr.addResidual:
debug(" Skipping residual Transformation #{}: {}\n".format(trId + 1,
self.transformations[trId + 1]))
trId += 2 # skip next transformation as we did it as a residual here
else:
trId += 1 # next transformation
self.debugOutput.append(mesh_transformed.clone().c("blue"))
debug(" Transformation done.\n")
if mesh_fixed is not None:
self.fixed_mesh.append(mesh_fixed)
else:
self.fixed_mesh.append(None)
def getPointId(self, pt, meshNum):
# return self.mesh[meshNum].closest_point(pt, 1, return_point_id=True)
return self.layers[meshNum].mesh.closest_point(pt, 1, return_point_id=True)
def start_transformation(self):
for tr in self.transformations:
for meshNum in range(len(tr.meshes)):
mesh = tr.get_preprocessed_mesh(meshNum)
mats = []
if tr.transformWholeMesh: # Transformation implemented a method to the whole transformation on its own
mesh = tr.transformMesh(mesh)
else:
points = mesh.points()
for pid, pt in enumerate(points):
self.update_progress(pid, len(points))
vec = np.array([pt[0], pt[1], pt[2], 1])
vec = np.dot(tr.getMatrixAt(pt), vec)
points[pid][0] = vec[0]
points[pid][1] = vec[1]
points[pid][2] = vec[2]
mesh.points(points)
tr.meshes[meshNum] = mesh
self.debugOutput.append(mesh)
def get_result_mesh(self):
for trId, tr in enumerate(self.transformations):
for meshNum, mesh in enumerate(tr.meshes):
print("--------> Got {}_{}-tr'ed".format(self.layers[meshNum].name, tr.name))
self.rcRender.add_layer("{}_{}-tr'ed".format(self.layers[meshNum].name, tr.name), mesh.alpha(1).c(self.layers[meshNum].color), True)
meshes = [v.merge(tr.meshes) for tr in self.transformations]
meshes = [e for e in meshes if e is not None]
meshes.append(v.merge(self.fixed_mesh))
ret = v.merge(meshes)
return ret
def cut_with_line(mesh, points, invert=False, closed=True, residual=True):
mesh = mesh.clone()
pplane = vtk.vtkPolyPlane()
if isinstance(points, v.Points):
points = points.points().tolist()
if closed:
if isinstance(points, np.ndarray):
points = points.tolist()
points.append(points[0])
vpoints = vtk.vtkPoints()
for p in points:
if len(p) == 2:
p = [p[0], p[1], 0.0]
vpoints.InsertNextPoint(p)
n = len(points)
polyline = vtk.vtkPolyLine()
polyline.Initialize(n, vpoints)
polyline.GetPointIds().SetNumberOfIds(n)
for i in range(n):
polyline.GetPointIds().SetId(i, i)
pplane.SetPolyLine(polyline)
currentscals = mesh.polydata().GetPointData().GetScalars()
if currentscals:
currentscals = currentscals.GetName()
clipper = vtk.vtkClipPolyData()
clipper.SetInputData(mesh.polydata(True)) # must be True
clipper.SetClipFunction(pplane)
clipper.SetInsideOut(invert)
clipper.GenerateClippedOutputOn()
clipper.GenerateClipScalarsOff()
clipper.SetValue(0)
clipper.Update()
cpoly = clipper.GetOutput(0)
kpoly = clipper.GetOutput(1)
vis = False
if currentscals:
cpoly.GetPointData().SetActiveScalars(currentscals)
vis = mesh.mapper().GetScalarVisibility()
if mesh.GetIsIdentity() or cpoly.GetNumberOfPoints() == 0:
mesh._update(cpoly)
else:
# bring the underlying polydata to where _data is
M = vtk.vtkMatrix4x4()
M.DeepCopy(mesh.GetMatrix())
M.Invert()
tr = vtk.vtkTransform()
tr.SetMatrix(M)
tf = vtk.vtkTransformPolyDataFilter()
tf.SetTransform(tr)
tf.SetInputData(cpoly)
tf.Update()
mesh._update(tf.GetOutput())
mesh.pointdata.remove("SignedDistances")
mesh.mapper().SetScalarVisibility(vis)
cutoff = v.Mesh(kpoly)
cutoff.property = vtk.vtkProperty()
cutoff.property.DeepCopy(mesh.property)
cutoff.property.DeepCopy(mesh.property)
cutoff.SetProperty(cutoff.property)
return mesh, cutoff
def split_with_transformation(self, mesh, tr):
mesh_transformed, part = cut_with_line(mesh.clone(), tr.getOutline())
fixedMeshes = []
residualMeshes = []
split = part.split()
debug(" -> Splitting {} parts...".format(len(split)))
for prt in split:
inter = len(self.fixed_scope.inside_points(prt.points()).points())
# debug(" Intersecting points: {}".format(inter)) # TODO: Check for bounding box intersections
if inter:
fixedMeshes.append(prt)
else:
residualMeshes.append(prt)
mesh_fixed = v.merge(fixedMeshes)
mesh_residual = v.merge(residualMeshes)
return mesh_transformed, mesh_fixed, mesh_residual
def get_contour_scope(mesh):
newMesh = mesh.clone()
newMesh.clean()
contour = newMesh.project_on_plane('z')
extrude = contour.clean().extrude(4, cap=True).z(-2)
return extrude