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 / carve.py
1 """
2 This page is in the table of contents.
3 Carve is the most important plugin to define for your printer.
4
5 It carves a shape into svg slice layers.  It also sets the layer height and edge width for the rest of the tool chain.
6
7 The carve manual page is at:
8 http://fabmetheus.crsndoo.com/wiki/index.php/Skeinforge_Carve
9
10 On the Arcol Blog a method of deriving the layer height is posted.  That article "Machine Calibrating" is at:
11 http://blog.arcol.hu/?p=157
12
13 ==Settings==
14 ===Add Layer Template to SVG===
15 Default is on.
16
17 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.
18
19 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.
20
21 ===Edge Width over Height===
22 Default is 1.8.
23
24 Defines the ratio of the extrusion edge width to the layer height.  This parameter tells skeinforge how wide the edge wall is expected to be in relation to the layer height.  Default value of 1.8 for the default layer height of 0.4 states that a single filament edge wall should be 0.4 mm * 1.8 = 0.72 mm wide.  The higher the value the more the edge will be inset.  A ratio of one means the extrusion is a circle, the default ratio of 1.8 means the extrusion is a wide oval.
25
26 This is an important value because if you are calibrating your machine you need to ensure that the speed of the head and the extrusion rate in combination produce a wall that is 'Layer Height' * 'Edge Width over Height' wide. To start with 'Edge Width over Height' is probably best left at the default of 1.8 and the extrusion rate adjusted to give the correct calculated wall thickness.
27
28 Adjustment is in the 'Speed' section with 'Feed Rate' controlling speed of the head in X & Y and 'Flow Rate' controlling the extrusion rate.  Initially it is probably easier to start adjusting the flow rate only a little at a time until you get a single filament of the correct width. If you change too many parameters at once you can get in a right mess.
29
30 ===Extra Decimal Places===
31 Default is two.
32
33 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.
34
35 ===Import Coarseness===
36 Default is one.
37
38 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.
39
40 ===Layer Height===
41 Default is 0.4 mm.
42
43 Defines the the height of the layers skeinforge will cut your object into, in the z direction.  This is the most important carve setting, many values in the toolchain are derived from the layer height.
44
45 For a 0.5 mm nozzle usable values are 0.3 mm to 0.5 mm.  Note; if you are using thinner layers make sure to adjust the extrusion speed as well.
46
47 ===Layers===
48 Carve slices from bottom to top.  To get a single layer, set the "Layers From" to zero and the "Layers To" to one.  The 'Layers From' until 'Layers To' range is a python slice.
49
50 ====Layers From====
51 Default is zero.
52
53 Defines the index of the bottom layer that will be carved.  If the 'Layers From' is the default zero, the carving will start from the lowest layer.  If the 'Layers From' index is negative, then the carving will start from the 'Layers From' index below the top layer.
54
55 For example if your object is 5 mm tall and your layer thicknes is 1 mm if you set layers from to 3 you will ignore the first 3 mm and start from 3 mm.
56
57 ====Layers To====
58 Default is a huge number, which will be limited to the highest index layer.
59
60 Defines the index of the top layer that will be carved.  If the 'Layers To' index is a huge number like the default, the carving will go to the top of the model.  If the 'Layers To' index is negative, then the carving will go to the 'Layers To' index below the top layer.
61
62 This is the same as layers from, only it defines when to end the generation of gcode.
63
64 ===Mesh Type===
65 Default is 'Correct Mesh'.
66
67 ====Correct Mesh====
68 When selected, the mesh will be accurately carved, and if a hole is found, carve will switch over to the algorithm that spans gaps.
69
70 ====Unproven Mesh====
71 When selected, carve 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.
72
73 ===SVG Viewer===
74 Default is webbrowser.
75
76 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.
77
78 ==Examples==
79 The following examples carve the file Screw Holder Bottom.stl.  The examples are run in a terminal in the folder which contains Screw Holder Bottom.stl and carve.py.
80
81 > python carve.py
82 This brings up the carve dialog.
83
84 > python carve.py Screw Holder Bottom.stl
85 The carve tool is parsing the file:
86 Screw Holder Bottom.stl
87 ..
88 The carve tool has created the file:
89 .. Screw Holder Bottom_carve.svg
90
91 """
92
93 from __future__ import absolute_import
94
95 from fabmetheus_utilities.fabmetheus_tools import fabmetheus_interpret
96 from fabmetheus_utilities import archive
97 from fabmetheus_utilities import euclidean
98 from fabmetheus_utilities import gcodec
99 from fabmetheus_utilities import settings
100 from fabmetheus_utilities import svg_writer
101 from skeinforge_application.skeinforge_utilities import skeinforge_polyfile
102 from skeinforge_application.skeinforge_utilities import skeinforge_profile
103 from fabmetheus_utilities.vector3 import Vector3
104 import math
105 import sys
106 import time
107
108 __author__ = 'Enrique Perez (perez_enrique@yahoo.com)'
109 __date__ = '$Date: 2008/02/05 $'
110 __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
111
112
113 def getCraftedText( fileName, gcodeText = '', repository=None):
114         "Get carved text."
115         if fileName.endswith('.svg'):
116                 gcodeText = archive.getTextIfEmpty(fileName, gcodeText)
117                 if gcodec.isProcedureDoneOrFileIsEmpty( gcodeText, 'carve'):
118                         return gcodeText
119         carving = svg_writer.getCarving(fileName)
120         if carving == None:
121                 return ''
122         if repository == None:
123                 repository = CarveRepository()
124                 settings.getReadRepository(repository)
125         return CarveSkein().getCarvedSVG( carving, fileName, repository )
126
127 def getNewRepository():
128         'Get new repository.'
129         return CarveRepository()
130
131 def writeOutput(fileName, shouldAnalyze=True):
132         "Carve a GNU Triangulated Surface file."
133         startTime = time.time()
134         print('File ' + archive.getSummarizedFileName(fileName) + ' is being carved.')
135         repository = CarveRepository()
136         settings.getReadRepository(repository)
137         carveGcode = getCraftedText(fileName, '', repository)
138         if carveGcode == '':
139                 return
140         suffixFileName = archive.getFilePathWithUnderscoredBasename(fileName, '_carve.svg')
141         archive.writeFileText(suffixFileName, carveGcode)
142         print('The carved file is saved as ' + archive.getSummarizedFileName(suffixFileName))
143         print('It took %s to carve the file.' % euclidean.getDurationString(time.time() - startTime))
144         if shouldAnalyze:
145                 settings.openSVGPage(suffixFileName, repository.svgViewer.value)
146
147
148 class CarveRepository(object):
149         "A class to handle the carve settings."
150         def __init__(self):
151                 "Set the default settings, execute title & settings fileName."
152                 skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge_plugins.craft_plugins.carve.html', self )
153                 self.fileNameInput = settings.FileNameInput().getFromFileName( fabmetheus_interpret.getTranslatorFileTypeTuples(), 'Open File for Carve', self, '')
154                 self.openWikiManualHelpPage = settings.HelpPage().getOpenFromAbsolute('http://fabmetheus.crsndoo.com/wiki/index.php/Skeinforge_Carve')
155                 self.addLayerTemplateToSVG = settings.BooleanSetting().getFromValue('Add Layer Template to SVG', self, True)
156                 self.edgeWidth = settings.FloatSpin().getFromValue( 0.1, 'Edge Width (mm):', self, 2.2, 0.4 )
157                 self.extraDecimalPlaces = settings.FloatSpin().getFromValue(0.0, 'Extra Decimal Places (float):', self, 3.0, 2.0)
158                 self.importCoarseness = settings.FloatSpin().getFromValue( 0.5, 'Import Coarseness (ratio):', self, 2.0, 1.0 )
159                 self.layerHeight = settings.FloatSpin().getFromValue( 0.1, 'Layer Height (mm):', self, 1.0, 0.2 )
160                 settings.LabelSeparator().getFromRepository(self)
161                 settings.LabelDisplay().getFromName('- Layers -', self )
162                 self.layersFrom = settings.IntSpin().getFromValue( 0, 'Layers From (index):', self, 20, 0 )
163                 self.layersTo = settings.IntSpin().getSingleIncrementFromValue( 0, 'Layers To (index):', self, 912345678, 912345678 )
164                 settings.LabelSeparator().getFromRepository(self)
165                 self.meshTypeLabel = settings.LabelDisplay().getFromName('Mesh Type: ', self )
166                 importLatentStringVar = settings.LatentStringVar()
167                 self.correctMesh = settings.Radio().getFromRadio( importLatentStringVar, 'Correct Mesh', self, True )
168                 self.unprovenMesh = settings.Radio().getFromRadio( importLatentStringVar, 'Unproven Mesh', self, False )
169                 self.svgViewer = settings.StringSetting().getFromValue('SVG Viewer:', self, 'webbrowser')
170                 settings.LabelSeparator().getFromRepository(self)
171                 self.executeTitle = 'Carve'
172
173                 self.centerX = settings.FloatSpin().getFromValue(0.0, 'CenterX', self, 1000.0, 0.0);
174                 self.centerY = settings.FloatSpin().getFromValue(0.0, 'CenterY', self, 1000.0, 0.0);
175                 self.objectSink = settings.FloatSpin().getFromValue(0.0, 'ObjectSink', self, 1000.0, 0.0)
176                 self.matrix = settings.StringSetting().getFromValue('ObjectMatrix', self, '1,0,0,0,1,0,0,0,1')
177                 self.alternativeCenter = settings.StringSetting().getFromValue('AlternativeCenterFile', self, '')
178
179
180         def execute(self):
181                 "Carve button has been clicked."
182                 fileNames = skeinforge_polyfile.getFileOrDirectoryTypes(self.fileNameInput.value, fabmetheus_interpret.getImportPluginFileNames(), self.fileNameInput.wasCancelled)
183                 for fileName in fileNames:
184                         writeOutput(fileName)
185
186
187 class CarveSkein(object):
188         "A class to carve a carving."
189         def getCarvedSVG(self, carving, fileName, repository):
190                 "Parse gnu triangulated surface text and store the carved gcode."
191
192                 matrix = map(float, repository.matrix.value.split(','))
193
194                 for i in xrange(0, len(carving.vertexes)):
195                         x = carving.vertexes[i].x
196                         y = carving.vertexes[i].y
197                         z = carving.vertexes[i].z
198                         carving.vertexes[i] = Vector3(
199                                 x * matrix[0] + y * matrix[3] + z * matrix[6],
200                                 x * matrix[1] + y * matrix[4] + z * matrix[7],
201                                 x * matrix[2] + y * matrix[5] + z * matrix[8])
202
203                 if repository.alternativeCenter.value != '':
204                         carving2 = svg_writer.getCarving(repository.alternativeCenter.value)
205                         for i in xrange(0, len(carving2.vertexes)):
206                                 x = carving2.vertexes[i].x
207                                 y = carving2.vertexes[i].y
208                                 z = carving2.vertexes[i].z
209                                 carving2.vertexes[i] = Vector3(
210                                         x * matrix[0] + y * matrix[3] + z * matrix[6],
211                                         x * matrix[1] + y * matrix[4] + z * matrix[7],
212                                         x * matrix[2] + y * matrix[5] + z * matrix[8])
213                         minZ = carving2.getMinimumZ()
214                         minSize = carving2.getCarveCornerMinimum()
215                         maxSize = carving2.getCarveCornerMaximum()
216                 else:
217                         minZ = carving.getMinimumZ()
218                         minSize = carving.getCarveCornerMinimum()
219                         maxSize = carving.getCarveCornerMaximum()
220                 for v in carving.vertexes:
221                         v.z -= minZ + repository.objectSink.value
222                         v.x -= minSize.x + (maxSize.x - minSize.x) / 2
223                         v.y -= minSize.y + (maxSize.y - minSize.y) / 2
224                         v.x += repository.centerX.value
225                         v.y += repository.centerY.value
226
227                 layerHeight = repository.layerHeight.value
228                 edgeWidth = repository.edgeWidth.value
229                 carving.setCarveLayerHeight(layerHeight)
230                 importRadius = 0.5 * repository.importCoarseness.value * abs(edgeWidth)
231                 carving.setCarveImportRadius(max(importRadius, 0.001 * layerHeight))
232                 carving.setCarveIsCorrectMesh(repository.correctMesh.value)
233                 loopLayers = carving.getCarveBoundaryLayers()
234                 if len(loopLayers) < 1:
235                         print('Warning, there are no slices for the model, this could be because the model is too small for the Layer Height.')
236                         return ''
237                 layerHeight = carving.getCarveLayerHeight()
238                 decimalPlacesCarried = euclidean.getDecimalPlacesCarried(repository.extraDecimalPlaces.value, layerHeight)
239                 edgeWidth = repository.edgeWidth.value
240                 svgWriter = svg_writer.SVGWriter(
241                         repository.addLayerTemplateToSVG.value,
242                         carving.getCarveCornerMaximum(),
243                         carving.getCarveCornerMinimum(),
244                         decimalPlacesCarried,
245                         carving.getCarveLayerHeight(),
246                         edgeWidth)
247                 truncatedRotatedBoundaryLayers = svg_writer.getTruncatedRotatedBoundaryLayers(loopLayers, repository)
248                 return svgWriter.getReplacedSVGTemplate(fileName, truncatedRotatedBoundaryLayers, 'carve', carving.getFabmetheusXML())
249
250
251 def main():
252         "Display the carve dialog."
253         if len(sys.argv) > 1:
254                 writeOutput(' '.join(sys.argv[1 :]))
255         else:
256                 settings.startMainLoopFromConstructor(getNewRepository())
257
258 if __name__ == "__main__":
259         main()