chiark / gitweb /
Start the first run wizard when we do not know the machine type. Only show the defaul...
[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': '220',\r
27         'print_bed_temperature': '70',\r
28         'support': 'None',\r
29         'filament_diameter': '2.89',\r
30         'filament_density': '1.00',\r
31         'machine_center_x': '100',\r
32         'machine_center_y': '100',\r
33         'retraction_min_travel': '5.0',\r
34         'retraction_enable': 'False',\r
35         'retraction_speed': '40.0',\r
36         'retraction_amount': '4.5',\r
37         'retraction_extra': '0.0',\r
38         'retract_on_jumps_only': 'True',\r
39         'travel_speed': '150',\r
40         'max_z_speed': '3.0',\r
41         'bottom_layer_speed': '20',\r
42         'cool_min_layer_time': '10',\r
43         'fan_enabled': 'True',\r
44         'fan_layer': '1',\r
45         'fan_speed': '100',\r
46         'fan_speed_max': '100',\r
47         'model_scale': '1.0',\r
48         'flip_x': 'False',\r
49         'flip_y': 'False',\r
50         'flip_z': 'False',\r
51         'swap_xz': 'False',\r
52         'swap_yz': 'False',\r
53         'model_rotate_base': '0',\r
54         'model_multiply_x': '1',\r
55         'model_multiply_y': '1',\r
56         'extra_base_wall_thickness': '0.0',\r
57         'sequence': 'Loops > Perimeter > Infill',\r
58         'force_first_layer_sequence': 'True',\r
59         'infill_type': 'Line',\r
60         'solid_top': 'True',\r
61         'fill_overlap': '15',\r
62         'support_rate': '50',\r
63         'support_distance': '0.5',\r
64         'support_dual_extrusion': 'False',\r
65         'joris': 'False',\r
66         'enable_skin': 'False',\r
67         'enable_raft': 'False',\r
68         'cool_min_feedrate': '10',\r
69         'bridge_speed': '100',\r
70         'raft_margin': '5',\r
71         'raft_base_material_amount': '100',\r
72         'raft_interface_material_amount': '100',\r
73         'bottom_thickness': '0.3',\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 {filename} at: {day} {date} {time}\r
84 ;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}\r
85 ;Print time: {print_time}\r
86 ;Filament used: {filament_amount}m {filament_weight}g\r
87 ;Filament cost: {filament_cost}\r
88 G21        ;metric values\r
89 G90        ;absolute positioning\r
90 M107       ;start with the fan off\r
91 \r
92 G28 X0 Y0  ;move X/Y to min endstops\r
93 G28 Z0     ;move Z to min endstops\r
94 G92 X0 Y0 Z0 E0         ;reset software position to front/left/z=0.0\r
95 \r
96 G1 Z15.0 F{max_z_speed} ;move the platform down 15mm\r
97 \r
98 G92 E0                  ;zero the extruded length\r
99 G1 F200 E3              ;extrude 3mm of feed stock\r
100 G92 E0                  ;zero the extruded length again\r
101 \r
102 ;go to the middle of the platform (disabled, as there is no need to go to the center)\r
103 ;G1 X{machine_center_x} Y{machine_center_y} F{travel_speed}\r
104 G1 F{travel_speed}\r
105 """,\r
106 #######################################################################################\r
107         'end.gcode': """;End GCode\r
108 M104 S0                     ;extruder heater off\r
109 M140 S0                     ;heated bed heater off (if you have it)\r
110 \r
111 G91                                    ;relative positioning\r
112 G1 E-1 F300                            ;retract the filament a bit before lifting the nozzle, to release some of the pressure\r
113 G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more\r
114 G28 X0 Y0                              ;move X/Y to min endstops, so the head is out of the way\r
115 \r
116 M84                         ;steppers off\r
117 G90                         ;absolute positioning\r
118 """,\r
119 #######################################################################################\r
120         'support_start.gcode': '',\r
121         'support_end.gcode': '',\r
122         'cool_start.gcode': '',\r
123         'cool_end.gcode': '',\r
124         'replace.csv': '',\r
125 #######################################################################################\r
126         '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
127 G92 E0\r
128 \r
129 G91                                    ;relative positioning\r
130 G1 E-1 F300                            ;retract the filament a bit before lifting the nozzle, to release some of the pressure\r
131 G1 Z+0.5 E-5 F{travel_speed}           ;move Z up a bit and retract filament even more\r
132 G90                                    ;absolute positioning\r
133 \r
134 G1 Z{clear_z} F{max_z_speed}\r
135 G92 E0\r
136 G1 X{machine_center_x} Y{machine_center_y} F{travel_speed}\r
137 G1 F200 E5\r
138 G92 E0\r
139 """,\r
140 #######################################################################################\r
141         'switchExtruder.gcode': """;Switch between the current extruder and the next extruder, when printing with multiple extruders.\r
142 G1 E-5 F5000\r
143 G92 E0\r
144 T{extruder}\r
145 G1 E5 F5000\r
146 G92 E0\r
147 """,\r
148 }\r
149 preferencesDefaultSettings = {\r
150         'startMode': 'Simple',\r
151         'lastFile': os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'example', 'UltimakerRobot_support.stl')),\r
152         'machine_width': '205',\r
153         'machine_depth': '205',\r
154         'machine_height': '200',\r
155         'machine_type': 'unknown',\r
156         'has_heated_bed': 'False',\r
157         'extruder_amount': '1',\r
158         'extruder_offset_x1': '-22.0',\r
159         'extruder_offset_y1': '0.0',\r
160         'extruder_offset_x2': '0.0',\r
161         'extruder_offset_y2': '0.0',\r
162         'extruder_offset_x3': '0.0',\r
163         'extruder_offset_y3': '0.0',\r
164         'filament_density': '1300',\r
165         'steps_per_e': '0',\r
166         'serial_port': 'AUTO',\r
167         'serial_port_auto': '',\r
168         'serial_baud': 'AUTO',\r
169         'serial_baud_auto': '',\r
170         'slicer': 'Cura (Skeinforge based)',\r
171         'save_profile': 'False',\r
172         'filament_cost_kg': '0',\r
173         'filament_cost_meter': '0',\r
174         'sdpath': '',\r
175         'sdshortnames': 'True',\r
176         \r
177         'extruder_head_size_min_x': '70.0',\r
178         'extruder_head_size_min_y': '18.0',\r
179         'extruder_head_size_max_x': '18.0',\r
180         'extruder_head_size_max_y': '35.0',\r
181         'extruder_head_size_height': '80.0',\r
182         \r
183         'model_colour': '#FFCC99',\r
184         'model_colour2': '#33FF1A',\r
185         'model_colour3': '#FF331A',\r
186         'model_colour4': '#1A33FF',\r
187 }\r
188 \r
189 #########################################################\r
190 ## Profile and preferences functions\r
191 #########################################################\r
192 \r
193 ## Profile functions\r
194 def getDefaultProfilePath():\r
195         basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))\r
196         #If we have a frozen python install, we need to step out of the library.zip\r
197         if hasattr(sys, 'frozen'):\r
198                 basePath = os.path.normpath(os.path.join(basePath, ".."))\r
199         return os.path.normpath(os.path.join(basePath, "current_profile.ini"))\r
200 \r
201 def loadGlobalProfile(filename):\r
202         #Read a configuration file as global config\r
203         global globalProfileParser\r
204         globalProfileParser = ConfigParser.ConfigParser()\r
205         globalProfileParser.read(filename)\r
206 \r
207 def resetGlobalProfile():\r
208         #Read a configuration file as global config\r
209         global globalProfileParser\r
210         globalProfileParser = ConfigParser.ConfigParser()\r
211 \r
212 def saveGlobalProfile(filename):\r
213         #Save the current profile to an ini file\r
214         globalProfileParser.write(open(filename, 'w'))\r
215 \r
216 def loadGlobalProfileFromString(options):\r
217         global globalProfileParser\r
218         globalProfileParser = ConfigParser.ConfigParser()\r
219         globalProfileParser.add_section('profile')\r
220         globalProfileParser.add_section('alterations')\r
221         options = base64.b64decode(options)\r
222         options = zlib.decompress(options)\r
223         (profileOpts, alt) = options.split('\f', 1)\r
224         for option in profileOpts.split('\b'):\r
225                 if len(option) > 0:\r
226                         (key, value) = option.split('=', 1)\r
227                         globalProfileParser.set('profile', key, value)\r
228         for option in alt.split('\b'):\r
229                 if len(option) > 0:\r
230                         (key, value) = option.split('=', 1)\r
231                         globalProfileParser.set('alterations', key, value)\r
232 \r
233 def getGlobalProfileString():\r
234         global globalProfileParser\r
235         if not globals().has_key('globalProfileParser'):\r
236                 loadGlobalProfile(getDefaultProfilePath())\r
237         \r
238         p = []\r
239         alt = []\r
240         tempDone = []\r
241         if globalProfileParser.has_section('profile'):\r
242                 for key in globalProfileParser.options('profile'):\r
243                         if key in tempOverride:\r
244                                 p.append(key + "=" + tempOverride[key])\r
245                                 tempDone.append(key)\r
246                         else:\r
247                                 p.append(key + "=" + globalProfileParser.get('profile', key))\r
248         if globalProfileParser.has_section('alterations'):\r
249                 for key in globalProfileParser.options('alterations'):\r
250                         if key in tempOverride:\r
251                                 p.append(key + "=" + tempOverride[key])\r
252                                 tempDone.append(key)\r
253                         else:\r
254                                 alt.append(key + "=" + globalProfileParser.get('alterations', key))\r
255         for key in tempOverride:\r
256                 if key not in tempDone:\r
257                         p.append(key + "=" + tempOverride[key])\r
258         ret = '\b'.join(p) + '\f' + '\b'.join(alt)\r
259         ret = base64.b64encode(zlib.compress(ret, 9))\r
260         return ret\r
261 \r
262 def getProfileSetting(name):\r
263         if name in tempOverride:\r
264                 return unicode(tempOverride[name], "utf-8")\r
265         #Check if we have a configuration file loaded, else load the default.\r
266         if not globals().has_key('globalProfileParser'):\r
267                 loadGlobalProfile(getDefaultProfilePath())\r
268         if not globalProfileParser.has_option('profile', name):\r
269                 if name in profileDefaultSettings:\r
270                         default = profileDefaultSettings[name]\r
271                 else:\r
272                         print("Missing default setting for: '" + name + "'")\r
273                         profileDefaultSettings[name] = ''\r
274                         default = ''\r
275                 if not globalProfileParser.has_section('profile'):\r
276                         globalProfileParser.add_section('profile')\r
277                 globalProfileParser.set('profile', name, str(default))\r
278                 #print(name + " not found in profile, so using default: " + str(default))\r
279                 return default\r
280         return globalProfileParser.get('profile', name)\r
281 \r
282 def getProfileSettingFloat(name):\r
283         try:\r
284                 setting = getProfileSetting(name).replace(',', '.')\r
285                 return float(eval(setting, {}, {}))\r
286         except (ValueError, SyntaxError, TypeError):\r
287                 return 0.0\r
288 \r
289 def putProfileSetting(name, value):\r
290         #Check if we have a configuration file loaded, else load the default.\r
291         if not globals().has_key('globalProfileParser'):\r
292                 loadGlobalProfile(getDefaultProfilePath())\r
293         if not globalProfileParser.has_section('profile'):\r
294                 globalProfileParser.add_section('profile')\r
295         globalProfileParser.set('profile', name, str(value))\r
296 \r
297 def isProfileSetting(name):\r
298         if name in profileDefaultSettings:\r
299                 return True\r
300         return False\r
301 \r
302 ## Preferences functions\r
303 global globalPreferenceParser\r
304 globalPreferenceParser = None\r
305 \r
306 def getPreferencePath():\r
307         basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))\r
308         #If we have a frozen python install, we need to step out of the library.zip\r
309         if hasattr(sys, 'frozen'):\r
310                 basePath = os.path.normpath(os.path.join(basePath, ".."))\r
311         return os.path.normpath(os.path.join(basePath, "preferences.ini"))\r
312 \r
313 def getPreferenceFloat(name):\r
314         try:\r
315                 setting = getPreference(name).replace(',', '.')\r
316                 return float(eval(setting, {}, {}))\r
317         except (ValueError, SyntaxError, TypeError):\r
318                 return 0.0\r
319 \r
320 def getPreferenceColour(name):\r
321         colorString = getPreference(name)\r
322         return [float(int(colorString[1:3], 16)) / 255, float(int(colorString[3:5], 16)) / 255, float(int(colorString[5:7], 16)) / 255, 1.0]\r
323 \r
324 def getPreference(name):\r
325         if name in tempOverride:\r
326                 return unicode(tempOverride[name])\r
327         global globalPreferenceParser\r
328         if globalPreferenceParser == None:\r
329                 globalPreferenceParser = ConfigParser.ConfigParser()\r
330                 globalPreferenceParser.read(getPreferencePath())\r
331         if not globalPreferenceParser.has_option('preference', name):\r
332                 if name in preferencesDefaultSettings:\r
333                         default = preferencesDefaultSettings[name]\r
334                 else:\r
335                         print("Missing default setting for: '" + name + "'")\r
336                         preferencesDefaultSettings[name] = ''\r
337                         default = ''\r
338                 if not globalPreferenceParser.has_section('preference'):\r
339                         globalPreferenceParser.add_section('preference')\r
340                 globalPreferenceParser.set('preference', name, str(default))\r
341                 #print(name + " not found in preferences, so using default: " + str(default))\r
342                 return default\r
343         return unicode(globalPreferenceParser.get('preference', name), "utf-8")\r
344 \r
345 def putPreference(name, value):\r
346         #Check if we have a configuration file loaded, else load the default.\r
347         global globalPreferenceParser\r
348         if globalPreferenceParser == None:\r
349                 globalPreferenceParser = ConfigParser.ConfigParser()\r
350                 globalPreferenceParser.read(getPreferencePath())\r
351         if not globalPreferenceParser.has_section('preference'):\r
352                 globalPreferenceParser.add_section('preference')\r
353         globalPreferenceParser.set('preference', name, unicode(value).encode("utf-8"))\r
354         globalPreferenceParser.write(open(getPreferencePath(), 'w'))\r
355 \r
356 def isPreference(name):\r
357         if name in preferencesDefaultSettings:\r
358                 return True\r
359         return False\r
360 \r
361 ## Temp overrides for multi-extruder slicing and the project planner.\r
362 tempOverride = {}\r
363 def setTempOverride(name, value):\r
364         tempOverride[name] = unicode(value).encode("utf-8")\r
365 def clearTempOverride(name):\r
366         del tempOverride[name]\r
367 def resetTempOverride():\r
368         tempOverride.clear()\r
369 \r
370 #########################################################\r
371 ## Utility functions to calculate common profile values\r
372 #########################################################\r
373 def calculateEdgeWidth():\r
374         wallThickness = getProfileSettingFloat('wall_thickness')\r
375         nozzleSize = getProfileSettingFloat('nozzle_size')\r
376         \r
377         if wallThickness < nozzleSize:\r
378                 return wallThickness\r
379 \r
380         lineCount = int(wallThickness / nozzleSize)\r
381         lineWidth = wallThickness / lineCount\r
382         lineWidthAlt = wallThickness / (lineCount + 1)\r
383         if lineWidth > nozzleSize * 1.5:\r
384                 return lineWidthAlt\r
385         return lineWidth\r
386 \r
387 def calculateLineCount():\r
388         wallThickness = getProfileSettingFloat('wall_thickness')\r
389         nozzleSize = getProfileSettingFloat('nozzle_size')\r
390         \r
391         if wallThickness < nozzleSize:\r
392                 return 1\r
393 \r
394         lineCount = int(wallThickness / nozzleSize + 0.0001)\r
395         lineWidth = wallThickness / lineCount\r
396         lineWidthAlt = wallThickness / (lineCount + 1)\r
397         if lineWidth > nozzleSize * 1.5:\r
398                 return lineCount + 1\r
399         return lineCount\r
400 \r
401 def calculateSolidLayerCount():\r
402         layerHeight = getProfileSettingFloat('layer_height')\r
403         solidThickness = getProfileSettingFloat('solid_layer_thickness')\r
404         return int(math.ceil(solidThickness / layerHeight - 0.0001))\r
405 \r
406 #########################################################\r
407 ## Alteration file functions\r
408 #########################################################\r
409 def replaceTagMatch(m):\r
410         pre = m.group(1)\r
411         tag = m.group(2)\r
412         if tag == 'time':\r
413                 return pre + time.strftime('%H:%M:%S')\r
414         if tag == 'date':\r
415                 return pre + time.strftime('%d %b %Y')\r
416         if tag == 'day':\r
417                 return pre + time.strftime('%a')\r
418         if tag == 'print_time':\r
419                 return pre + '#P_TIME#'\r
420         if tag == 'filament_amount':\r
421                 return pre + '#F_AMNT#'\r
422         if tag == 'filament_weight':\r
423                 return pre + '#F_WGHT#'\r
424         if tag == 'filament_cost':\r
425                 return pre + '#F_COST#'\r
426         if pre == 'F' and tag in ['print_speed', 'retraction_speed', 'travel_speed', 'max_z_speed', 'bottom_layer_speed', 'cool_min_feedrate']:\r
427                 f = getProfileSettingFloat(tag) * 60\r
428         elif isProfileSetting(tag):\r
429                 f = getProfileSettingFloat(tag)\r
430         elif isPreference(tag):\r
431                 f = getProfileSettingFloat(tag)\r
432         else:\r
433                 return '%s?%s?' % (pre, tag)\r
434         if (f % 1) == 0:\r
435                 return pre + str(int(f))\r
436         return pre + str(f)\r
437 \r
438 def replaceGCodeTags(filename, gcodeInt):\r
439         f = open(filename, 'r+')\r
440         data = f.read(2048)\r
441         data = data.replace('#P_TIME#', ('%5d:%02d' % (int(gcodeInt.totalMoveTimeMinute / 60), int(gcodeInt.totalMoveTimeMinute % 60)))[-8:])\r
442         data = data.replace('#F_AMNT#', ('%8.2f' % (gcodeInt.extrusionAmount / 1000))[-8:])\r
443         data = data.replace('#F_WGHT#', ('%8.2f' % (gcodeInt.calculateWeight() * 1000))[-8:])\r
444         cost = gcodeInt.calculateCost()\r
445         if cost == False:\r
446                 cost = 'Unknown'\r
447         data = data.replace('#F_COST#', ('%8s' % (cost.split(' ')[0]))[-8:])\r
448         f.seek(0)\r
449         f.write(data)\r
450         f.close()\r
451 \r
452 ### Get aleration raw contents. (Used internally in Cura)\r
453 def getAlterationFile(filename):\r
454         #Check if we have a configuration file loaded, else load the default.\r
455         if not globals().has_key('globalProfileParser'):\r
456                 loadGlobalProfile(getDefaultProfilePath())\r
457         \r
458         if not globalProfileParser.has_option('alterations', filename):\r
459                 if filename in alterationDefault:\r
460                         default = alterationDefault[filename]\r
461                 else:\r
462                         print("Missing default alteration for: '" + filename + "'")\r
463                         alterationDefault[filename] = ''\r
464                         default = ''\r
465                 if not globalProfileParser.has_section('alterations'):\r
466                         globalProfileParser.add_section('alterations')\r
467                 #print("Using default for: %s" % (filename))\r
468                 globalProfileParser.set('alterations', filename, default)\r
469         return unicode(globalProfileParser.get('alterations', filename), "utf-8")\r
470 \r
471 def setAlterationFile(filename, value):\r
472         #Check if we have a configuration file loaded, else load the default.\r
473         if not globals().has_key('globalProfileParser'):\r
474                 loadGlobalProfile(getDefaultProfilePath())\r
475         if not globalProfileParser.has_section('alterations'):\r
476                 globalProfileParser.add_section('alterations')\r
477         globalProfileParser.set('alterations', filename, value.encode("utf-8"))\r
478         saveGlobalProfile(getDefaultProfilePath())\r
479 \r
480 ### Get the alteration file for output. (Used by Skeinforge)\r
481 def getAlterationFileContents(filename):\r
482         prefix = ''\r
483         postfix = ''\r
484         alterationContents = getAlterationFile(filename)\r
485         if filename == 'start.gcode':\r
486                 #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
487                 #We also set our steps per E here, if configured.\r
488                 eSteps = getPreferenceFloat('steps_per_e')\r
489                 if eSteps > 0:\r
490                         prefix += 'M92 E%f\n' % (eSteps)\r
491                 temp = getProfileSettingFloat('print_temperature')\r
492                 bedTemp = 0\r
493                 if getPreference('has_heated_bed') == 'True':\r
494                         bedTemp = getProfileSettingFloat('print_bed_temperature')\r
495                 \r
496                 if bedTemp > 0 and not '{print_bed_temperature}' in alterationContents:\r
497                         prefix += 'M140 S%f\n' % (bedTemp)\r
498                 if temp > 0 and not '{print_temperature}' in alterationContents:\r
499                         prefix += 'M109 S%f\n' % (temp)\r
500                 if bedTemp > 0 and not '{print_bed_temperature}' in alterationContents:\r
501                         prefix += 'M190 S%f\n' % (bedTemp)\r
502         elif filename == 'end.gcode':\r
503                 #Append the profile string to the end of the GCode, so we can load it from the GCode file later.\r
504                 postfix = ';CURA_PROFILE_STRING:%s\n' % (getGlobalProfileString())\r
505         elif filename == 'replace.csv':\r
506                 #Always remove the extruder on/off M codes. These are no longer needed in 5D printing.\r
507                 prefix = 'M101\nM103\n'\r
508         elif filename == 'support_start.gcode' or filename == 'support_end.gcode':\r
509                 #Add support start/end code \r
510                 if getProfileSetting('support_dual_extrusion') == 'True' and int(getPreference('extruder_amount')) > 1:\r
511                         if filename == 'support_start.gcode':\r
512                                 setTempOverride('extruder', '1')\r
513                         else:\r
514                                 setTempOverride('extruder', '0')\r
515                         alterationContents = getAlterationFileContents('switchExtruder.gcode')\r
516                         clearTempOverride('extruder')\r
517                 else:\r
518                         alterationContents = ''\r
519         return unicode(prefix + re.sub("(.)\{([^\}]*)\}", replaceTagMatch, alterationContents).rstrip() + '\n' + postfix).encode('utf-8')\r
520 \r