chiark / gitweb /
Add back the ultimaker platform, and made the platform mesh simpler.
[cura.git] / Cura / slice / cura_sf / skeinforge_application / skeinforge_plugins / craft_plugins / chop.py
1 """
2 This page is in the table of contents.
3 Chop is a script to chop a shape into svg slice layers.
4
5 ==Settings==
6 ===Add Layer Template to SVG===
7 Default is on.
8
9 When selected, the layer template will be added to the svg output, which adds javascript control boxes.  So 'Add Layer Template to SVG' should be selected when the svg will be viewed in a browser.
10
11 When off, no controls will be added, the svg output will only include the fabrication paths.  So 'Add Layer Template to SVG' should be deselected when the svg will be used by other software, like Inkscape.
12
13 ===Add Extra Top Layer if Necessary===
14 Default is on.
15
16 When selected, chop will add an extra layer at the very top of the object if the top of the object is more than half the layer height above the first slice.  This is so the cutting tool doesn't cut too deeply through the top of the object on its first pass.
17
18 ===Extra Decimal Places===
19 Default is two.
20
21 Defines the number of extra decimal places export will output compared to the number of decimal places in the layer height.  The higher the 'Extra Decimal Places', the more significant figures the output numbers will have.
22
23 ===Import Coarseness===
24 Default is one.
25
26 When a triangle mesh has holes in it, the triangle mesh slicer switches over to a slow algorithm that spans gaps in the mesh.  The higher the 'Import Coarseness' setting, the wider the gaps in the mesh it will span.  An import coarseness of one means it will span gaps of the edge width.
27
28 ===Layer Height===
29 Default is 0.4 mm.
30
31 Defines the height of the layer, this is the most important chop setting.
32
33 ===Layers===
34 Chop slices from top to bottom.  To get only the bottom layer, set the "Layers From" to minus one.  The 'Layers From' until 'Layers To' range is a python slice.
35
36 ====Layers From====
37 Default is zero.
38
39 Defines the index of the top layer that will be chopped.  If the 'Layers From' is the default zero, the carving will start from the top layer.  If the 'Layers From' index is negative, then the carving will start from the 'Layers From' index above the bottom layer.
40
41 ====Layers To====
42 Default is a huge number, which will be limited to the highest index number.
43
44 Defines the index of the bottom layer that will be chopped.  If the 'Layers To' index is a huge number like the default, the carving will go to the bottom of the model.  If the 'Layers To' index is negative, then the carving will go to the 'Layers To' index above the bottom layer.
45
46 ===Mesh Type===
47 Default is 'Correct Mesh'.
48
49 ====Correct Mesh====
50 When selected, the mesh will be accurately chopped, and if a hole is found, chop will switch over to the algorithm that spans gaps.
51
52 ====Unproven Mesh====
53 When selected, chop will use the gap spanning algorithm from the start.  The problem with the gap spanning algothm is that it will span gaps, even if there is not actually a gap in the model.
54
55 ===Perimeter Width===
56 Default is 2 mm.
57
58 Defines the width of the edge.
59
60 ===SVG Viewer===
61 Default is webbrowser.
62
63 If the 'SVG Viewer' is set to the default 'webbrowser', the scalable vector graphics file will be sent to the default browser to be opened.  If the 'SVG Viewer' is set to a program name, the scalable vector graphics file will be sent to that program to be opened.
64
65 ==Examples==
66 The following examples chop the file Screw Holder Bottom.stl.  The examples are run in a terminal in the folder which contains Screw Holder Bottom.stl and chop.py.
67
68 > python chop.py
69 This brings up the chop dialog.
70
71 > python chop.py Screw Holder Bottom.stl
72 The chop tool is parsing the file:
73 Screw Holder Bottom.stl
74 ..
75 The chop tool has created the file:
76 .. Screw Holder Bottom_chop.svg
77
78 """
79
80 from __future__ import absolute_import
81
82 from fabmetheus_utilities.fabmetheus_tools import fabmetheus_interpret
83 from fabmetheus_utilities import archive
84 from fabmetheus_utilities import euclidean
85 from fabmetheus_utilities import gcodec
86 from fabmetheus_utilities import settings
87 from fabmetheus_utilities import svg_writer
88 from skeinforge_application.skeinforge_utilities import skeinforge_polyfile
89 from skeinforge_application.skeinforge_utilities import skeinforge_profile
90 import os
91 import sys
92 import time
93
94
95 __author__ = 'Enrique Perez (perez_enrique@yahoo.com)'
96 __date__ = '$Date: 2008/02/05 $'
97 __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
98
99
100 def getCraftedText( fileName, gcodeText = '', repository=None):
101         "Get chopped text."
102         if fileName.endswith('.svg'):
103                 gcodeText = archive.getTextIfEmpty(fileName, gcodeText)
104                 if gcodec.isProcedureDoneOrFileIsEmpty( gcodeText, 'chop'):
105                         return gcodeText
106         carving = svg_writer.getCarving(fileName)
107         if carving == None:
108                 return ''
109         if repository == None:
110                 repository = ChopRepository()
111                 settings.getReadRepository(repository)
112         return ChopSkein().getCarvedSVG( carving, fileName, repository )
113
114 def getNewRepository():
115         'Get new repository.'
116         return ChopRepository()
117
118 def writeOutput(fileName, shouldAnalyze=True):
119         "Chop a GNU Triangulated Surface file.  If no fileName is specified, chop the first GNU Triangulated Surface file in this folder."
120         startTime = time.time()
121         print('File ' + archive.getSummarizedFileName(fileName) + ' is being chopped.')
122         repository = ChopRepository()
123         settings.getReadRepository(repository)
124         chopGcode = getCraftedText( fileName, '', repository )
125         if chopGcode == '':
126                 return
127         suffixFileName = fileName[ : fileName.rfind('.') ] + '_chop.svg'
128         suffixDirectoryName = os.path.dirname(suffixFileName)
129         suffixReplacedBaseName = os.path.basename(suffixFileName).replace(' ', '_')
130         suffixFileName = os.path.join( suffixDirectoryName, suffixReplacedBaseName )
131         archive.writeFileText( suffixFileName, chopGcode )
132         print('The chopped file is saved as ' + archive.getSummarizedFileName(suffixFileName) )
133         print('It took %s to chop the file.' % euclidean.getDurationString( time.time() - startTime ) )
134         if shouldAnalyze:
135                 settings.openSVGPage( suffixFileName, repository.svgViewer.value )
136
137
138 class ChopRepository(object):
139         "A class to handle the chop settings."
140         def __init__(self):
141                 "Set the default settings, execute title & settings fileName."
142                 skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge_plugins.craft_plugins.chop.html', self )
143                 self.fileNameInput = settings.FileNameInput().getFromFileName( fabmetheus_interpret.getTranslatorFileTypeTuples(), 'Open File to be Chopped', self, '')
144                 self.addExtraTopLayerIfNecessary = settings.BooleanSetting().getFromValue('Add Extra Top Layer if Necessary', self, True )
145                 self.addLayerTemplateToSVG = settings.BooleanSetting().getFromValue('Add Layer Template to SVG', self, True)
146                 self.edgeWidth = settings.FloatSpin().getFromValue( 0.4, 'Edge Width (mm):', self, 4.0, 2.0 )
147                 self.extraDecimalPlaces = settings.FloatSpin().getFromValue(0.0, 'Extra Decimal Places (float):', self, 3.0, 2.0)
148                 self.importCoarseness = settings.FloatSpin().getFromValue( 0.5, 'Import Coarseness (ratio):', self, 2.0, 1.0 )
149                 self.layerHeight = settings.FloatSpin().getFromValue( 0.1, 'Layer Height (mm):', self, 1.0, 0.4 )
150                 self.layersFrom = settings.IntSpin().getFromValue( 0, 'Layers From (index):', self, 20, 0 )
151                 self.layersTo = settings.IntSpin().getSingleIncrementFromValue( 0, 'Layers To (index):', self, 912345678, 912345678 )
152                 self.meshTypeLabel = settings.LabelDisplay().getFromName('Mesh Type: ', self, )
153                 importLatentStringVar = settings.LatentStringVar()
154                 self.correctMesh = settings.Radio().getFromRadio( importLatentStringVar, 'Correct Mesh', self, True )
155                 self.unprovenMesh = settings.Radio().getFromRadio( importLatentStringVar, 'Unproven Mesh', self, False )
156                 self.svgViewer = settings.StringSetting().getFromValue('SVG Viewer:', self, 'webbrowser')
157                 settings.LabelSeparator().getFromRepository(self)
158                 self.executeTitle = 'Chop'
159
160         def execute(self):
161                 "Chop button has been clicked."
162                 fileNames = skeinforge_polyfile.getFileOrDirectoryTypes(self.fileNameInput.value, fabmetheus_interpret.getImportPluginFileNames(), self.fileNameInput.wasCancelled)
163                 for fileName in fileNames:
164                         writeOutput(fileName)
165
166
167 class ChopSkein(object):
168         "A class to chop a carving."
169         def addExtraTopLayerIfNecessary( self, carving, layerHeight, loopLayers ):
170                 "Add extra top layer if necessary."
171                 topRotatedBoundaryLayer = loopLayers[-1]
172                 cuttingSafeHeight = topRotatedBoundaryLayer.z + 0.5001 * layerHeight
173                 if cuttingSafeHeight > carving.getCarveCornerMaximum().z:
174                         return
175                 extraTopRotatedBoundaryLayer = topRotatedBoundaryLayer.getCopyAtZ( topRotatedBoundaryLayer.z + layerHeight )
176                 loopLayers.append( extraTopRotatedBoundaryLayer )
177
178         def getCarvedSVG( self, carving, fileName, repository ):
179                 "Parse gnu triangulated surface text and store the chopped gcode."
180                 layerHeight = repository.layerHeight.value
181                 edgeWidth = repository.edgeWidth.value
182                 carving.setCarveLayerHeight( layerHeight )
183                 importRadius = 0.5 * repository.importCoarseness.value * abs(edgeWidth)
184                 carving.setCarveImportRadius(max(importRadius, 0.001 * layerHeight))
185                 carving.setCarveIsCorrectMesh( repository.correctMesh.value )
186                 loopLayers = carving.getCarveBoundaryLayers()
187                 if len( loopLayers ) < 1:
188                         print('Warning, there are no slices for the model, this could be because the model is too small for the Layer Height.')
189                         return ''
190                 if repository.addExtraTopLayerIfNecessary.value:
191                         self.addExtraTopLayerIfNecessary( carving, layerHeight, loopLayers )
192                 loopLayers.reverse()
193                 layerHeight = carving.getCarveLayerHeight()
194                 decimalPlacesCarried = euclidean.getDecimalPlacesCarried(repository.extraDecimalPlaces.value, layerHeight)
195                 svgWriter = svg_writer.SVGWriter(
196                         repository.addLayerTemplateToSVG.value,
197                         carving.getCarveCornerMaximum(),
198                         carving.getCarveCornerMinimum(),
199                         decimalPlacesCarried,
200                         carving.getCarveLayerHeight(),
201                         edgeWidth)
202                 truncatedRotatedBoundaryLayers = svg_writer.getTruncatedRotatedBoundaryLayers(loopLayers, repository)
203                 return svgWriter.getReplacedSVGTemplate( fileName, truncatedRotatedBoundaryLayers, 'chop', carving.getFabmetheusXML())
204
205
206 def main():
207         "Display the chop dialog."
208         if len(sys.argv) > 1:
209                 writeOutput(' '.join(sys.argv[1 :]))
210         else:
211                 settings.startMainLoopFromConstructor(getNewRepository())
212
213 if __name__ == "__main__":
214         main()