1 from __future__ import absolute_import
2 from __future__ import division
4 import os, traceback, math, re, zlib, base64, time, sys, platform, glob, string, stat
5 import cPickle as pickle
6 if sys.version_info[0] < 3:
9 import configparser as ConfigParser
11 from Cura.util import version
13 #########################################################
14 ## Default settings when none are found.
15 #########################################################
17 #Single place to store the defaults, so we have a consistent set of default settings.
18 profileDefaultSettings = {
20 'layer_height': '0.2',
21 'wall_thickness': '0.8',
22 'solid_layer_thickness': '0.6',
24 'skirt_line_count': '1',
27 'print_temperature': '220',
28 'print_bed_temperature': '70',
30 'filament_diameter': '2.89',
31 'filament_density': '1.00',
32 'retraction_min_travel': '5.0',
33 'retraction_enable': 'False',
34 'retraction_speed': '40.0',
35 'retraction_amount': '4.5',
36 'retraction_extra': '0.0',
37 'retract_on_jumps_only': 'True',
38 'travel_speed': '150',
40 'bottom_layer_speed': '20',
41 'cool_min_layer_time': '5',
42 'fan_enabled': 'True',
45 'fan_speed_max': '100',
52 'model_rotate_base': '0',
53 'model_multiply_x': '1',
54 'model_multiply_y': '1',
55 'extra_base_wall_thickness': '0.0',
56 'sequence': 'Loops > Perimeter > Infill',
57 'force_first_layer_sequence': 'True',
58 'infill_type': 'Line',
62 'support_distance': '0.5',
63 'support_dual_extrusion': 'False',
65 'enable_skin': 'False',
66 'enable_raft': 'False',
67 'cool_min_feedrate': '10',
68 'bridge_speed': '100',
70 'raft_base_material_amount': '100',
71 'raft_interface_material_amount': '100',
72 'bottom_thickness': '0.3',
73 'hop_on_move': 'False',
75 'object_center_x': '-1',
76 'object_center_y': '-1',
78 'add_start_end_gcode': 'True',
79 'gcode_extension': 'gcode',
80 'alternative_center': '',
85 #######################################################################################
86 'start.gcode': """;Sliced {filename} at: {day} {date} {time}
87 ;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
88 ;Print time: {print_time}
89 ;Filament used: {filament_amount}m {filament_weight}g
90 ;Filament cost: {filament_cost}
92 G90 ;absolute positioning
93 M107 ;start with the fan off
95 G28 X0 Y0 ;move X/Y to min endstops
96 G28 Z0 ;move Z to min endstops
97 G92 X0 Y0 Z0 E0 ;reset software position to front/left/z=0.0
99 G1 Z15.0 F{max_z_speed} ;move the platform down 15mm
101 G92 E0 ;zero the extruded length
102 G1 F200 E3 ;extrude 3mm of feed stock
103 G92 E0 ;zero the extruded length again
106 #######################################################################################
107 'end.gcode': """;End GCode
108 M104 S0 ;extruder heater off
109 M140 S0 ;heated bed heater off (if you have it)
111 G91 ;relative positioning
112 G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
113 G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
114 G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
117 G90 ;absolute positioning
119 #######################################################################################
120 'support_start.gcode': '',
121 'support_end.gcode': '',
122 'cool_start.gcode': '',
123 'cool_end.gcode': '',
125 #######################################################################################
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.
129 G91 ;relative positioning
130 G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
131 G1 Z+0.5 E-5 F{travel_speed} ;move Z up a bit and retract filament even more
132 G90 ;absolute positioning
134 G1 Z{clear_z} F{max_z_speed}
136 G1 X{object_center_x} Y{object_center_x} F{travel_speed}
140 #######################################################################################
141 'switchExtruder.gcode': """;Switch between the current extruder and the next extruder, when printing with multiple extruders.
150 preferencesDefaultSettings = {
151 'startMode': 'Simple',
152 'lastFile': os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'example', 'UltimakerRobot_support.stl')),
153 'machine_width': '205',
154 'machine_depth': '205',
155 'machine_height': '200',
156 'machine_type': 'unknown',
157 'ultimaker_extruder_upgrade': 'False',
158 'has_heated_bed': 'False',
159 'extruder_amount': '1',
160 'extruder_offset_x1': '-22.0',
161 'extruder_offset_y1': '0.0',
162 'extruder_offset_x2': '0.0',
163 'extruder_offset_y2': '0.0',
164 'extruder_offset_x3': '0.0',
165 'extruder_offset_y3': '0.0',
166 'filament_density': '1300',
168 'serial_port': 'AUTO',
169 'serial_port_auto': '',
170 'serial_baud': 'AUTO',
171 'serial_baud_auto': '',
172 'slicer': 'Cura (Skeinforge based)',
173 'save_profile': 'False',
174 'filament_cost_kg': '0',
175 'filament_cost_meter': '0',
177 'sdshortnames': 'True',
179 'extruder_head_size_min_x': '70.0',
180 'extruder_head_size_min_y': '18.0',
181 'extruder_head_size_max_x': '18.0',
182 'extruder_head_size_max_y': '35.0',
183 'extruder_head_size_height': '80.0',
185 'model_colour': '#72CB30',
186 'model_colour2': '#CB3030',
187 'model_colour3': '#DDD93C',
188 'model_colour4': '#4550D3',
191 #########################################################
192 ## Profile and preferences functions
193 #########################################################
196 def getDefaultProfilePath():
197 if platform.system() == "Windows":
198 basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
199 #If we have a frozen python install, we need to step out of the library.zip
200 if hasattr(sys, 'frozen'):
201 basePath = os.path.normpath(os.path.join(basePath, ".."))
203 basePath = os.path.expanduser('~/.cura/%s' % version.getVersion(False))
204 if not os.path.isdir(basePath):
205 os.makedirs(basePath)
206 return os.path.join(basePath, 'current_profile.ini')
208 def loadGlobalProfile(filename):
209 #Read a configuration file as global config
210 global globalProfileParser
211 globalProfileParser = ConfigParser.ConfigParser()
212 globalProfileParser.read(filename)
214 def resetGlobalProfile():
215 #Read a configuration file as global config
216 global globalProfileParser
217 globalProfileParser = ConfigParser.ConfigParser()
219 if getPreference('machine_type') == 'ultimaker':
220 putProfileSetting('nozzle_size', '0.4')
221 if getPreference('ultimaker_extruder_upgrade') == 'True':
222 putProfileSetting('retraction_enable', 'True')
224 putProfileSetting('nozzle_size', '0.5')
226 def saveGlobalProfile(filename):
227 #Save the current profile to an ini file
228 globalProfileParser.write(open(filename, 'w'))
230 def loadGlobalProfileFromString(options):
231 global globalProfileParser
232 globalProfileParser = ConfigParser.ConfigParser()
233 globalProfileParser.add_section('profile')
234 globalProfileParser.add_section('alterations')
235 options = base64.b64decode(options)
236 options = zlib.decompress(options)
237 (profileOpts, alt) = options.split('\f', 1)
238 for option in profileOpts.split('\b'):
240 (key, value) = option.split('=', 1)
241 globalProfileParser.set('profile', key, value)
242 for option in alt.split('\b'):
244 (key, value) = option.split('=', 1)
245 globalProfileParser.set('alterations', key, value)
247 def getGlobalProfileString():
248 global globalProfileParser
249 if not globals().has_key('globalProfileParser'):
250 loadGlobalProfile(getDefaultProfilePath())
255 if globalProfileParser.has_section('profile'):
256 for key in globalProfileParser.options('profile'):
257 if key in tempOverride:
258 p.append(key + "=" + tempOverride[key])
261 p.append(key + "=" + globalProfileParser.get('profile', key))
262 if globalProfileParser.has_section('alterations'):
263 for key in globalProfileParser.options('alterations'):
264 if key in tempOverride:
265 p.append(key + "=" + tempOverride[key])
268 alt.append(key + "=" + globalProfileParser.get('alterations', key))
269 for key in tempOverride:
270 if key not in tempDone:
271 p.append(key + "=" + tempOverride[key])
272 ret = '\b'.join(p) + '\f' + '\b'.join(alt)
273 ret = base64.b64encode(zlib.compress(ret, 9))
276 def getProfileSetting(name):
277 if name in tempOverride:
278 return unicode(tempOverride[name], "utf-8")
279 #Check if we have a configuration file loaded, else load the default.
280 if not globals().has_key('globalProfileParser'):
281 loadGlobalProfile(getDefaultProfilePath())
282 if not globalProfileParser.has_option('profile', name):
283 if name in profileDefaultSettings:
284 default = profileDefaultSettings[name]
286 print("Missing default setting for: '" + name + "'")
287 profileDefaultSettings[name] = ''
289 if not globalProfileParser.has_section('profile'):
290 globalProfileParser.add_section('profile')
291 globalProfileParser.set('profile', name, str(default))
292 #print(name + " not found in profile, so using default: " + str(default))
294 return globalProfileParser.get('profile', name)
296 def getProfileSettingFloat(name):
298 setting = getProfileSetting(name).replace(',', '.')
299 return float(eval(setting, {}, {}))
300 except (ValueError, SyntaxError, TypeError):
303 def putProfileSetting(name, value):
304 #Check if we have a configuration file loaded, else load the default.
305 if not globals().has_key('globalProfileParser'):
306 loadGlobalProfile(getDefaultProfilePath())
307 if not globalProfileParser.has_section('profile'):
308 globalProfileParser.add_section('profile')
309 globalProfileParser.set('profile', name, str(value))
311 def isProfileSetting(name):
312 if name in profileDefaultSettings:
316 ## Preferences functions
317 global globalPreferenceParser
318 globalPreferenceParser = None
320 def getPreferencePath():
321 if platform.system() == "Windows":
322 basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
323 #If we have a frozen python install, we need to step out of the library.zip
324 if hasattr(sys, 'frozen'):
325 basePath = os.path.normpath(os.path.join(basePath, ".."))
327 basePath = os.path.expanduser('~/.cura/%s' % version.getVersion(False))
328 if not os.path.isdir(basePath):
329 os.makedirs(basePath)
330 return os.path.join(basePath, 'preferences.ini')
332 def getPreferenceFloat(name):
334 setting = getPreference(name).replace(',', '.')
335 return float(eval(setting, {}, {}))
336 except (ValueError, SyntaxError, TypeError):
339 def getPreferenceColour(name):
340 colorString = getPreference(name)
341 return [float(int(colorString[1:3], 16)) / 255, float(int(colorString[3:5], 16)) / 255, float(int(colorString[5:7], 16)) / 255, 1.0]
343 def getPreference(name):
344 if name in tempOverride:
345 return unicode(tempOverride[name])
346 global globalPreferenceParser
347 if globalPreferenceParser == None:
348 globalPreferenceParser = ConfigParser.ConfigParser()
349 globalPreferenceParser.read(getPreferencePath())
350 if not globalPreferenceParser.has_option('preference', name):
351 if name in preferencesDefaultSettings:
352 default = preferencesDefaultSettings[name]
354 print("Missing default setting for: '" + name + "'")
355 preferencesDefaultSettings[name] = ''
357 if not globalPreferenceParser.has_section('preference'):
358 globalPreferenceParser.add_section('preference')
359 globalPreferenceParser.set('preference', name, str(default))
360 #print(name + " not found in preferences, so using default: " + str(default))
362 return unicode(globalPreferenceParser.get('preference', name), "utf-8")
364 def putPreference(name, value):
365 #Check if we have a configuration file loaded, else load the default.
366 global globalPreferenceParser
367 if globalPreferenceParser == None:
368 globalPreferenceParser = ConfigParser.ConfigParser()
369 globalPreferenceParser.read(getPreferencePath())
370 if not globalPreferenceParser.has_section('preference'):
371 globalPreferenceParser.add_section('preference')
372 globalPreferenceParser.set('preference', name, unicode(value).encode("utf-8"))
373 globalPreferenceParser.write(open(getPreferencePath(), 'w'))
375 def isPreference(name):
376 if name in preferencesDefaultSettings:
380 ## Temp overrides for multi-extruder slicing and the project planner.
382 def setTempOverride(name, value):
383 tempOverride[name] = unicode(value).encode("utf-8")
384 def clearTempOverride(name):
385 del tempOverride[name]
386 def resetTempOverride():
389 #########################################################
390 ## Utility functions to calculate common profile values
391 #########################################################
392 def calculateEdgeWidth():
393 wallThickness = getProfileSettingFloat('wall_thickness')
394 nozzleSize = getProfileSettingFloat('nozzle_size')
396 if wallThickness < nozzleSize:
399 lineCount = int(wallThickness / nozzleSize)
400 lineWidth = wallThickness / lineCount
401 lineWidthAlt = wallThickness / (lineCount + 1)
402 if lineWidth > nozzleSize * 1.5:
406 def calculateLineCount():
407 wallThickness = getProfileSettingFloat('wall_thickness')
408 nozzleSize = getProfileSettingFloat('nozzle_size')
410 if wallThickness < nozzleSize:
413 lineCount = int(wallThickness / nozzleSize + 0.0001)
414 lineWidth = wallThickness / lineCount
415 lineWidthAlt = wallThickness / (lineCount + 1)
416 if lineWidth > nozzleSize * 1.5:
420 def calculateSolidLayerCount():
421 layerHeight = getProfileSettingFloat('layer_height')
422 solidThickness = getProfileSettingFloat('solid_layer_thickness')
423 return int(math.ceil(solidThickness / layerHeight - 0.0001))
425 #########################################################
426 ## Alteration file functions
427 #########################################################
428 def replaceTagMatch(m):
432 return pre + time.strftime('%H:%M:%S')
434 return pre + time.strftime('%d %b %Y')
436 return pre + time.strftime('%a')
437 if tag == 'print_time':
438 return pre + '#P_TIME#'
439 if tag == 'filament_amount':
440 return pre + '#F_AMNT#'
441 if tag == 'filament_weight':
442 return pre + '#F_WGHT#'
443 if tag == 'filament_cost':
444 return pre + '#F_COST#'
445 if pre == 'F' and tag in ['print_speed', 'retraction_speed', 'travel_speed', 'max_z_speed', 'bottom_layer_speed', 'cool_min_feedrate']:
446 f = getProfileSettingFloat(tag) * 60
447 elif isProfileSetting(tag):
448 f = getProfileSettingFloat(tag)
449 elif isPreference(tag):
450 f = getProfileSettingFloat(tag)
452 return '%s?%s?' % (pre, tag)
454 return pre + str(int(f))
457 def replaceGCodeTags(filename, gcodeInt):
458 f = open(filename, 'r+')
460 data = data.replace('#P_TIME#', ('%5d:%02d' % (int(gcodeInt.totalMoveTimeMinute / 60), int(gcodeInt.totalMoveTimeMinute % 60)))[-8:])
461 data = data.replace('#F_AMNT#', ('%8.2f' % (gcodeInt.extrusionAmount / 1000))[-8:])
462 data = data.replace('#F_WGHT#', ('%8.2f' % (gcodeInt.calculateWeight() * 1000))[-8:])
463 cost = gcodeInt.calculateCost()
466 data = data.replace('#F_COST#', ('%8s' % (cost.split(' ')[0]))[-8:])
471 ### Get aleration raw contents. (Used internally in Cura)
472 def getAlterationFile(filename):
473 #Check if we have a configuration file loaded, else load the default.
474 if not globals().has_key('globalProfileParser'):
475 loadGlobalProfile(getDefaultProfilePath())
477 if not globalProfileParser.has_option('alterations', filename):
478 if filename in alterationDefault:
479 default = alterationDefault[filename]
481 print("Missing default alteration for: '" + filename + "'")
482 alterationDefault[filename] = ''
484 if not globalProfileParser.has_section('alterations'):
485 globalProfileParser.add_section('alterations')
486 #print("Using default for: %s" % (filename))
487 globalProfileParser.set('alterations', filename, default)
488 return unicode(globalProfileParser.get('alterations', filename), "utf-8")
490 def setAlterationFile(filename, value):
491 #Check if we have a configuration file loaded, else load the default.
492 if not globals().has_key('globalProfileParser'):
493 loadGlobalProfile(getDefaultProfilePath())
494 if not globalProfileParser.has_section('alterations'):
495 globalProfileParser.add_section('alterations')
496 globalProfileParser.set('alterations', filename, value.encode("utf-8"))
497 saveGlobalProfile(getDefaultProfilePath())
499 ### Get the alteration file for output. (Used by Skeinforge)
500 def getAlterationFileContents(filename):
503 alterationContents = getAlterationFile(filename)
504 if filename == 'start.gcode':
505 #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.
506 #We also set our steps per E here, if configured.
507 eSteps = getPreferenceFloat('steps_per_e')
509 prefix += 'M92 E%f\n' % (eSteps)
510 temp = getProfileSettingFloat('print_temperature')
512 if getPreference('has_heated_bed') == 'True':
513 bedTemp = getProfileSettingFloat('print_bed_temperature')
515 if bedTemp > 0 and not '{print_bed_temperature}' in alterationContents:
516 prefix += 'M140 S%f\n' % (bedTemp)
517 if temp > 0 and not '{print_temperature}' in alterationContents:
518 prefix += 'M109 S%f\n' % (temp)
519 if bedTemp > 0 and not '{print_bed_temperature}' in alterationContents:
520 prefix += 'M190 S%f\n' % (bedTemp)
521 elif filename == 'end.gcode':
522 #Append the profile string to the end of the GCode, so we can load it from the GCode file later.
523 postfix = ';CURA_PROFILE_STRING:%s\n' % (getGlobalProfileString())
524 elif filename == 'replace.csv':
525 #Always remove the extruder on/off M codes. These are no longer needed in 5D printing.
526 prefix = 'M101\nM103\n'
527 elif filename == 'support_start.gcode' or filename == 'support_end.gcode':
528 #Add support start/end code
529 if getProfileSetting('support_dual_extrusion') == 'True' and int(getPreference('extruder_amount')) > 1:
530 if filename == 'support_start.gcode':
531 setTempOverride('extruder', '1')
533 setTempOverride('extruder', '0')
534 alterationContents = getAlterationFileContents('switchExtruder.gcode')
535 clearTempOverride('extruder')
537 alterationContents = ''
538 return unicode(prefix + re.sub("(.)\{([^\}]*)\}", replaceTagMatch, alterationContents).rstrip() + '\n' + postfix).strip().encode('utf-8')
542 def getPluginConfig():
544 return pickle.loads(getProfileSetting('plugin_config'))
548 def setPluginConfig(config):
549 putProfileSetting('plugin_config', pickle.dumps(config))
551 def getPluginBasePaths():
553 if platform.system() != "Windows":
554 ret.append(os.path.expanduser('~/.cura/plugins/'))
555 ret.append(os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'plugins')))
560 for basePath in getPluginBasePaths():
561 for filename in glob.glob(os.path.join(basePath, '*.py')):
562 filename = os.path.basename(filename)
563 if filename.startswith('_'):
565 with open(os.path.join(basePath, filename), "r") as f:
566 item = {'filename': filename, 'name': None, 'info': None, 'type': None, 'params': []}
569 if not line.startswith('#'):
571 line = line[1:].split(':', 1)
574 if line[0].upper() == 'NAME':
575 item['name'] = line[1].strip()
576 elif line[0].upper() == 'INFO':
577 item['info'] = line[1].strip()
578 elif line[0].upper() == 'TYPE':
579 item['type'] = line[1].strip()
580 elif line[0].upper() == 'DEPEND':
582 elif line[0].upper() == 'PARAM':
583 m = re.match('([a-zA-Z]*)\(([a-zA-Z_]*)(?::([^\)]*))?\) +(.*)', line[1].strip())
585 item['params'].append({'name': m.group(1), 'type': m.group(2), 'default': m.group(3), 'description': m.group(4)})
587 print "Unknown item in effect meta data: %s %s" % (line[0], line[1])
588 if item['name'] != None and item['type'] == 'postprocess':
592 def runPostProcessingPlugins(gcodefilename):
593 pluginConfigList = getPluginConfig()
594 pluginList = getPluginList()
596 for pluginConfig in pluginConfigList:
598 for pluginTest in pluginList:
599 if pluginTest['filename'] == pluginConfig['filename']:
605 for basePath in getPluginBasePaths():
606 testFilename = os.path.join(basePath, pluginConfig['filename'])
607 if os.path.isfile(testFilename):
608 pythonFile = testFilename
609 if pythonFile is None:
612 locals = {'filename': gcodefilename}
613 for param in plugin['params']:
614 value = param['default']
615 if param['name'] in pluginConfig['params']:
616 value = pluginConfig['params'][param['name']]
618 if param['type'] == 'float':
622 value = float(param['default'])
624 locals[param['name']] = value
626 execfile(pythonFile, locals)
628 locationInfo = traceback.extract_tb(sys.exc_info()[2])[-1]
629 return "%s: '%s' @ %s:%s:%d" % (str(sys.exc_info()[0].__name__), str(sys.exc_info()[1]), os.path.basename(locationInfo[0]), locationInfo[2], locationInfo[1])
632 def getSDcardDrives():
634 if platform.system() == "Windows":
635 from ctypes import windll
636 bitmask = windll.kernel32.GetLogicalDrives()
637 for letter in string.uppercase:
639 drives.append(letter + ':/')
641 if platform.system() == "Darwin":
643 for volume in glob.glob('/Volumes/*'):
644 if stat.S_ISLNK(os.lstat(volume).st_mode):
646 drives.append(volume)