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