chiark / gitweb /
Added copy to SD feature. Fixed #138
[cura.git] / Cura / util / profile.py
1 from __future__ import absolute_import\r
2 from __future__ import division\r
3 #Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module.\r
4 import __init__\r
5 \r
6 import os, traceback, math, re, zlib, base64, time, sys\r
7 if sys.version_info.major < 3:\r
8         import ConfigParser\r
9 else:\r
10         import configparser as ConfigParser\r
11 \r
12 #########################################################\r
13 ## Default settings when none are found.\r
14 #########################################################\r
15 \r
16 #Single place to store the defaults, so we have a consistent set of default settings.\r
17 profileDefaultSettings = {\r
18         'nozzle_size': '0.4',\r
19         'layer_height': '0.2',\r
20         'wall_thickness': '0.8',\r
21         'solid_layer_thickness': '0.6',\r
22         'fill_density': '20',\r
23         'skirt_line_count': '1',\r
24         'skirt_gap': '3.0',\r
25         'print_speed': '50',\r
26         'print_temperature': '0',\r
27         'support': 'None',\r
28         'filament_diameter': '2.89',\r
29         'filament_density': '1.00',\r
30         'machine_center_x': '100',\r
31         'machine_center_y': '100',\r
32         'retraction_min_travel': '5.0',\r
33         'retraction_speed': '40.0',\r
34         'retraction_amount': '0.0',\r
35         'retraction_extra': '0.0',\r
36         'retract_on_jumps_only': 'True',\r
37         'travel_speed': '150',\r
38         'max_z_speed': '3.0',\r
39         'bottom_layer_speed': '20',\r
40         'cool_min_layer_time': '10',\r
41         'fan_enabled': 'True',\r
42         'fan_layer': '1',\r
43         'fan_speed': '100',\r
44         'model_scale': '1.0',\r
45         'flip_x': 'False',\r
46         'flip_y': 'False',\r
47         'flip_z': 'False',\r
48         'swap_xz': 'False',\r
49         'swap_yz': 'False',\r
50         'model_rotate_base': '0',\r
51         'model_multiply_x': '1',\r
52         'model_multiply_y': '1',\r
53         'extra_base_wall_thickness': '0.0',\r
54         'sequence': 'Loops > Perimeter > Infill',\r
55         'force_first_layer_sequence': 'True',\r
56         'infill_type': 'Line',\r
57         'solid_top': 'True',\r
58         'fill_overlap': '15',\r
59         'support_rate': '50',\r
60         'support_distance': '0.5',\r
61         'joris': 'False',\r
62         'enable_skin': 'False',\r
63         'enable_raft': 'False',\r
64         'cool_min_feedrate': '5',\r
65         'bridge_speed': '100',\r
66         'raft_margin': '5',\r
67         'raft_base_material_amount': '100',\r
68         'raft_interface_material_amount': '100',\r
69         'bottom_thickness': '0.3',\r
70         \r
71         'enable_dwindle': 'False',\r
72         'dwindle_pent_up_volume': '0.4',\r
73         'dwindle_slowdown_volume': '5.0',\r
74 \r
75         'add_start_end_gcode': 'True',\r
76         'gcode_extension': 'gcode',\r
77         'alternative_center': '',\r
78         'clear_z': '0.0',\r
79         'extruder': '0',\r
80 }\r
81 alterationDefault = {\r
82 #######################################################################################\r
83         'start.gcode': """;Sliced at: {day} {date} {time}\r
84 ;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}\r
85 G21        ;metric values\r
86 G90        ;absolute positioning\r
87 M107       ;start with the fan off\r
88 \r
89 G28 X0 Y0  ;move X/Y to min endstops\r
90 G28 Z0     ;move Z to min endstops\r
91 \r
92 ; if your prints start too high, try changing the Z0.0 below\r
93 ; to Z1.0 - the number after the Z is the actual, physical\r
94 ; height of the nozzle in mm. This can take some messing around\r
95 ; with to get just right...\r
96 G92 X0 Y0 Z0 E0         ;reset software position to front/left/z=0.0\r
97 G1 Z15.0 F{max_z_speed} ;move the platform down 15mm\r
98 G92 E0                  ;zero the extruded length\r
99 \r
100 G1 F200 E5              ;extrude 5mm of feed stock\r
101 G1 F200 E3.5            ;reverse feed stock by 1.5mm\r
102 G92 E0                  ;zero the extruded length again\r
103 \r
104 ;go to the middle of the platform, and move to Z=0 before starting the print.\r
105 G1 X{machine_center_x} Y{machine_center_y} F{travel_speed}\r
106 G1 Z0.0 F{max_z_speed}\r
107 """,\r
108 #######################################################################################\r
109         'end.gcode': """;End GCode\r
110 M104 S0                    ;extruder heat off\r
111 G91                        ;relative positioning\r
112 G1 Z+10 E-5 F{max_z_speed} ;move Z up a bit and retract filament by 5mm\r
113 G28 X0 Y0                  ;move X/Y to min endstops, so the head is out of the way\r
114 M84                        ;steppers off\r
115 G90                        ;absolute positioning\r
116 """,\r
117 #######################################################################################\r
118         'support_start.gcode': '',\r
119         'support_end.gcode': '',\r
120         'cool_start.gcode': '',\r
121         'cool_end.gcode': '',\r
122         'replace.csv': '',\r
123 #######################################################################################\r
124         'nextobject.gcode': """;Move to next object on the platform. clear_z is the minimal z height we need to make sure we do not hit any objects.\r
125 G92 E0\r
126 G1 Z{clear_z} E-5 F{max_z_speed}\r
127 G92 E0\r
128 G1 X{machine_center_x} Y{machine_center_y} F{travel_speed}\r
129 G1 F200 E5.5\r
130 G92 E0\r
131 G1 Z0 F{max_z_speed}\r
132 """,\r
133 #######################################################################################\r
134         'switchExtruder.gcode': """;Switch between the current extruder and the next extruder, when printing with multiple extruders.\r
135 G1 E-5 F5000\r
136 G92 E0\r
137 T{extruder}\r
138 G1 E5 F5000\r
139 G92 E0\r
140 """,\r
141 }\r
142 preferencesDefaultSettings = {\r
143         'wizardDone': 'False',\r
144         'startMode': 'Simple',\r
145         'lastFile': '',\r
146         'machine_width': '205',\r
147         'machine_depth': '205',\r
148         'machine_height': '200',\r
149         'extruder_amount': '1',\r
150         'extruder_offset_x1': '-22.0',\r
151         'extruder_offset_y1': '0.0',\r
152         'extruder_offset_x2': '0.0',\r
153         'extruder_offset_y2': '0.0',\r
154         'extruder_offset_x3': '0.0',\r
155         'extruder_offset_y3': '0.0',\r
156         'filament_density': '1300',\r
157         'steps_per_e': '0',\r
158         'serial_port': 'AUTO',\r
159         'serial_baud': '250000',\r
160         'slicer': 'Cura (Skeinforge based)',\r
161         'save_profile': 'False',\r
162         'filament_cost_kg': '0',\r
163         'filament_cost_meter': '0',\r
164         'sdpath': '',\r
165         'sdshortnames': 'True',\r
166         \r
167         'extruder_head_size_min_x': '70.0',\r
168         'extruder_head_size_min_y': '18.0',\r
169         'extruder_head_size_max_x': '18.0',\r
170         'extruder_head_size_max_y': '35.0',\r
171 }\r
172 \r
173 #########################################################\r
174 ## Profile and preferences functions\r
175 #########################################################\r
176 \r
177 ## Profile functions\r
178 def getDefaultProfilePath():\r
179         basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))\r
180         #If we have a frozen python install, we need to step out of the library.zip\r
181         if hasattr(sys, 'frozen'):\r
182                 basePath = os.path.normpath(os.path.join(basePath, ".."))\r
183         return os.path.normpath(os.path.join(basePath, "current_profile.ini"))\r
184 \r
185 def loadGlobalProfile(filename):\r
186         #Read a configuration file as global config\r
187         global globalProfileParser\r
188         globalProfileParser = ConfigParser.ConfigParser()\r
189         globalProfileParser.read(filename)\r
190 \r
191 def resetGlobalProfile():\r
192         #Read a configuration file as global config\r
193         global globalProfileParser\r
194         globalProfileParser = ConfigParser.ConfigParser()\r
195 \r
196 def saveGlobalProfile(filename):\r
197         #Save the current profile to an ini file\r
198         globalProfileParser.write(open(filename, 'w'))\r
199 \r
200 def loadGlobalProfileFromString(options):\r
201         global globalProfileParser\r
202         globalProfileParser = ConfigParser.ConfigParser()\r
203         globalProfileParser.add_section('profile')\r
204         globalProfileParser.add_section('alterations')\r
205         options = base64.b64decode(options)\r
206         options = zlib.decompress(options)\r
207         (profileOpts, alt) = options.split('\f', 1)\r
208         for option in profileOpts.split('\b'):\r
209                 if len(option) > 0:\r
210                         (key, value) = option.split('=', 1)\r
211                         globalProfileParser.set('profile', key, value)\r
212         for option in alt.split('\b'):\r
213                 if len(option) > 0:\r
214                         (key, value) = option.split('=', 1)\r
215                         globalProfileParser.set('alterations', key, value)\r
216 \r
217 def getGlobalProfileString():\r
218         global globalProfileParser\r
219         if not globals().has_key('globalProfileParser'):\r
220                 loadGlobalProfile(getDefaultProfilePath())\r
221         \r
222         p = []\r
223         alt = []\r
224         tempDone = []\r
225         if globalProfileParser.has_section('profile'):\r
226                 for key in globalProfileParser.options('profile'):\r
227                         if key in tempOverride:\r
228                                 p.append(key + "=" + unicode(tempOverride[key]))\r
229                                 tempDone.append(key)\r
230                         else:\r
231                                 p.append(key + "=" + globalProfileParser.get('profile', key))\r
232         if globalProfileParser.has_section('alterations'):\r
233                 for key in globalProfileParser.options('alterations'):\r
234                         if key in tempOverride:\r
235                                 p.append(key + "=" + tempOverride[key])\r
236                                 tempDone.append(key)\r
237                         else:\r
238                                 alt.append(key + "=" + globalProfileParser.get('alterations', key))\r
239         for key in tempOverride:\r
240                 if key not in tempDone:\r
241                         p.append(key + "=" + unicode(tempOverride[key]))\r
242         ret = '\b'.join(p) + '\f' + '\b'.join(alt)\r
243         ret = base64.b64encode(zlib.compress(ret, 9))\r
244         return ret\r
245 \r
246 def getProfileSetting(name):\r
247         if name in tempOverride:\r
248                 return unicode(tempOverride[name])\r
249         #Check if we have a configuration file loaded, else load the default.\r
250         if not globals().has_key('globalProfileParser'):\r
251                 loadGlobalProfile(getDefaultProfilePath())\r
252         if not globalProfileParser.has_option('profile', name):\r
253                 if name in profileDefaultSettings:\r
254                         default = profileDefaultSettings[name]\r
255                 else:\r
256                         print("Missing default setting for: '" + name + "'")\r
257                         profileDefaultSettings[name] = ''\r
258                         default = ''\r
259                 if not globalProfileParser.has_section('profile'):\r
260                         globalProfileParser.add_section('profile')\r
261                 globalProfileParser.set('profile', name, str(default))\r
262                 #print(name + " not found in profile, so using default: " + str(default))\r
263                 return default\r
264         return globalProfileParser.get('profile', name)\r
265 \r
266 def getProfileSettingFloat(name):\r
267         try:\r
268                 return float(eval(getProfileSetting(name), {}, {}))\r
269         except (ValueError, SyntaxError):\r
270                 return 0.0\r
271 \r
272 def putProfileSetting(name, value):\r
273         #Check if we have a configuration file loaded, else load the default.\r
274         if not globals().has_key('globalProfileParser'):\r
275                 loadGlobalProfile(getDefaultProfilePath())\r
276         if not globalProfileParser.has_section('profile'):\r
277                 globalProfileParser.add_section('profile')\r
278         globalProfileParser.set('profile', name, str(value))\r
279 \r
280 def isProfileSetting(name):\r
281         if name in profileDefaultSettings:\r
282                 return True\r
283         return False\r
284 \r
285 ## Preferences functions\r
286 global globalPreferenceParser\r
287 globalPreferenceParser = None\r
288 \r
289 def getPreferencePath():\r
290         basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))\r
291         #If we have a frozen python install, we need to step out of the library.zip\r
292         if hasattr(sys, 'frozen'):\r
293                 basePath = os.path.normpath(os.path.join(basePath, ".."))\r
294         return os.path.normpath(os.path.join(basePath, "preferences.ini"))\r
295 \r
296 def getPreferenceFloat(name):\r
297         try:\r
298                 return float(eval(getPreference(name), {}, {}))\r
299         except (ValueError, SyntaxError):\r
300                 return 0.0\r
301 \r
302 def getPreference(name):\r
303         if name in tempOverride:\r
304                 return unicode(tempOverride[name])\r
305         global globalPreferenceParser\r
306         if globalPreferenceParser == None:\r
307                 globalPreferenceParser = ConfigParser.ConfigParser()\r
308                 globalPreferenceParser.read(getPreferencePath())\r
309         if not globalPreferenceParser.has_option('preference', name):\r
310                 if name in preferencesDefaultSettings:\r
311                         default = preferencesDefaultSettings[name]\r
312                 else:\r
313                         print("Missing default setting for: '" + name + "'")\r
314                         preferencesDefaultSettings[name] = ''\r
315                         default = ''\r
316                 if not globalPreferenceParser.has_section('preference'):\r
317                         globalPreferenceParser.add_section('preference')\r
318                 globalPreferenceParser.set('preference', name, str(default))\r
319                 #print(name + " not found in preferences, so using default: " + str(default))\r
320                 return default\r
321         return unicode(globalPreferenceParser.get('preference', name), "utf-8")\r
322 \r
323 def putPreference(name, value):\r
324         #Check if we have a configuration file loaded, else load the default.\r
325         global globalPreferenceParser\r
326         if globalPreferenceParser == None:\r
327                 globalPreferenceParser = ConfigParser.ConfigParser()\r
328                 globalPreferenceParser.read(getPreferencePath())\r
329         if not globalPreferenceParser.has_section('preference'):\r
330                 globalPreferenceParser.add_section('preference')\r
331         globalPreferenceParser.set('preference', name, unicode(value).encode("utf-8"))\r
332         globalPreferenceParser.write(open(getPreferencePath(), 'w'))\r
333 \r
334 def isPreference(name):\r
335         if name in preferencesDefaultSettings:\r
336                 return True\r
337         return False\r
338 \r
339 ## Temp overrides for multi-extruder slicing and the project planner.\r
340 tempOverride = {}\r
341 def setTempOverride(name, value):\r
342         tempOverride[name] = value\r
343 def resetTempOverride():\r
344         tempOverride.clear()\r
345 \r
346 #########################################################\r
347 ## Utility functions to calculate common profile values\r
348 #########################################################\r
349 def calculateEdgeWidth():\r
350         wallThickness = getProfileSettingFloat('wall_thickness')\r
351         nozzleSize = getProfileSettingFloat('nozzle_size')\r
352         \r
353         if wallThickness < nozzleSize:\r
354                 return wallThickness\r
355 \r
356         lineCount = int(wallThickness / nozzleSize)\r
357         lineWidth = wallThickness / lineCount\r
358         lineWidthAlt = wallThickness / (lineCount + 1)\r
359         if lineWidth > nozzleSize * 1.5:\r
360                 return lineWidthAlt\r
361         return lineWidth\r
362 \r
363 def calculateLineCount():\r
364         wallThickness = getProfileSettingFloat('wall_thickness')\r
365         nozzleSize = getProfileSettingFloat('nozzle_size')\r
366         \r
367         if wallThickness < nozzleSize:\r
368                 return 1\r
369 \r
370         lineCount = int(wallThickness / nozzleSize + 0.0001)\r
371         lineWidth = wallThickness / lineCount\r
372         lineWidthAlt = wallThickness / (lineCount + 1)\r
373         if lineWidth > nozzleSize * 1.5:\r
374                 return lineCount + 1\r
375         return lineCount\r
376 \r
377 def calculateSolidLayerCount():\r
378         layerHeight = getProfileSettingFloat('layer_height')\r
379         solidThickness = getProfileSettingFloat('solid_layer_thickness')\r
380         return int(math.ceil(solidThickness / layerHeight - 0.0001))\r
381 \r
382 #########################################################\r
383 ## Alteration file functions\r
384 #########################################################\r
385 def replaceTagMatch(m):\r
386         tag = m.group(0)[1:-1]\r
387         if tag == 'time':\r
388                 return time.strftime('%H:%M:%S')\r
389         if tag == 'date':\r
390                 return time.strftime('%d %b %Y')\r
391         if tag == 'day':\r
392                 return time.strftime('%a')\r
393         if tag in ['print_speed', 'retraction_speed', 'travel_speed', 'max_z_speed', 'bottom_layer_speed', 'cool_min_feedrate']:\r
394                 f = getProfileSettingFloat(tag) * 60\r
395         elif isProfileSetting(tag):\r
396                 f = getProfileSettingFloat(tag)\r
397         elif isPreference(tag):\r
398                 f = getProfileSettingFloat(tag)\r
399         else:\r
400                 return tag\r
401         if (f % 1) == 0:\r
402                 return str(int(f))\r
403         return str(f)\r
404 \r
405 ### Get aleration raw contents. (Used internally in Cura)\r
406 def getAlterationFile(filename):\r
407         #Check if we have a configuration file loaded, else load the default.\r
408         if not globals().has_key('globalProfileParser'):\r
409                 loadGlobalProfile(getDefaultProfilePath())\r
410         \r
411         if not globalProfileParser.has_option('alterations', filename):\r
412                 if filename in alterationDefault:\r
413                         default = alterationDefault[filename]\r
414                 else:\r
415                         print("Missing default alteration for: '" + filename + "'")\r
416                         alterationDefault[filename] = ''\r
417                         default = ''\r
418                 if not globalProfileParser.has_section('alterations'):\r
419                         globalProfileParser.add_section('alterations')\r
420                 #print("Using default for: %s" % (filename))\r
421                 globalProfileParser.set('alterations', filename, default)\r
422         return unicode(globalProfileParser.get('alterations', filename), "utf-8")\r
423 \r
424 def setAlterationFile(filename, value):\r
425         #Check if we have a configuration file loaded, else load the default.\r
426         if not globals().has_key('globalProfileParser'):\r
427                 loadGlobalProfile(getDefaultProfilePath())\r
428         if not globalProfileParser.has_section('alterations'):\r
429                 globalProfileParser.add_section('alterations')\r
430         globalProfileParser.set('alterations', filename, value.encode("utf-8"))\r
431         saveGlobalProfile(getDefaultProfilePath())\r
432 \r
433 ### Get the alteration file for output. (Used by Skeinforge)\r
434 def getAlterationFileContents(filename):\r
435         prefix = ''\r
436         alterationContents = getAlterationFile(filename)\r
437         if filename == 'start.gcode':\r
438                 #For the start code, hack the temperature and the steps per E value into it. So the temperature is reached before the start code extrusion.\r
439                 #We also set our steps per E here, if configured.\r
440                 eSteps = getPreferenceFloat('steps_per_e')\r
441                 if eSteps > 0:\r
442                         prefix += 'M92 E%f\n' % (eSteps)\r
443                 temp = getProfileSettingFloat('print_temperature')\r
444                 if temp > 0 and not '{print_temperature}' in alterationContents:\r
445                         prefix += 'M109 S%f\n' % (temp)\r
446         elif filename == 'replace.csv':\r
447                 #Always remove the extruder on/off M codes. These are no longer needed in 5D printing.\r
448                 prefix = 'M101\nM103\n'\r
449         \r
450         return unicode(prefix + re.sub("\{[^\}]*\}", replaceTagMatch, alterationContents).rstrip() + '\n').encode('utf-8')\r
451 \r