-
Notifications
You must be signed in to change notification settings - Fork 0
/
monkeyprintModelHandling.py
2309 lines (1912 loc) · 85.9 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 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
import Image#, ImageTk
import Queue, threading
import monkeyprintImageHandling as imageHandling
import gtk
import cPickle # Save modelCollection to file.
import gzip
import tarfile
import monkeyprintSettings
class modelContainer:
def __init__(self, filenameOrSettings, 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
# Create model object.
self.model = modelData(filename, 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()
# Set inital visibilities.
self.hideOverhang()
self.hideSupports()
self.hideBottomPlate()
self.hideSlices()
self.hideClipModel()
# Set changed flag to start slicer.
self.setChanged()
def getHeight(self):
return self.model.getHeight()
def setChanged(self):
self.model.setChanged()
def updateModel(self):
#self.model.setChanged()
self.model.updateModel()
def updateSupports(self):
#self.model.setChanged()
self.model.updateBottomPlate()
self.model.updateSupports()
def updateSlice3d(self, sliceNumber):
self.model.updateSlice3d(sliceNumber)
def updateSliceStack(self):
self.model.startBackgroundSlicer()
def sliceThreadListener(self):
# self.model.setChanged()
self.model.checkBackgroundSlicer()
def getAllActors(self):
return ( self.getActor(),
self.getBoxActor(),
self.getBoxTextActor(),
self.getOverhangActor(),
self.getBottomPlateActor(),
self.getSupportsActor(),
self.getClipModelActor(),
self.getSlicesActor()
)
def hideAllActors(self):
print "bar"
self.hideModel(),
self.hideBox(),
self.hideOverhang(),
self.hideBottomPlate(),
self.hideSupports(),
self.hideClipModel(),
self.hideSlices()
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'].value, self.programSettings['projectorSizeY'].value, 0)
self.sliceImageBlack = numpy.empty_like(self.sliceImage)
# 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 model list.***********************************
# List will contain strings for dispayed name,
# internal name and file name and a bool for active state.
self.modelList = gtk.ListStore(str, str, str, bool)
# Create job settings object. *************************
self.jobSettings = monkeyprintSettings.jobSettings(self.programSettings)
# 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
# Save slice stack.
def saveSliceStack(self, path, updateFunction=None):
# Get number of slices.
nSlices = self.getNumberOfSlices()
digits = len(str(nSlices))
for i in range(nSlices):
# Update progress bar.
if updateFunction != None:
updateFunction(i)
while gtk.events_pending():
gtk.main_iteration(False)
# Format number string.
numberString = str(i+1)
# Create image file string.
fileString = path[:-4] + "_" + numberString + path[-4:]
print "Saving image " + fileString + "."
image = Image.fromarray(self.updateSliceImage(i))
image.save(fileString)
# 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.
data = [self.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.
# Load a compressed model collection from disk.
def loadProject(self, filename):
# Create temporary working directory.
tmpPath = os.getcwd()+'/tmp'
# 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.
self.jobSettings = data[0]
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, modelId, filenameOrSettings):
self[modelId] = modelContainer(filenameOrSettings, self.programSettings, self.console)
# Set new model as current model.
self.currentModelId = modelId
# Function to remove a model from the model collection
def remove(self, modelId):
if self[modelId]:
self[modelId].model.killBackgroundSlicer()
# 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)
# Function to retrieve the highest model. This dictates the slice stack height.
def getNumberOfSlices(self):
height = 0
# Loop through all models.
for model in self:
# If model higher than current height value...
if height < self[model].getHeight():
# ... set new height value.
height = self[model].getHeight()
if self.console != None:
self.console.addLine('Maximum model height: ' + str(height) + ' mm.')
numberOfSlices = int(math.floor(height / self.programSettings['layerHeight'].value))
return numberOfSlices
# Update the slice stack. Set it's height according to max model
# height and layerHeight.
def updateSliceStack(self):
# Update all models' slice stacks.
for model in self:
self[model].updateSliceStack()
# Create the projector frame from the model slice stacks.
def updateSliceImage(self, i):
# Make sure index is an integer.
i = int(i)
# Get slice images from all models and add to projector frame.
# Reset projector frame.
self.sliceImage = imageHandling.createImageGray(self.programSettings['projectorSizeX'].value, self.programSettings['projectorSizeY'].value, 0)
# print "Projector dimensions: " + str(self.sliceImage.shape) + "."
# Get slice images from models.
# Append the slice image and its position on the projector frame.
imgList = []
for model in self:
# self[model].updateSlice3d(sliceNumber)
if model != "default" and self[model].isactive() and i<len(self[model].model.sliceStack):
# print "Image dimensions: " + str(self[model].model.sliceStack[i].shape) + "."
imgList.append((self[model].model.sliceStack[i], self[model].model.getSlicePosition()))
# Add list of slice images to projector frame.
for i in range(len(imgList)):
self.sliceImage = imageHandling.imgAdd(self.sliceImage, imgList[i][0], imgList[i][1])
# Subtract calibration image.
self.sliceImage = self.subtractCalibrationImage(self.sliceImage)
return self.sliceImage
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 gtk main loop to
# check the slicer queue.
def checkSlicerThreads(self):
for model in self:
self[model].sliceThreadListener()
# Return true, otherwise the function will not run again.
return True
def slicerRunning(self):
# Return True if one of the slicers is still running.
running = False
for model in self:
# if self[model].model.flagSlicerRunning:
# print ("Slicer of model " + model + " is running.")
running = running or self[model].model.flagSlicerRunning
# print running
return running
# 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
################################################################################
################################################################################
################################################################################
class buildVolume:
def __init__(self, buildVolumeSize):
# Create build volume.
self.buildVolume = vtk.vtkCubeSource()
self.buildVolume.SetCenter(buildVolumeSize[0]/2.0, buildVolumeSize[1]/2.0, buildVolumeSize[2]/2.0)
self.buildVolume.SetXLength(buildVolumeSize[0])
self.buildVolume.SetYLength(buildVolumeSize[1])
self.buildVolume.SetZLength(buildVolumeSize[2])
# Build volume outline filter.
self.outlineFilter = vtk.vtkOutlineFilter()
if vtk.VTK_MAJOR_VERSION <= 5:
self.outlineFilter.SetInput(self.buildVolume.GetOutput())
else:
self.outlineFilter.SetInputConnection(self.buildVolume.GetOutputPort())
# Build volume outline mapper.
self.buildVolumeMapper = vtk.vtkPolyDataMapper()
if vtk.VTK_MAJOR_VERSION <= 5:
self.buildVolumeMapper.SetInput(self.outlineFilter.GetOutput())
else:
self.buildVolumeMapper.SetInputConnection(self.outlineFilter.GetOutputPort())
# Build volume outline actor.
self.buildVolumeActor = vtk.vtkActor()
self.buildVolumeActor.SetMapper(self.buildVolumeMapper)
def getActor(self):
return self.buildVolumeActor
def resize(self, buildVolumeSize):
self.buildVolume.SetCenter(buildVolumeSize[0]/2.0, buildVolumeSize[1]/2.0, buildVolumeSize[2]/2.0)
self.buildVolume.SetXLength(buildVolumeSize[0])
self.buildVolume.SetYLength(buildVolumeSize[1])
self.buildVolume.SetZLength(buildVolumeSize[2])
################################################################################
################################################################################
################################################################################
class modelData:
###########################################################################
# Construction method definition. #########################################
###########################################################################
def __init__(self, filename, settings, programSettings, console=None):
# Create VTK error observer to catch errors.
self.errorObserver = ErrorObserver()
# Set up variables.
# Internalise settings.
self.filenameStl = ""
self.filename = filename
self.flagactive = True
self.settings = settings
self.programSettings = programSettings
self.console = console
# Set up values for model positioning.
self.rotationXOld = 0
self.rotationYOld = 0
self.rotationZOld = 0
self.flagChanged = False
self.flagSlicerRunning = False
# Set up the slice stack. Has one slice only at first...
self.sliceStack = sliceStack()
self.slicePosition = (0,0)
# Background thread for updating the slices on demand.
self.queueSlicerIn = Queue.Queue()
self.queueSlicerOut = Queue.Queue()
if self.filename != "":
# Initialise the thread.
if self.console!=None:
self.console.addLine("Starting slicer thread")
self.slicerThread = backgroundSlicer(self.settings, self.programSettings, self.queueSlicerIn, self.queueSlicerOut, self.console)
self.slicerThread.start()
# Set up pipeline. ###################################################
# Stl
# --> Polydata
# --> Calc normals
# --> Scale
# --> Move to origin
# --> Rotate
# --> Move to desired position.
# --> Create overhang model.
# --> Intersect support pattern with overhang model.
# --> Create supports on intersection points.
if self.filename != "":
# Create stl source.
self.stlReader = vtk.vtkSTLReader() # File name will be set later on when model is actually loaded.
self.stlReader.SetFileName(self.filename)
# Get polydata from stl file.
self.stlPolyData = vtk.vtkPolyData
self.stlPolyData = self.stlReader.GetOutput()
# Calculate normals.
self.stlPolyDataNormals = vtk.vtkPolyDataNormals()
self.stlPolyDataNormals.SetInput(self.stlPolyData)
self.stlPolyDataNormals.SplittingOff() # Don't split sharp edges using feature angle.
self.stlPolyDataNormals.ComputePointNormalsOn()
self.stlPolyDataNormals.ComputeCellNormalsOff()
# stlNormals.Update()
# Move to origin filter. Input is stl polydata.
self.stlCenterTransform = vtk.vtkTransform() # Empty transformation matrix.
self.stlCenterFilter = vtk.vtkTransformFilter()
self.stlCenterFilter.SetTransform(self.stlCenterTransform)
self.stlCenterFilter.SetInput(self.stlPolyDataNormals.GetOutput())
# Scale filter. Input is scale filter.
self.stlScaleTransform = vtk.vtkTransform() # Empty transformation matrix.
self.stlScaleFilter = vtk.vtkTransformFilter()
self.stlScaleFilter.SetTransform(self.stlScaleTransform)
self.stlScaleFilter.SetInput(self.stlCenterFilter.GetOutput()) # Note: stlPolyData is a data object, hence no GetOutput() method is needed.
# Rotate filter. Input is move filter.
self.stlRotateTransform = vtk.vtkTransform() # Empty transformation matrix.
self.stlRotationFilter=vtk.vtkTransformPolyDataFilter()
self.stlRotationFilter.SetTransform(self.stlRotateTransform)
self.stlRotationFilter.SetInputConnection(self.stlScaleFilter.GetOutputPort())
# Move to position filter. Input is rotate filter.
self.stlPositionTransform = vtk.vtkTransform() # Empty transformation matrix.
self.stlPositionFilter = vtk.vtkTransformFilter()
self.stlPositionFilter.SetTransform(self.stlPositionTransform)
self.stlPositionFilter.SetInput(self.stlRotationFilter.GetOutput())
# Create clipping filter. Use normals to clip stl.
self.overhangClipFilter = vtk.vtkClipPolyData()
self.overhangClipFilter.GenerateClipScalarsOff()
self.overhangClipFilter.SetInsideOut(1)
self.overhangClipFilter.GenerateClippedOutputOff()
self.overhangClipFilter.SetInput(self.stlPositionFilter.GetOutput())
# Define cell locator for intersections of support pattern and overhang model.
self.locator = vtk.vtkCellLocator()
self.locator.SetDataSet(self.overhangClipFilter.GetOutput()) #TODO: change to selected region input.
# Create supports polydata.
self.supports = vtk.vtkAppendPolyData()
self.supports.AddObserver('ErrorEvent', self.errorObserver)
# Create bottom plate polydata. Edge length 1 mm, place outside of build volume by 1 mm.
self.bottomPlate = vtk.vtkCubeSource()
self.bottomPlate.SetXLength(1)
self.bottomPlate.SetYLength(1)
self.bottomPlate.SetZLength(1)
self.bottomPlate.SetCenter((-1, -1, -1))
# The following is for 3D slice data. ################################
# Create cutting plane, clip filter, cutting filter and cut line polydata.
self.extrusionVector = (0,0,-1)
# Create cutting plane.
self.cuttingPlane = vtk.vtkPlane()
self.cuttingPlane.SetNormal(0,0,-1)
self.cuttingPlane.SetOrigin(0,0,0.001) # Make sure bottom plate is cut properly.
# Create clip filter for model.
self.clipFilterModel = vtk.vtkClipPolyData()
self.clipFilterModel.SetClipFunction(self.cuttingPlane)
self.clipFilterModel.SetInput(self.stlPositionFilter.GetOutput())
# Create clip filter for model.
self.clipFilterSupports = vtk.vtkClipPolyData()
self.clipFilterSupports.SetClipFunction(self.cuttingPlane)
self.clipFilterSupports.SetInput(self.supports.GetOutput())
# Create clip filter for model.
self.clipFilterBottomPlate = vtk.vtkClipPolyData()
self.clipFilterBottomPlate.SetClipFunction(self.cuttingPlane)
self.clipFilterBottomPlate.SetInput(self.bottomPlate.GetOutput())
# Combine clipped models.
self.combinedClipModels = vtk.vtkAppendPolyData()
self.combinedClipModels.AddObserver('ErrorEvent', self.errorObserver)
self.combinedClipModels.AddInput(self.clipFilterModel.GetOutput())
self.combinedClipModels.AddInput(self.clipFilterSupports.GetOutput())
self.combinedClipModels.AddInput(self.clipFilterBottomPlate.GetOutput())
# Create cutting filter for model.
self.cuttingFilterModel = vtk.vtkCutter()
self.cuttingFilterModel.SetCutFunction(self.cuttingPlane)
self.cuttingFilterModel.SetInput(self.stlPositionFilter.GetOutput())
# Create cutting filter for supports.
self.cuttingFilterSupports = vtk.vtkCutter()
self.cuttingFilterSupports.SetCutFunction(self.cuttingPlane)
self.cuttingFilterSupports.SetInput(self.supports.GetOutput())
# Create cutting filter for bottom plate.
self.cuttingFilterBottomPlate = vtk.vtkCutter()
self.cuttingFilterBottomPlate.SetCutFunction(self.cuttingPlane)
self.cuttingFilterBottomPlate.SetInput(self.bottomPlate.GetOutput())
# Create polylines from cutter output for model.
self.sectionStripperModel = vtk.vtkStripper()
self.sectionStripperModel.SetInput(self.cuttingFilterModel.GetOutput())
#TODO: remove scalars so color is white.
#self.sectionStripperModel.GetOutput().GetPointData().RemoveArray('normalsZ')
# Create polylines from cutter output for supports.
self.sectionStripperSupports = vtk.vtkStripper()
self.sectionStripperSupports.SetInput(self.cuttingFilterSupports.GetOutput())
# Create polylines from cutter output for bottom plate.
self.sectionStripperBottomPlate = vtk.vtkStripper()
self.sectionStripperBottomPlate.SetInput(self.cuttingFilterBottomPlate.GetOutput())
# Combine cut lines from model, supports and bottom plate. This is for display only.
self.combinedCutlines = vtk.vtkAppendPolyData()
self.combinedCutlines.AddObserver('ErrorEvent', self.errorObserver)
self.combinedCutlines.AddInput(self.sectionStripperModel.GetOutput())
self.combinedCutlines.AddInput(self.sectionStripperSupports.GetOutput())
self.combinedCutlines.AddInput(self.sectionStripperBottomPlate.GetOutput())
# Create a small cone to have at least one input
# to the slice line vtkAppendPolyData in case no
# model intersections were found.
cone = vtk.vtkConeSource()
cone.SetRadius(.01)
cone.SetHeight(.01)
cone.SetResolution(6)
cone.SetCenter([-.1,-.1,-.1])
self.combinedCutlines.AddInput(cone.GetOutput())
# Bounding box. Create cube and set outline filter.
self.modelBoundingBox = vtk.vtkCubeSource()
self.modelBoundingBox.SetCenter(self.getCenter()[0], self.getCenter()[1], self.getBounds()[5]/2)
self.modelBoundingBox.SetXLength(self.getSize()[0])