chiark / gitweb /
Updated start/end code.
[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[0] < 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         'fan_speed_max': '100',\r
45         'model_scale': '1.0',\r
46         'flip_x': 'False',\r
47         'flip_y': 'False',\r
48         'flip_z': 'False',\r
49         'swap_xz': 'False',\r
50         'swap_yz': 'False',\r
51         'model_rotate_base': '0',\r
52         'model_multiply_x': '1',\r
53         'model_multiply_y': '1',\r
54         'extra_base_wall_thickness': '0.0',\r
55         'sequence': 'Loops > Perimeter > Infill',\r
56         'force_first_layer_sequence': 'True',\r
57         'infill_type': 'Line',\r
58         'solid_top': 'True',\r
59         'fill_overlap': '15',\r
60         'support_rate': '50',\r
61         'support_distance': '0.5',\r
62         'joris': 'False',\r
63         'enable_skin': 'False',\r
64         'enable_raft': 'False',\r
65         'cool_min_feedrate': '5',\r
66         'bridge_speed': '100',\r
67         'raft_margin': '5',\r
68         'raft_base_material_amount': '100',\r
69         'raft_interface_material_amount': '100',\r
70         'bottom_thickness': '0.3',\r
71         \r
72         'enable_dwindle': 'False',\r
73         'dwindle_pent_up_volume': '0.4',\r
74         'dwindle_slowdown_volume': '5.0',\r
75 \r
76         'add_start_end_gcode': 'True',\r
77         'gcode_extension': 'gcode',\r
78         'alternative_center': '',\r
79         'clear_z': '0.0',\r
80         'extruder': '0',\r
81 }\r
82 alterationDefault = {\r
83 #######################################################################################\r
84         'start.gcode': """;Sliced {filename} at: {day} {date} {time}\r
85 ;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}\r
86 ;Print time: {print_time}\r
87 ;Filament used: {filament_amount}m {filament_weight}g\r
88 ;Filament cost: {filament_cost}\r
89 G21        ;metric values\r
90 G90        ;absolute positioning\r
91 M107       ;start with the fan off\r
92 \r
93 G28 X0 Y0  ;move X/Y to min endstops\r
94 G28 Z0     ;move Z to min endstops\r
95 G92 X0 Y0 Z0 E0         ;reset software position to front/left/z=0.0\r
96 \r
97 G1 Z15.0 F{max_z_speed} ;move the platform down 15mm\r
98 \r
99 G92 E0                  ;zero the extruded length\r
100 G1 F200 E3              ;extrude 3mm of feed stock\r
101 G92 E0                  ;zero the extruded length again\r
102 \r
103 G1 X{machine_center_x} Y{machine_center_y} F{travel_speed} ;go to the middle of the platform\r
104 """,\r
105 #######################################################################################\r
106         'end.gcode': """;End GCode\r
107 M104 S0                    ;extruder heat off\r
108 G91                        ;relative positioning\r
109 G1 E-1 F300                ;retract the filament a bit before lifting the nozzle, to release some of the pressure\r
110 G1 Z+0.5 E-5 F{max_z_speed};move Z up a bit and retract filament even more\r
111 G1 Z+10 F{max_z_speed}     ;move Z up a bit more without retraction\r
112 G28 X0 Y0                  ;move X/Y to min endstops, so the head is out of the way\r
113 M84                        ;steppers off\r
114 G90                        ;absolute positioning\r
115 """,\r
116 #######################################################################################\r
117         'support_start.gcode': '',\r
118         'support_end.gcode': '',\r
119         'cool_start.gcode': '',\r
120         'cool_end.gcode': '',\r
121         'replace.csv': '',\r
122 #######################################################################################\r
123         '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
124 G92 E0\r
125 G1 Z{clear_z} E-5 F{max_z_speed}\r
126 G92 E0\r
127 G1 X{machine_center_x} Y{machine_center_y} F{travel_speed}\r
128 G1 F200 E5.5\r
129 G92 E0\r
130 G1 Z0 F{max_z_speed}\r
131 """,\r
132 #######################################################################################\r
133         'switchExtruder.gcode': """;Switch between the current extruder and the next extruder, when printing with multiple extruders.\r
134 G1 E-5 F5000\r
135 G92 E0\r
136 T{extruder}\r
137 G1 E5 F5000\r
138 G92 E0\r
139 """,\r
140 }\r
141 preferencesDefaultSettings = {\r
142         'wizardDone': 'False',\r
143         'startMode': 'Simple',\r
144         'lastFile': '',\r
145         'machine_width': '205',\r
146         'machine_depth': '205',\r
147         'machine_height': '200',\r
148         'machine_type': 'unknown',\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': 'AUTO',\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, TypeError):\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, TypeError):\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(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 == 'print_time':\r
394                 return '#P_TIME#'\r
395         if tag == 'filament_amount':\r
396                 return '#F_AMNT#'\r
397         if tag == 'filament_weight':\r
398                 return '#F_WGHT#'\r
399         if tag == 'filament_cost':\r
400                 return '#F_COST#'\r
401         if tag in ['print_speed', 'retraction_speed', 'travel_speed', 'max_z_speed', 'bottom_layer_speed', 'cool_min_feedrate']:\r
402                 f = getProfileSettingFloat(tag) * 60\r
403         elif isProfileSetting(tag):\r
404                 f = getProfileSettingFloat(tag)\r
405         elif isPreference(tag):\r
406                 f = getProfileSettingFloat(tag)\r
407         else:\r
408                 return '?%s?' % (tag)\r
409         if (f % 1) == 0:\r
410                 return str(int(f))\r
411         return str(f)\r
412 \r
413 def replaceGCodeTags(filename, gcodeInt):\r
414         f = open(filename, 'r+')\r
415         data = f.read(2048)\r
416         data = data.replace('#P_TIME#', ('%5d:%02d' % (int(gcodeInt.totalMoveTimeMinute / 60), int(gcodeInt.totalMoveTimeMinute % 60)))[-8:])\r
417         data = data.replace('#F_AMNT#', ('%8.2f' % (gcodeInt.extrusionAmount / 1000))[-8:])\r
418         data = data.replace('#F_WGHT#', ('%8.2f' % (gcodeInt.calculateWeight() * 1000))[-8:])\r
419         cost = gcodeInt.calculateCost()\r
420         if cost == False:\r
421                 cost = 'Unknown'\r
422         data = data.replace('#F_COST#', ('%8s' % (cost.split(' ')[0]))[-8:])\r
423         f.seek(0)\r
424         f.write(data)\r
425         f.close()\r
426 \r
427 ### Get aleration raw contents. (Used internally in Cura)\r
428 def getAlterationFile(filename):\r
429         #Check if we have a configuration file loaded, else load the default.\r
430         if not globals().has_key('globalProfileParser'):\r
431                 loadGlobalProfile(getDefaultProfilePath())\r
432         \r
433         if not globalProfileParser.has_option('alterations', filename):\r
434                 if filename in alterationDefault:\r
435                         default = alterationDefault[filename]\r
436                 else:\r
437                         print("Missing default alteration for: '" + filename + "'")\r
438                         alterationDefault[filename] = ''\r
439                         default = ''\r
440                 if not globalProfileParser.has_section('alterations'):\r
441                         globalProfileParser.add_section('alterations')\r
442                 #print("Using default for: %s" % (filename))\r
443                 globalProfileParser.set('alterations', filename, default)\r
444         return unicode(globalProfileParser.get('alterations', filename), "utf-8")\r
445 \r
446 def setAlterationFile(filename, value):\r
447         #Check if we have a configuration file loaded, else load the default.\r
448         if not globals().has_key('globalProfileParser'):\r
449                 loadGlobalProfile(getDefaultProfilePath())\r
450         if not globalProfileParser.has_section('alterations'):\r
451                 globalProfileParser.add_section('alterations')\r
452         globalProfileParser.set('alterations', filename, value.encode("utf-8"))\r
453         saveGlobalProfile(getDefaultProfilePath())\r
454 \r
455 ### Get the alteration file for output. (Used by Skeinforge)\r
456 def getAlterationFileContents(filename):\r
457         prefix = ''\r
458         postfix = ''\r
459         alterationContents = getAlterationFile(filename)\r
460         if filename == 'start.gcode':\r
461                 #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
462                 #We also set our steps per E here, if configured.\r
463                 eSteps = getPreferenceFloat('steps_per_e')\r
464                 if eSteps > 0:\r
465                         prefix += 'M92 E%f\n' % (eSteps)\r
466                 temp = getProfileSettingFloat('print_temperature')\r
467                 if temp > 0 and not '{print_temperature}' in alterationContents:\r
468                         prefix += 'M109 S%f\n' % (temp)\r
469         elif filename == 'end.gcode':\r
470                 #Append the profile string to the end of the GCode, so we can load it from the GCode file later.\r
471                 postfix = ';CURA_PROFILE_STRING:%s\n' % (getGlobalProfileString())\r
472         elif filename == 'replace.csv':\r
473                 #Always remove the extruder on/off M codes. These are no longer needed in 5D printing.\r
474                 prefix = 'M101\nM103\n'\r
475         \r
476         return unicode(prefix + re.sub("\{([^\}]*)\}", replaceTagMatch, alterationContents).rstrip() + '\n' + postfix).encode('utf-8')\r
477 \r