-
Notifications
You must be signed in to change notification settings - Fork 0
/
mp_VTKRoutines.py
executable file
·391 lines (281 loc) · 14 KB
/
mp_VTKRoutines.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
#!/usr/bin/python
'''
VTK engine room for mrMeshPy viewer
The main vtk processing is done by functions here - although some hardcore
processing is handled in subroutines of other imported modules.
A core concept here is the tracking (kepping in scope) or the "targetVTKWindow"
- this is a vtkRenderWindowInteractor instance in the main program UI (user
interface) - by creatoing multiple instances of vtk windows we can load
multiple meshes. Some functions reference this specifically with a reference
index passed from mrVista --- mainWindowUI.vtkInstances[int(theMeshInstance)]
while others just referene the most recently added instance (e.g. when adding
a new mesh) --- mainWindowUI.vtkInstances[-1]
Note that it is the mainWindowUI that is passed to all functions so that all
funcitons have the content of the main window in scope.
Andre' Gouws 2017
'''
import vtk
from numpy import *
import time
from vtk.util import numpy_support
debug = True
# local modules
from mp_unpackIncomingData import unpackData
from mp_VTKProcessing import *
from mp_VTKDrawing import *
def loadNewMesh(currVTKInstance, commandArgs, mainWindowUI, the_TCPserver):
#first get all the data we are expecting from the server
## NB this assumes that the order of sending by the server is
# 1) vertices
# 2) triangles
# 3) color data r (rgba) for each vertex
# 4) color data g (rgba) for each vertex
# 5) color data b (rgba) for each vertex
# 6) color data a (rgba) for each vertex
if debug:
print('received request for new mesh with Args:')
print(commandArgs)
# sanity check
if ('vertices' in commandArgs[0]) and ('triangles' in commandArgs[1]):
pass
else:
return "error - expecting vertices, then triangles!"
# load the surfaces data
verticesArgs = commandArgs[0].strip().split(',')
vertices = unpackData(verticesArgs[1], int(verticesArgs[2]), the_TCPserver)
vertices = array(vertices,'f')
vertices = vertices.reshape((len(vertices)/3,3))
trianglesArgs = commandArgs[1].strip().split(',')
triangles = unpackData(trianglesArgs[1], int(trianglesArgs[2]), the_TCPserver)
triangles = array(triangles,'f')
if debug: print(triangles)
triangles = triangles.reshape((len(triangles)/3,3))
if debug: print(triangles)
# load the surface colour data
rVecArgs = commandArgs[2].strip().split(',')
r_vec = unpackData(rVecArgs[1], int(rVecArgs[2]), the_TCPserver)
r_vec = array(r_vec,'uint8')
if debug: print(r_vec)
gVecArgs = commandArgs[3].strip().split(',')
g_vec = unpackData(gVecArgs[1], int(gVecArgs[2]), the_TCPserver)
g_vec = array(g_vec,'uint8')
bVecArgs = commandArgs[4].strip().split(',')
b_vec = unpackData(bVecArgs[1], int(bVecArgs[2]), the_TCPserver)
b_vec = array(b_vec,'uint8')
aVecArgs = commandArgs[5].strip().split(',')
a_vec = unpackData(aVecArgs[1], int(aVecArgs[2]), the_TCPserver)
a_vec = array(a_vec,'uint8')
if debug:
print(len(r_vec))
print(len(g_vec))
print(len(b_vec))
print(len(a_vec))
#combine into numpy array
colorDat = squeeze(array(squeeze([r_vec,g_vec,b_vec,a_vec]),'B',order='F').transpose())
# convert this to a VTK unsigned char array
scalars = numpy_support.numpy_to_vtk(colorDat,0)
curr_scalars = vtk.vtkUnsignedCharArray()
curr_scalars.DeepCopy(scalars)
## ---- ok, we hav the data, lets turn it into vtk stuff
# Process vertices
points = vtk.vtkPoints()
for i in range(vertices.shape[0]):
points.InsertPoint(i,vertices[i][0],vertices[i][1],vertices[i][2])
# Process faces (triangles)
polys = vtk.vtkCellArray()
nTriangles = triangles.shape[0]
for i in range(nTriangles):
polys.InsertNextCell(3)
for j in range(3):
polys.InsertCellPoint(int(triangles[i][j]))
# check
if debug: print(points)
if debug: print(polys)
if debug: print(scalars)
if debug: print(currVTKInstance)
# Assemble as PolyData
polyData = vtk.vtkPolyData()
polyData.SetPoints(points)
polyData.SetPolys(polys)
polyData.GetPointData().SetScalars(scalars)
## TODO ? smoothing on first load?
smooth = vtk.vtkSmoothPolyDataFilter()
smooth = vtk.vtkSmoothPolyDataFilter()
smooth.SetNumberOfIterations(0)
smooth.SetRelaxationFactor(0.0)
smooth.FeatureEdgeSmoothingOff()
smooth.SetInputData(polyData)
pdm = vtk.vtkPolyDataMapper()
pdm.SetScalarModeToUsePointData()
pdm.SetInputConnection(smooth.GetOutputPort())
actor = vtk.vtkActor()
actor.SetMapper(pdm)
iren = mainWindowUI.vtkInstances[-1]
## ---- engine room for drawing on the surface
# add a picker that allows is top pick points on the surface
picker = vtk.vtkCellPicker()
picker.SetTolerance(0.0001)
mainWindowUI.vtkInstances[-1].SetPicker(picker)
mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds = [] #place holder for picked vtk point IDs so we can track
mainWindowUI.vtkInstances[-1].pickedPointIds = mainWindowUI.vtkInstances[-1]._Iren.pickedPointIds
mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues = [] #place holder for picked vtk point IDs so we can track
mainWindowUI.vtkInstances[-1].pickedPointOrigValues = mainWindowUI.vtkInstances[-1]._Iren.pickedPointOrigValues
mainWindowUI.vtkInstances[-1]._Iren.pickedPoints = vtk.vtkPoints() #place holder for picked vtk point IDs so we can track
mainWindowUI.vtkInstances[-1].pickedPoints = mainWindowUI.vtkInstances[-1]._Iren.pickedPoints
mainWindowUI.vtkInstances[-1]._Iren.inDrawMode = 0 #TODO
mainWindowUI.vtkInstances[-1].inDrawMode = mainWindowUI.vtkInstances[-1]._Iren.inDrawMode
# drawing functions imported from mp_VTKDrawing
mainWindowUI.vtkInstances[-1].AddObserver('LeftButtonPressEvent', drawingPickPoint, 1.0)
mainWindowUI.vtkInstances[-1].AddObserver('RightButtonPressEvent', drawingMakeROI, 1.0)
ren = mainWindowUI.vtkInstances[-1].ren
mainWindowUI.vtkInstances[-1]._Iren.ren = ren
ren.AddActor(actor)
ren.SetBackground(1,1,1)
ren.ResetCamera()
ren.Render()
mainWindowUI.vtkInstances[-1].Render()
# lets put some of the data objects in the scope of the
# main window so that they can be manipulated later.
mainWindowUI.vtkInstances[-1].curr_actor = actor
mainWindowUI.vtkInstances[-1].curr_smoother = smooth
mainWindowUI.vtkInstances[-1].curr_polydata = polyData
mainWindowUI.vtkInstances[-1].curr_mapper = pdm
mainWindowUI.vtkInstances[-1].curr_camera = ren.GetActiveCamera()
# and the raw mesh coordinate data.. why not
mainWindowUI.vtkInstances[-1].curr_points = points
mainWindowUI.vtkInstances[-1].curr_polys = polys
mainWindowUI.vtkInstances[-1].curr_scalars = curr_scalars #Deep copied
# turns out that later processes access the inherited renderwindowinteractor (?)
# so lets put all the above in the scope of that too
mainWindowUI.vtkInstances[-1]._Iren.curr_actor = actor
mainWindowUI.vtkInstances[-1]._Iren.curr_smoother = smooth
mainWindowUI.vtkInstances[-1]._Iren.curr_polydata = polyData
mainWindowUI.vtkInstances[-1]._Iren.curr_mapper = pdm
mainWindowUI.vtkInstances[-1]._Iren.curr_camera = ren.GetActiveCamera()
mainWindowUI.vtkInstances[-1]._Iren.curr_points = points
mainWindowUI.vtkInstances[-1]._Iren.curr_polys = polys
mainWindowUI.vtkInstances[-1]._Iren.curr_scalars = curr_scalars #Deep copied
# and so we can access ui controls (e.g. statusbar) from the inherited window
mainWindowUI.vtkInstances[-1]._Iren.parent_ui = mainWindowUI
def KeyPress(obj, evt):
key = obj.GetKeySym()
if key == 'l':
currVTKinstance = len(mainWindowUI.vtkInstances)
print(key)
print(mainWindowUI.vtkInstances[currVTKinstance-1])
#let's also track key presses per instance esp for the draw routine :)
mainWindowUI.vtkInstances[-1].AddObserver("KeyPressEvent",KeyPress)
mainWindowUI.tabWidget.setCurrentIndex(len(mainWindowUI.vtkInstances)-1) #zero index
def smoothMesh(theMeshInstance, commandArgs, mainWindowUI, the_TCPserver):
#lets get the apt window
targetVTKWindow = mainWindowUI.vtkInstances[int(theMeshInstance)] #NB zero indexing
# lets show the correct tab
mainWindowUI.tabWidget.setCurrentIndex(int(theMeshInstance)) #zero index
#mainWindowUI.tabWidget.repaint()
mainWindowUI.tabWidget.update()
#lets get the original data
the_smoother = targetVTKWindow.curr_smoother
the_mapper = targetVTKWindow.curr_mapper
if debug: print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars())
if debug: print(targetVTKWindow.curr_actor.GetMapper().GetInput().GetPointData().GetScalars().GetTuple(1000))
#expecting a string that reads something like 'iterations,200,relaxationfactor,1.2'
# sanity check
if ('iterations' in commandArgs[0]) and ('relaxationfactor' in commandArgs[0]):
smoothingArgs = commandArgs[0].strip().split(',')
iterations = int(smoothingArgs[1])
relaxationfactor = float(smoothingArgs[3])
else:
return "error - expecting vertices, then curvature, then triangles!"
newActor = VTK_smoothing(the_smoother, the_mapper, iterations, relaxationfactor)
targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor)
targetVTKWindow.ren.AddActor(newActor)
targetVTKWindow.curr_actor = newActor #lets keep track
targetVTKWindow.ren.Render()
targetVTKWindow.Render()
# run mesh update to reset the color map (smoothing "messes" this up)
updateMeshData(theMeshInstance, [], mainWindowUI, the_TCPserver)
def updateMeshData(theMeshInstance, commandArgs, mainWindowUI, the_TCPserver):
# here the base mesh is already loaded and we are simply updating with the
# current View settings in from the vista session WITH THE COLOR VALUES FROM
# VISTA - i.e. do not go through a lookuptable
#lets get the apt window
targetVTKWindow = mainWindowUI.vtkInstances[int(theMeshInstance)] #NB zero indexing
# lets show the correct tab
mainWindowUI.tabWidget.setCurrentIndex(int(theMeshInstance)) #zero index
#mainWindowUI.tabWidget.repaint()
mainWindowUI.tabWidget.update()
#lets get the original data
the_polyData = targetVTKWindow.curr_polydata
the_mapper = targetVTKWindow.curr_mapper
#first get all the data we are expecting from the server
## NB this assumes that the order of sending by the server is
# 1) r_vector - red component
# 2) g_vector - blue component
# 3) b_vector - green component
# 4) a_vector - aplha component
if debug:
print('received request for UPDATE DIRECT mesh with Args:')
print(commandArgs)
if len(commandArgs) != 0 : #new data has come from MATLAB so recompute
# load the surfaces data
rVecArgs = commandArgs[0].strip().split(',')
r_vec = unpackData(rVecArgs[1], int(rVecArgs[2]), the_TCPserver)
r_vec = array(r_vec,'uint8')
if debug: print(r_vec)
gVecArgs = commandArgs[1].strip().split(',')
g_vec = unpackData(gVecArgs[1], int(gVecArgs[2]), the_TCPserver)
g_vec = array(g_vec,'uint8')
bVecArgs = commandArgs[2].strip().split(',')
b_vec = unpackData(bVecArgs[1], int(bVecArgs[2]), the_TCPserver)
b_vec = array(b_vec,'uint8')
aVecArgs = commandArgs[3].strip().split(',')
a_vec = unpackData(aVecArgs[1], int(aVecArgs[2]), the_TCPserver)
a_vec = array(a_vec,'uint8')
if debug:
print(len(r_vec))
print(len(g_vec))
print(len(b_vec))
print(len(a_vec))
#combine into numpy array
colorDat = squeeze(array(squeeze([r_vec,g_vec,b_vec,a_vec]),'B',order='F').transpose())
# convert this to a VTK unsigned char array
vtkColorArray = numpy_support.numpy_to_vtk(colorDat,0)
# keep a "deep" copy - this is to workaround some artifacts generated
# by vtk algorithms (e.g. smoothing) that also smooth the color data
# on the surface and then automatically update the inherited color map
# - we allow vtk to do this but then overwrite the recomptued color
# map AFTER the algorithms have run
deepCopyScalars = vtk.vtkUnsignedCharArray()
deepCopyScalars.DeepCopy(vtkColorArray)
targetVTKWindow.curr_scalars = deepCopyScalars
#TODO - this may have impact on later processing - investigate
else:
# no new data from MATLAB, probably just an internal re-draw call
# after something like smoothing - just grab the current deep
# copy of the required scalars
vtkColorArray = targetVTKWindow.curr_scalars
# OK - we have the data - let's update the mesh
newActor = VTK_updateMesh(targetVTKWindow, vtkColorArray, mainWindowUI)
targetVTKWindow.ren.AddActor(newActor)
targetVTKWindow.ren.RemoveActor(targetVTKWindow.curr_actor)
targetVTKWindow.curr_actor = newActor #lets keep track
targetVTKWindow.ren.Render()
targetVTKWindow.Render()
print('success with direct mesh update routine')
## --------------------------------------------------------------------------------
# test example animation
def rotateMeshAnimation(currVTKInstance, commandArgs, mainWindowUI, the_TCPserver):
#rotation args
rotations = commandArgs[0].strip().split(',')
rotations = unpackData(rotations[1], int(rotations[2]), the_TCPserver)
if debug: print(rotations)
targetVTKWindow = mainWindowUI.vtkInstances[int(currVTKInstance)] #NB zero indexing
camera = targetVTKWindow.ren.GetActiveCamera()
if debug: print(camera)
for i in range(len(rotations)):
camera.Azimuth(rotations[i])
#targetVTKWindow.ren.Render()
targetVTKWindow.iren.Render()
time.sleep(0.02)
the_TCPserver.socket.write(str('send useful message back here TODO'))
## --------------------------------------------------------------------------------