-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathmonkeyprintModelHandling.py
3572 lines (2968 loc) · 137 KB
/
monkeyprintModelHandling.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: latin-1 -*-
#
# Copyright (c) 2015-2016 Paul Bomke
# Distributed under the GNU GPL v2.
#
# This file is part of monkeyprint.
#
# monkeyprint 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 3 of the License, or
# (at your option) any later version.
#
# monkeyprint 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 have received a copy of the GNU General Public License
# along with monkeyprint. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
import shutil
import vtk
from vtk.util import numpy_support # Functions to convert between numpy and vtk
import math
import cv2
import numpy
import time
import random
from PIL import Image
import Queue, threading
import monkeyprintImageHandling as imageHandling
import cPickle # Save modelCollection to file.
import gzip
import tarfile
import copy
import monkeyprintSettings
## ## #### ##### ##### ## #### #### ## ## ###### #### ###### ## ## ##### #####
###### ## ## ## ## ## ## ## ## ## ## ### ## ## ## ## ## ### ## ## ## ##
###### ## ## ## ## #### ## ## ## ## ###### ## ## ## ## ###### #### ## ##
## ## ## ## ## ## ## ## ## ## ## ## ### ## ###### ## ## ### ## #####
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
## ## #### ##### ##### ###### #### #### ## ## ## ## ## ###### ## ## ##### ## ##
class modelContainer:
def __init__(self, filenameOrSettings, modelId, programSettings, console=None):
# Check if a filename has been given or an existing model settings object.
# If filename was given...
if type(filenameOrSettings) == str:
# ... create the model data with default settings.
# Create settings object.
self.settings = monkeyprintSettings.modelSettings()
filename = filenameOrSettings
# Save filename to settings.
self.settings['filename'].value = filename
# If settings object was given...
else:
# ... create the model data with the given settings.
self.settings = filenameOrSettings
# Get filename from settings object.
filename = self.settings['filename'].value
# Internalise remaining data.
self.console=console
# Get the slice path where slice images are saved.
self.slicePath = programSettings['tmpDir'].value + '/slicer/' + modelId
self.slicePath = self.slicePath.replace(' ', '') + '.d'
# Create model object.
self.model = modelData(filename, self.slicePath, self.settings, programSettings, self.console)
# active flag. Only do updates if model is active.
self.flagactive = True
# Update model and supports.
self.updateModel()
# self.updateSupports() # Do this upon entering supports tab.
# Set inital visibilities.
self.hideOverhang()
self.hideSupports()
self.hideBottomPlate()
self.hideSlices()
self.hideClipModel()
def getHeight(self):
return self.model.getHeight()
def updateModel(self):
return self.model.updateModel()
def updateSupports(self):
return self.model.updateSupports()
def updateSlice3d(self, sliceNumber):
self.model.updateSlice3d(sliceNumber)
def updateSliceStack(self, force=False):
return self.model.updateSliceStack()
def getSlicerProgress(self):
return self.model.slicerProgress
def sliceThreadListener(self):
self.model.checkBackgroundSlicer()
# Delete slice images.
def cleanUp(self):
# Empty the slicer temp directory.
shutil.rmtree(self.slicePath, ignore_errors=True)
def getAllActors(self):
return ( self.getActor(),
self.getBoxActor(),
self.getBoxTextActor(),
self.getOverhangActor(),
self.getBottomPlateActor(),
self.getSupportsActor(),
self.getClipModelActor(),
self.getSlicesActor()
)
def hideAllActors(self):
self.hideModel(),
self.hideBox(),
self.hideOverhang(),
self.hideBottomPlate(),
self.hideSupports(),
self.hideClipModel(),
self.hideSlices()
def updateAllActors(self, state):
if self.isActive():
if state == 0:
self.showActorsDefault()
elif state == 1:
self.showActorsSupports()
elif state == 2:
self.showActorsSlices()
elif state == 3:
self.showActorsPrint()
else:
self.ghostAllActors()
def showAllActors(self, state):
# if self.isActive():
if state == 0:
self.showActorsDefault()
elif state == 1:
self.showActorsSupports()
elif state == 2:
self.showActorsSlices()
elif state == 3:
self.showActorsPrint()
# else:
# self.ghostAllActors()
def ghostAllActors(self):
self.ghostModel()
self.ghostSupports()
self.ghostBottomPlate()
self.ghostClipModel()
self.ghostSlices()
self.hideOverhang()
# Adjust view for model manipulation.
def showActorsDefault(self):
self.opaqueModel()
self.showModel()
self.hideOverhang()
self.hideBottomPlate()
self.hideSupports()
self.hideSlices()
self.hideClipModel()
# Adjust view for support generation.
def showActorsSupports(self):
self.transparentModel()
self.showModel()
self.showOverhang()
self.opaqueBottomPlate()
self.showBottomPlate()
self.opaqueSupports()
self.showSupports()
self.hideSlices()
self.hideClipModel()
# Adjust view for slicing.
def showActorsSlices(self):
#self.transparentModel()
self.hideModel()
self.hideOverhang()
#self.transparentBottomPlate()
self.hideBottomPlate()
#self.transparentSupports()
self.hideSupports()
self.opaqueSlices()
self.showSlices()
self.opaqueClipModel()
self.showClipModel()
def showActorsPrint(self):
self.opaqueClipModel()
self.showClipModel()
#self.opaqueModel()
self.hideModel()
self.hideOverhang()
#self.opaqueBottomPlate()
self.hideBottomPlate()
#self.opaqueSupports()
self.hideSupports()
self.hideSlices()
def setActive(self, active):
self.flagactive = active
self.model.setActive(active)
def isActive(self):
return self.flagactive
def getActor(self):
return self.model.getActor()
def getBoxActor(self):
self.model.opacityBoundingBox(0.3)
return self.model.getActorBoundingBox()
def getBoxTextActor(self):
self.model.opacityBoundingBoxText(0.7)
return self.model.getActorBoundingBoxText()
def getSupportsActor(self):
return self.model.getActorSupports()
def getBottomPlateActor(self):
return self.model.getActorBottomPlate()
def getOverhangActor(self):
return self.model.getActorOverhang()
def getClipModelActor(self):
return self.model.getActorClipModel()
def getSlicesActor(self):
return self.model.getActorSlices()
def showBox(self):
#if self.flagactive:
self.model.showBoundingBox()
self.model.showBoundingBoxText()
def hideBox(self):
self.model.hideBoundingBox()
self.model.hideBoundingBoxText()
def showModel(self):
self.model.show()
if not self.flagactive:
self.model.opacity(.1)
def hideModel(self):
self.model.hide()
def opaqueModel(self):
self.model.opacity(1.0)
def transparentModel(self):
self.model.opacity(.5)
def ghostModel(self):
self.model.opacity(.1)
def showOverhang(self):
self.model.showActorOverhang()
if not self.flagactive:
self.hideOverhang()
def hideOverhang(self):
self.model.hideActorOverhang()
def showBottomPlate(self):
self.model.showActorBottomPlate()
if not self.flagactive:
self.model.setOpacityBottomPlate(.1)
def hideBottomPlate(self):
self.model.hideActorBottomPlate()
def opaqueBottomPlate(self):
self.model.setOpacityBottomPlate(1.0)
def transparentBottomPlate(self):
self.model.setOpacityBottomPlate(.5)
def ghostBottomPlate(self):
self.model.setOpacityBottomPlate(.1)
def showSupports(self):
self.model.showActorSupports()
if not self.flagactive:
self.model.setOpacitySupports(.1)
def hideSupports(self):
self.model.hideActorSupports()
def opaqueSupports(self):
self.model.setOpacitySupports(1.0)
def transparentSupports(self):
self.model.setOpacitySupports(.5)
def ghostSupports(self):
self.model.setOpacitySupports(.1)
def showClipModel(self):
self.model.showActorClipModel()
if not self.flagactive:
self.model.setOpacityClipModel(.1)
def hideClipModel(self):
self.model.hideActorClipModel()
def opaqueClipModel(self):
self.model.setOpacityClipModel(1.0)
def transparentClipModel(self):
self.model.setOpacityClipModel(.5)
def ghostClipModel(self):
self.model.setOpacityClipModel(.1)
def showSlices(self):
self.model.showActorSlices()
if not self.flagactive:
self.model.setOpacitySlices(.1)
def opaqueSlices(self):
self.model.setOpacitySlices(1.0)
def ghostSlices(self):
self.model.setOpacitySlices(.1)
def hideSlices(self):
self.model.hideActorSlices()
## ## #### ##### ##### ## #### #### ## ## ##### #### ###### ###### #### ## ##
###### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ### ##
###### ## ## ## ## #### ## ## ## ## ## ## #### ## ## ## ## ## ######
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ###
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
## ## #### ##### ##### ###### #### #### ###### ###### ##### #### ## ###### #### ## ##
class modelCollection(dict):
def __init__(self, programSettings, console=None):
# Call super class init function. *********************
dict.__init__(self)
# Internalise settings. *******************************
self.programSettings = programSettings
self.console = console
# Create slice image. *********************************
self.sliceImage = imageHandling.createImageGray(self.programSettings['projectorSizeX'].getValue(), self.programSettings['projectorSizeY'].getValue(), 0)
self.sliceImageBlack = numpy.empty_like(self.sliceImage)
# Preview slice stack. ********************************
widthPreview = self.programSettings['previewSliceWidth'].getValue()
aspect = self.programSettings['projectorSizeX'].getValue() / float(self.programSettings['projectorSizeY'].getValue())
heightPreview = int(widthPreview / aspect)
self.sliceStackPreview = sliceStack(self.programSettings, width=widthPreview, height=heightPreview, imgType='empty')
self.sliceStackPreviewLabels = [0]
self.sliceMode = "preview" # Needed for slice combiner poll method.
self.currentSliceNumber = None
self.currentSlice = imageHandling.createImageGray(self.programSettings['projectorSizeX'].value, self.programSettings['projectorSizeY'].value,0)
self.sliceCombinerFinished = False
#self.numberOfPreviewSlices = self.programSettings['previewSlicesMax'].getValue()
#print "Maximum number of preview slices: " + str(self.numberOfPreviewSlices) + "."
#self.stackHeightOld = self.sliceStackPreview.getStackHeight()
# Queue for transferring slice images from model slicer threads
# to slice combiner thread.
self.queueModelCollectionToCombiner = Queue.Queue()
self.queueCombinerToModelCollection = Queue.Queue()
self.queueCombinerToModelCollectionSingle = Queue.Queue()
# Slice combiner thread.
self.threadSliceCombiner = sliceCombiner(self.programSettings, self.queueModelCollectionToCombiner, self.queueCombinerToModelCollection, self.queueCombinerToModelCollectionSingle, self.console)
self.threadSliceCombiner.start()
# Create calibration image. ***************************
self.calibrationImage = None#numpy.empty_like(self.sliceImage)
# Set defaults. ***************************************
# Create current model id.
self.currentModelId = ""
# Load default model to fill settings for gui. ********
self.add("default", "") # Don't provide file name.
# Create job settings object. *************************
#self.jobSettings = monkeyprintSettings.jobSettings(self.programSettings)
# THIS WILL BE DONE LATER ON JOB PACKING
# Reload calibration image.
def subtractCalibrationImage(self, inputImage):
# Get the image if it does not exist.
if self.calibrationImage == None and self.programSettings['calibrationImage'].value:
print "Loading calibration image."
calibrationImage = None
try:
if os.path.isfile('./calibrationImage.png'):
calibrationImage = cv2.imread('./calibrationImage.png')
elif os.path.isfile('./calibrationImage.jpg'):
calibrationImage = cv2.imread('./calibrationImage.jpg')
except Error:
print "Could not load calibration image. Skipping..."
# If loading succeded...
if calibrationImage != None:
# Convert to grayscale.
calibrationImage = cv2.cvtColor(calibrationImage, cv2.COLOR_BGR2GRAY)
# ... scale the image according to projector size.
calibrationImage = cv2.resize(calibrationImage, (self.programSettings['projectorSizeX'].value, self.programSettings['projectorSizeY'].value))
# Blur the image to reduce the influence of noise.
calibrationImage = cv2.GaussianBlur(calibrationImage, (21, 21), 0)
# Turn into numpy array.
self.calibrationImage = numpy.asarray(calibrationImage, dtype=numpy.uint8)
# Find the lowest pixel value.
minVal = numpy.amin(self.calibrationImage)
# Shift pixel values down.
# Darkest pixel should be black now.
self.calibrationImage -= minVal
#print calibrationImage.shape
# If the image exists now...
if self.calibrationImage != None and self.programSettings['calibrationImage'].value:
# Resize in case of settings change.
if self.calibrationImage.shape[0] != self.programSettings['projectorSizeY'].value or self.calibrationImage.shape[1] != self.programSettings['projectorSizeX'].value:
self.calibrationImage = cv2.resize(self.calibrationImage, (self.programSettings['projectorSizeX'].value, self.programSettings['projectorSizeY'].value))
# print "Subtracting calibration image."
# ... subtract the calibration image from the input image.
inputImage = cv2.subtract(inputImage, self.calibrationImage)
if not self.programSettings['calibrationImage'].value:
self.calibrationImage = None
return inputImage
# TODO
# Save model collection to compressed disk file. Works well with huge objects.
def saveProject(self, filename, protocol = -1, fileSearchFnc=None):
# Gather the relevant data.
# Model settings.
modelSettings = {}
for model in self:
if model != "default":
modelSettings[model] = (self[model].settings)
# Model list for GUI.
# gtk.ListStores cannot be pickled, so we convert to list of lists.
listStoreList = []
for row in range(len(self.modelList)):
i = self.modelList.get_iter(row)
rowData = []
for j in range(4):
dat = self.modelList.get_value(i,j)
rowData.append(dat)
listStoreList.append(rowData)
# Combine model settings with job settings.
jobSettings = monkeyprintSettings.jobSettings(self.programSettings)
data = [jobSettings, modelSettings, listStoreList]#TODO
# Write the data into a pickled binary file.
picklePath = os.getcwd() + '/pickle.bin'
with open(picklePath, 'wb') as pickleFile:
# Dump the data.
cPickle.dump(data, pickleFile, protocol)
# Add all relevant stl files.
# First, create a list of the model file paths.
modelPathList = []
self.console.addLine("Packing the following stl files: ")
for model in self:
if model != "default":
# Get the model file path.
modelPath = self[model].settings['filename'].value
# Append if not in list already.
if modelPath not in modelPathList:
modelPathList.append(modelPath)
self.console.addLine(" " + modelPath.split('/')[-1])
# Create a tar archive with gzip compression. This will be the mkp file.
with tarfile.open(filename, 'w:gz') as mkpFile:
# Add the pickled settings file.
mkpFile.add(picklePath, arcname='pickle.bin', recursive=False)
# Add the stl files. Use file name without path as name.
for path in modelPathList:
#print path.split('/')[-1]
try:
mkpFile.add(path, arcname=path.split('/')[-1])
except IOError, OSError:
print "Stl file not found..."
# TODO: Handle file not found error in GUI.
# TODO: Maybe copy stls into temporary dir upon load?
# This would be consistent with loading an mkp file and saving stls to tmp dir.
# TODO
# Load a compressed model collection from disk.
def loadProject(self, filename):
# Create temporary working directory path.
#tmpPath = os.getcwd()+'/tmp'
tmpPath = self.programSettings['tmpDir'].value
# Delete the tmp directory, just in case it is there already.
shutil.rmtree(tmpPath, ignore_errors=True)
# Extract project files to tmp directory.
with tarfile.open(filename, 'r:gz') as mkpFile:
mkpFile.extractall(path=tmpPath)
# Read the pickled settings file.
data=None
with open(tmpPath+'/pickle.bin', 'rb') as pickleFile:
# Dump the data.
data = cPickle.load(pickleFile)
# Clear all models from current model collection.
self.removeAll()
# Get the relevant parts from the object.
# First is job settings, second is list of model settings.
jobSettings = data[0]
jobSettings.setProgramSettings(self.programSettings)
settingsList = data[1]
# Import the model settings from the file into the model collection.
for model in settingsList:
if model != "default":
# Make the model file path point to the tmp directory.
modelFilename = settingsList[model]['filename'].value.split('/')[-1]
settingsList[model]['filename'].value = tmpPath+'/'+modelFilename
# Create a new model from the modelId and settings.
self.add(model, settingsList[model])
self.getCurrentModel().hideBox()
# Get the model list and convert to list store.
modelListData = data[2]
for row in modelListData:
if row[0] != "default":
self.modelList.append(row)
# Delete the tmp directory.
#shutil.rmtree(tmpPath)
# Function to retrieve id of the current model.
def getCurrentModelId(self):
return self.currentModelId
# Function to retrieve current model.
def getCurrentModel(self):
return self[self.currentModelId]
# Function to change to current model.
def setCurrentModelId(self, modelId):
self.currentModelId = modelId
# Function to retrieve a model object.
def getModel(self, modelId):
return self[modelId]
# Add a model to the collection.
def add(self, newModelId, filenameOrSettings):
# Prepare newModelId if this is not the default model.
# Also, add to modelListQt.
if not newModelId == "default":
# Check if there is a file with the same name loaded already.
# Use the permanent file id in second row for this.
copyNumber = 0
for modelId in self:
# Check if filename already loaded.
if newModelId == modelId[:len(newModelId)]:
# If so, set the copy number to 1.
copyNumber = 1
# Check if this is a copy already.
if len(modelId) > len(newModelId):
if int(modelId[len(newModelId)+2:len(modelId)-1]) >= copyNumber:
copyNumber = int(modelId[len(newModelId)+2:len(modelId)-1]) + 1
if copyNumber > 0:
newModelId = newModelId + " (" + str(copyNumber) + ")"
# Add model to collection.
self[newModelId] = modelContainer(filenameOrSettings=filenameOrSettings, modelId=newModelId, programSettings=self.programSettings, console=self.console)
# Set new model as current model.
self.currentModelId = newModelId
return newModelId
# Function to remove a model from the model collection
def remove(self, modelId):
# Kill slicer.
self[modelId].model.killBackgroundSlicer()
self[modelId].cleanUp()
# Explicitly delete model data to free memory from slice images.
del self[modelId].model
del self[modelId]
def removeAll(self):
# Set current model to default.
self.setCurrentModelId("default")
# Get list of model ids.
modelIDs = []
for model in self:
if model != "default":
modelIDs.append(model)
for i in range(len(modelIDs)):
self.remove(modelIDs[i])
# Empty existing model list.
listIters = []
for row in range(len(self.modelList)):
listIters.append(self.modelList.get_iter(row))
for i in listIters:
if self.modelList.get_value(i,0) != "default":
self.modelList.remove(i)
def getNumberOfActiveModels(self):
nActive = 0
for model in self:
nActive += (model != "default" and self[model].isActive())
return nActive
# Function to retrieve the highest model. This dictates the slice stack height.
def getNumberOfSlices(self):
modelHeights = []
for model in self:
if model != "default" and self[model].isActive():
modelHeights.append(self[model].model.getNumberOfSlices())
if modelHeights != []:
return sorted(modelHeights)[-1]
# Return 0 if no model has been loaded yet.
else:
return 1
# Return the calculated preview stack height.
def getPreviewStackHeight(self):
stackHeight = min(self.programSettings['previewSlicesMax'].getValue(), self.getNumberOfSlices())
return stackHeight
# Return the current preview stack height.
# This might be 1 if slicer is still running.
#def getPreviewStackHeightCurrent(self):
# return len(self.sliceStackPreview)
def calcSliceStackPreviewSubset(self):
# Get slice multiplier. If there are more slices than preview slices, the multiplier must be > 1.
sliceMultiplier = max(1, self.getNumberOfSlices() / float(self.programSettings['previewSlicesMax'].getValue()))
# First and last index are fixed, all in between are approximated.
self.sliceStackPreviewLabels = [0]
self.sliceStackPreviewLabels += [int(round((previewSlice)*sliceMultiplier)) for previewSlice in range(1, self.getPreviewStackHeight()-1)]
self.sliceStackPreviewLabels += [self.getNumberOfSlices()-1]
# Gather slicer input info.
def createSlicerInputInfo(self, mode="preview", savePath=None):
assert mode == "preview" or mode == "full" or mode.split(' ')[0] == "single"
# Create model height list.
# Data: create preview, number of prev slices, prev slice height,
# slice paths, number of model slices, model position, model size.
# Mode can be preview, full or slice number.
if mode == "preview":
sliceNumbers = self.sliceStackPreviewLabels
elif mode == "full":
sliceNumbers = range(self.getNumberOfSlices())
elif mode.split(' ')[0] == "single":
sliceNumbers = int(mode.split(' ')[1])
modelNamesAndHeights = [sliceNumbers, [],[],[],[], mode, savePath]
# Update all models' slice stacks.
for model in self:
if model != 'default' and self[model].isActive():
modelNamesAndHeights[1].append(self[model].slicePath)
modelNamesAndHeights[2].append(self[model].model.getNumberOfSlices())
modelNamesAndHeights[3].append(self[model].model.getSlicePositionPx(border=False))
modelNamesAndHeights[4].append(self[model].model.getSliceSizePx(border=True))
return modelNamesAndHeights
# Update the slice stack.
# This is called from the GUI and starts all model
# slicers if the respective model has changed.
# The force option will start all model slicers
# even if the models have not been changed.
# This method also starts the slice combiner.
def updateSliceStack(self, force=False):
# Update model slice stacks.
# Also, check if there are any active models at all.
empty = True
for model in self:
self[model].updateSliceStack(force)
if model != 'default' and self[model].isActive():
empty = False
if not empty:
# Set the preview subset indices.
self.calcSliceStackPreviewSubset()
# Reset preview slice stack.
self.sliceStackPreview.reset(imgType='update')
# Update preview slice stack.
self.queueModelCollectionToCombiner.put(self.createSlicerInputInfo(mode="preview"))
self.sliceCombinerFinished = False
else:
self.sliceStackPreviewLabels = [0]
self.sliceStackPreview.reset( imgType='empty')
# Save slice stack.
# Update function is a gui function that moves a progress bar.
def saveSliceStack(self, path, updateFunction=None):
# Set slice mode to full to block slice combiner checker
# timeout function to read slicer status from the slice
# combiner output queue.
self.sliceMode = "full"
# Run the slice combiner. This will automatically
# save the images to the temp directory.
self.queueModelCollectionToCombiner.put(self.createSlicerInputInfo(mode="full", savePath=path))
# Update the status bar.
while True:
while not self.queueCombinerToModelCollection.qsize():
time.sleep(0.1)
status = self.queueCombinerToModelCollection.get()
# Update progress bar.
if updateFunction != None:
updateFunction(int(status))
if int(status) == 100:
break
# Reset slice mode to preview.
self.sliceMode = "preview"
# Create the projector frame from the model slice stacks.
def updateSliceImage(self, i, mode='preview'):
assert mode == 'preview' or mode == 'full'
# Make sure index is an integer.
i = int(i)
if mode == 'preview':
#print "Requested slice {n:g}".format(n=i)
#print "Number of slices: {n:g}".format(n=len(self.sliceStackPreview))
# Return preview image.
#print "Returning image size: " + str(self.sliceStackPreview.getSlice(i).shape)
return self.sliceStackPreview.getSlice(i)
'''
if i < len(self.sliceStackPreview) and i >= 0:
return self.sliceStackPreview[i]
else:
return None
'''
elif mode == 'full':
# Check if the current slice is requested again.
if self.currentSliceNumber != None and i == self.currentSliceNumber:
return self.currentSlice
# If not, create it.
else:
# Send request to slice combiner.
self.queueModelCollectionToCombiner.put(self.createSlicerInputInfo(mode="single "+str(i)))
# Wait for response.
while not self.queueCombinerToModelCollectionSingle.qsize():
time.sleep(0.1)
# Get slice image.
self.currentSlice = self.queueCombinerToModelCollectionSingle.get()
self.currentSliceNumber = i
# Return slice.
return self.currentSlice
def viewState(self, state):
if state == 0:
for model in self:
self[model].showActorsDefault()
elif state == 1:
for model in self:
self[model].showActorsSupports()
elif state == 2:
for model in self:
self[model].showActorsSlices()
elif state == 3:
for model in self:
self[model].showActorsPrint()
'''
# Adjust view for model manipulation.
def viewDefault(self):
for model in self:
self[model].opaqueModel()
self[model].hideOverhang()
self[model].hideBottomPlate()
self[model].hideSupports()
self[model].hideSlices()
# Adjust view for support generation.
def viewSupports(self):
for model in self:
self[model].transparentModel()
self[model].showOverhang()
self[model].showBottomPlate()
self[model].opaqueBottomPlate()
self[model].showSupports()
self[model].opaqueSupports()
self[model].hideSlices()
# Adjust view for slicing.
def viewSlices(self):
for model in self:
self[model].transparentModel()
self[model].hideOverhang()
self[model].showBottomPlate()
self[model].transparentBottomPlate()
self[model].showSupports()
self[model].transparentSupports()
self[model].showSlices()
def viewPrint(self):
for model in self:
self[model].transparentModel()
self[model].hideOverhang()
self[model].showBottomPlate()
self[model].transparentBottomPlate()
self[model].showSupports()
self[model].transparentSupports()
self[model].showSlices()
'''
def updateAllModels(self):
for model in self:
self[model].updateModel()
# Update supports.
def updateAllSupports(self):
for model in self:
self[model].updateSupports()
# Update the 3d slice view for all models.
def updateAllSlices3d(self, sliceNumber):
for model in self:
self[model].model.updateSlice3d(sliceNumber)
# Function that is called every n milliseconds from GUI main loop to
# check the slicers.
def checkSlicer(self):
# Check the individual model slicer threads.
for model in self:
self[model].sliceThreadListener()
# Also, check the slice combiner thread.
self.checkSliceCombinerThread()
def checkSliceCombinerThread(self):
if self.sliceMode == "preview":
if self.queueCombinerToModelCollection.qsize():
sliceCombinerOutput = self.queueCombinerToModelCollection.get()
if type(sliceCombinerOutput) == str:
pass#self.console.addLine('All slices progress: ' + sliceCombinerOutput + '%.')
else:
self.sliceStackPreview.setSlices(sliceCombinerOutput)
self.sliceCombinerFinished = True
elif self.sliceMode == "full":
pass
def slicerRunning(self):
# Return True if one of the slicers is still running.
running = False
for model in self:
if model != "default":
running = running or self[model].model.flagSlicerRunning
# print running
return running
def slicerThreadsFinished(self):
finished = False
for model in self:
if model != "default":
finished = finished or self[model].model.flagSlicerFinished
# print running
#print finished
return finished
# Get all model volumes.
def getTotalVolume(self):
volume = 0
for model in self:
if self[model].isActive():
volume += self[model].model.getVolume()
return volume
def getAllActors(self):
allActors = []
for model in self:
modelActors = self[model].getAllActors()
for actor in modelActors:
allActors.append(actor)
return allActors
def modelsLoaded(self):
if len(self) > 1:
return True
else:
return False
################################################################################
# Create an error observer for the VTK error messages. #########################
################################################################################
# Taken from here: http://www.vtk.org/pipermail/vtkusers/2012-June/074703.html
class ErrorObserver:
def __init__(self):
self.__ErrorOccurred = False
self.__WarningOccurred = False
self.__ErrorMessage = None
self.__WarningMessage = None
self.CallDataType = 'string0'
def __call__(self, obj, event, message):
if event == 'WarningEvent':
self.__WarningOccurred = True
self.__WarningMessage = message
else:
self.__ErrorOccurred = True
self.__ErrorMessage = message
def ErrorOccurred(self):
occ = self.__ErrorOccurred
self.__ErrorOccurred = False
return occ
def WarningOccurred(self):
occ = self.__WarningOccurred
self.__WarningOccurred = False
return occ
def ErrorMessage(self):
return self.__ErrorMessage
def WarningMessage(self):
return self.__WarningMessage
##### ## ## ###### ## ##### ## ## #### ## ## ## ## ## ##### ##### #### ###### ####
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ###### ## ## ## ## ## ## ## ##
##### ## ## ## ## ## ## ## ## ## ## ## ## ## ###### #### ## ## ## ## ## ## ##
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ###### ## ######
## ## ## ## ## ## ## ## #### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
##### #### ###### ###### ##### ## #### ###### #### ## ## ##### ##### ## ## ## ## ##