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 resources
12 from Cura.util import version
14 #########################################################
15 ## Default settings when none are found.
16 #########################################################
18 #Single place to store the defaults, so we have a consistent set of default settings.
19 profileDefaultSettings = {
21 'layer_height': '0.2',
22 'wall_thickness': '0.8',
23 'solid_layer_thickness': '0.6',
25 'skirt_line_count': '1',
28 'print_temperature': '220',
29 'print_bed_temperature': '70',
31 'filament_diameter': '2.89',
32 'filament_density': '1.00',
33 'retraction_min_travel': '5.0',
34 'retraction_enable': 'False',
35 'retraction_speed': '40.0',
36 'retraction_amount': '4.5',
37 'retraction_extra': '0.0',
38 'retract_on_jumps_only': 'True',
39 'travel_speed': '150',
41 'bottom_layer_speed': '20',
42 'cool_min_layer_time': '5',
43 'fan_enabled': 'True',
46 'fan_speed_max': '100',
47 'model_matrix': '1,0,0,0,1,0,0,0,1',
48 'extra_base_wall_thickness': '0.0',
49 'sequence': 'Loops > Perimeter > Infill',
50 'force_first_layer_sequence': 'True',
51 'infill_type': 'Line',
55 'support_distance': '0.5',
56 'support_dual_extrusion': 'False',
58 'enable_skin': 'False',
59 'enable_raft': 'False',
60 'cool_min_feedrate': '10',
61 'bridge_speed': '100',
63 'raft_base_material_amount': '100',
64 'raft_interface_material_amount': '100',
65 'bottom_thickness': '0.3',
66 'hop_on_move': 'False',
68 'object_center_x': '-1',
69 'object_center_y': '-1',
72 'gcode_extension': 'gcode',
73 'alternative_center': '',
78 #######################################################################################
79 'start.gcode': """;Sliced {filename} at: {day} {date} {time}
80 ;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
81 ;Print time: {print_time}
82 ;Filament used: {filament_amount}m {filament_weight}g
83 ;Filament cost: {filament_cost}
85 G90 ;absolute positioning
86 M107 ;start with the fan off
88 G28 X0 Y0 ;move X/Y to min endstops
89 G28 Z0 ;move Z to min endstops
90 G92 X0 Y0 Z0 E0 ;reset software position to front/left/z=0.0
92 G1 Z15.0 F{max_z_speed} ;move the platform down 15mm
94 G92 E0 ;zero the extruded length
95 G1 F200 E3 ;extrude 3mm of feed stock
96 G92 E0 ;zero the extruded length again
100 #######################################################################################
101 'end.gcode': """;End GCode
102 M104 S0 ;extruder heater off
103 M140 S0 ;heated bed heater off (if you have it)
105 G91 ;relative positioning
106 G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
107 G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
108 G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
111 G90 ;absolute positioning
113 #######################################################################################
114 'support_start.gcode': '',
115 'support_end.gcode': '',
116 'cool_start.gcode': '',
117 'cool_end.gcode': '',
119 #######################################################################################
120 '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.
123 G91 ;relative positioning
124 G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
125 G1 Z+0.5 E-5 F{travel_speed} ;move Z up a bit and retract filament even more
126 G90 ;absolute positioning
128 G1 Z{clear_z} F{max_z_speed}
130 G1 X{object_center_x} Y{object_center_x} F{travel_speed}
134 #######################################################################################
135 'switchExtruder.gcode': """;Switch between the current extruder and the next extruder, when printing with multiple extruders.
144 preferencesDefaultSettings = {
145 'startMode': 'Simple',
146 'lastFile': os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'resources', 'example', 'UltimakerRobot_support.stl')),
147 'machine_width': '205',
148 'machine_depth': '205',
149 'machine_height': '200',
150 'machine_type': 'unknown',
151 'machine_center_is_zero': 'False',
152 'ultimaker_extruder_upgrade': 'False',
153 'has_heated_bed': 'False',
154 'reprap_name': 'RepRap',
155 'extruder_amount': '1',
156 'extruder_offset_x1': '-22.0',
157 'extruder_offset_y1': '0.0',
158 'extruder_offset_x2': '0.0',
159 'extruder_offset_y2': '0.0',
160 'extruder_offset_x3': '0.0',
161 'extruder_offset_y3': '0.0',
162 'filament_density': '1300',
164 'serial_port': 'AUTO',
165 'serial_port_auto': '',
166 'serial_baud': 'AUTO',
167 'serial_baud_auto': '',
168 'slicer': 'Cura (Skeinforge based)',
169 'save_profile': 'False',
170 'filament_cost_kg': '0',
171 'filament_cost_meter': '0',
173 'sdshortnames': 'False',
174 'check_for_updates': 'True',
175 'submit_slice_information': 'False',
177 'planner_always_autoplace': 'True',
178 'extruder_head_size_min_x': '75.0',
179 'extruder_head_size_min_y': '18.0',
180 'extruder_head_size_max_x': '18.0',
181 'extruder_head_size_max_y': '35.0',
182 'extruder_head_size_height': '60.0',
184 'model_colour': '#7AB645',
185 'model_colour2': '#CB3030',
186 'model_colour3': '#DDD93C',
187 'model_colour4': '#4550D3',
189 'window_maximized': 'False',
190 'window_pos_x': '-1',
191 'window_pos_y': '-1',
192 'window_width': '-1',
193 'window_height': '-1',
194 'window_normal_sash': '320',
197 #########################################################
198 ## Profile and preferences functions
199 #########################################################
203 if platform.system() == "Windows":
204 basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
205 #If we have a frozen python install, we need to step out of the library.zip
206 if hasattr(sys, 'frozen'):
207 basePath = os.path.normpath(os.path.join(basePath, ".."))
209 basePath = os.path.expanduser('~/.cura/%s' % version.getVersion(False))
210 if not os.path.isdir(basePath):
211 os.makedirs(basePath)
214 def getDefaultProfilePath():
215 return os.path.join(getBasePath(), 'current_profile.ini')
217 def loadGlobalProfile(filename):
218 #Read a configuration file as global config
219 global globalProfileParser
220 globalProfileParser = ConfigParser.ConfigParser()
222 globalProfileParser.read(filename)
223 except ConfigParser.ParsingError:
226 def resetGlobalProfile():
227 #Read a configuration file as global config
228 global globalProfileParser
229 globalProfileParser = ConfigParser.ConfigParser()
231 if getPreference('machine_type') == 'ultimaker':
232 putProfileSetting('nozzle_size', '0.4')
233 if getPreference('ultimaker_extruder_upgrade') == 'True':
234 putProfileSetting('retraction_enable', 'True')
236 putProfileSetting('nozzle_size', '0.5')
238 def saveGlobalProfile(filename):
239 #Save the current profile to an ini file
240 globalProfileParser.write(open(filename, 'w'))
242 def loadGlobalProfileFromString(options):
243 global globalProfileParser
244 globalProfileParser = ConfigParser.ConfigParser()
245 globalProfileParser.add_section('profile')
246 globalProfileParser.add_section('alterations')
247 options = base64.b64decode(options)
248 options = zlib.decompress(options)
249 (profileOpts, alt) = options.split('\f', 1)
250 for option in profileOpts.split('\b'):
252 (key, value) = option.split('=', 1)
253 globalProfileParser.set('profile', key, value)
254 for option in alt.split('\b'):
256 (key, value) = option.split('=', 1)
257 globalProfileParser.set('alterations', key, value)
259 def getGlobalProfileString():
260 global globalProfileParser
261 if not globals().has_key('globalProfileParser'):
262 loadGlobalProfile(getDefaultProfilePath())
267 if globalProfileParser.has_section('profile'):
268 for key in globalProfileParser.options('profile'):
269 if key in tempOverride:
270 p.append(key + "=" + tempOverride[key])
273 p.append(key + "=" + globalProfileParser.get('profile', key))
274 if globalProfileParser.has_section('alterations'):
275 for key in globalProfileParser.options('alterations'):
276 if key in tempOverride:
277 p.append(key + "=" + tempOverride[key])
280 alt.append(key + "=" + globalProfileParser.get('alterations', key))
281 for key in tempOverride:
282 if key not in tempDone:
283 p.append(key + "=" + tempOverride[key])
284 ret = '\b'.join(p) + '\f' + '\b'.join(alt)
285 ret = base64.b64encode(zlib.compress(ret, 9))
288 def getProfileSetting(name):
289 if name in tempOverride:
290 return unicode(tempOverride[name], "utf-8")
291 #Check if we have a configuration file loaded, else load the default.
292 if not globals().has_key('globalProfileParser'):
293 loadGlobalProfile(getDefaultProfilePath())
294 if not globalProfileParser.has_option('profile', name):
295 if name in profileDefaultSettings:
296 default = profileDefaultSettings[name]
298 print("Missing default setting for: '" + name + "'")
299 profileDefaultSettings[name] = ''
301 if not globalProfileParser.has_section('profile'):
302 globalProfileParser.add_section('profile')
303 globalProfileParser.set('profile', name, str(default))
304 #print(name + " not found in profile, so using default: " + str(default))
306 return globalProfileParser.get('profile', name)
308 def getProfileSettingFloat(name):
310 setting = getProfileSetting(name).replace(',', '.')
311 return float(eval(setting, {}, {}))
312 except (ValueError, SyntaxError, TypeError):
315 def putProfileSetting(name, value):
316 #Check if we have a configuration file loaded, else load the default.
317 if not globals().has_key('globalProfileParser'):
318 loadGlobalProfile(getDefaultProfilePath())
319 if not globalProfileParser.has_section('profile'):
320 globalProfileParser.add_section('profile')
321 globalProfileParser.set('profile', name, str(value))
323 def isProfileSetting(name):
324 if name in profileDefaultSettings:
328 ## Preferences functions
329 global globalPreferenceParser
330 globalPreferenceParser = None
332 def getPreferencePath():
333 return os.path.join(getBasePath(), 'preferences.ini')
335 def getPreferenceFloat(name):
337 setting = getPreference(name).replace(',', '.')
338 return float(eval(setting, {}, {}))
339 except (ValueError, SyntaxError, TypeError):
342 def getPreferenceColour(name):
343 colorString = getPreference(name)
344 return [float(int(colorString[1:3], 16)) / 255, float(int(colorString[3:5], 16)) / 255, float(int(colorString[5:7], 16)) / 255, 1.0]
346 def getPreference(name):
347 if name in tempOverride:
348 return unicode(tempOverride[name])
349 global globalPreferenceParser
350 if globalPreferenceParser is None:
351 globalPreferenceParser = ConfigParser.ConfigParser()
353 globalPreferenceParser.read(getPreferencePath())
354 except ConfigParser.ParsingError:
356 if not globalPreferenceParser.has_option('preference', name):
357 if name in preferencesDefaultSettings:
358 default = preferencesDefaultSettings[name]
360 print("Missing default setting for: '" + name + "'")
361 preferencesDefaultSettings[name] = ''
363 if not globalPreferenceParser.has_section('preference'):
364 globalPreferenceParser.add_section('preference')
365 globalPreferenceParser.set('preference', name, str(default))
366 #print(name + " not found in preferences, so using default: " + str(default))
368 return unicode(globalPreferenceParser.get('preference', name), "utf-8")
370 def putPreference(name, value):
371 #Check if we have a configuration file loaded, else load the default.
372 global globalPreferenceParser
373 if globalPreferenceParser == None:
374 globalPreferenceParser = ConfigParser.ConfigParser()
376 globalPreferenceParser.read(getPreferencePath())
377 except ConfigParser.ParsingError:
379 if not globalPreferenceParser.has_section('preference'):
380 globalPreferenceParser.add_section('preference')
381 globalPreferenceParser.set('preference', name, unicode(value).encode("utf-8"))
382 globalPreferenceParser.write(open(getPreferencePath(), 'w'))
384 def isPreference(name):
385 if name in preferencesDefaultSettings:
389 ## Temp overrides for multi-extruder slicing and the project planner.
391 def setTempOverride(name, value):
392 tempOverride[name] = unicode(value).encode("utf-8")
393 def clearTempOverride(name):
394 del tempOverride[name]
395 def resetTempOverride():
398 #########################################################
399 ## Utility functions to calculate common profile values
400 #########################################################
401 def calculateEdgeWidth():
402 wallThickness = getProfileSettingFloat('wall_thickness')
403 nozzleSize = getProfileSettingFloat('nozzle_size')
405 if wallThickness < nozzleSize:
408 lineCount = int(wallThickness / nozzleSize + 0.0001)
409 lineWidth = wallThickness / lineCount
410 lineWidthAlt = wallThickness / (lineCount + 1)
411 if lineWidth > nozzleSize * 1.5:
415 def calculateLineCount():
416 wallThickness = getProfileSettingFloat('wall_thickness')
417 nozzleSize = getProfileSettingFloat('nozzle_size')
419 if wallThickness < nozzleSize:
422 lineCount = int(wallThickness / nozzleSize + 0.0001)
423 lineWidth = wallThickness / lineCount
424 lineWidthAlt = wallThickness / (lineCount + 1)
425 if lineWidth > nozzleSize * 1.5:
429 def calculateSolidLayerCount():
430 layerHeight = getProfileSettingFloat('layer_height')
431 solidThickness = getProfileSettingFloat('solid_layer_thickness')
432 return int(math.ceil(solidThickness / layerHeight - 0.0001))
434 def getMachineCenterCoords():
435 if getPreference('machine_center_is_zero') == 'True':
437 return [getPreferenceFloat('machine_width') / 2, getPreferenceFloat('machine_depth') / 2]
439 def getObjectMatrix():
441 return map(float, getProfileSetting('model_matrix').split(','))
443 return [1,0,0, 0,1,0, 0,0,1]
446 #########################################################
447 ## Alteration file functions
448 #########################################################
449 def replaceTagMatch(m):
453 return pre + time.strftime('%H:%M:%S').encode('utf-8', 'replace')
455 return pre + time.strftime('%d %b %Y').encode('utf-8', 'replace')
457 return pre + time.strftime('%a').encode('utf-8', 'replace')
458 if tag == 'print_time':
459 return pre + '#P_TIME#'
460 if tag == 'filament_amount':
461 return pre + '#F_AMNT#'
462 if tag == 'filament_weight':
463 return pre + '#F_WGHT#'
464 if tag == 'filament_cost':
465 return pre + '#F_COST#'
466 if pre == 'F' and tag in ['print_speed', 'retraction_speed', 'travel_speed', 'max_z_speed', 'bottom_layer_speed', 'cool_min_feedrate']:
467 f = getProfileSettingFloat(tag) * 60
468 elif isProfileSetting(tag):
469 f = getProfileSettingFloat(tag)
470 elif isPreference(tag):
471 f = getProfileSettingFloat(tag)
473 return '%s?%s?' % (pre, tag)
475 return pre + str(int(f))
478 def replaceGCodeTags(filename, gcodeInt):
479 f = open(filename, 'r+')
481 data = data.replace('#P_TIME#', ('%5d:%02d' % (int(gcodeInt.totalMoveTimeMinute / 60), int(gcodeInt.totalMoveTimeMinute % 60)))[-8:])
482 data = data.replace('#F_AMNT#', ('%8.2f' % (gcodeInt.extrusionAmount / 1000))[-8:])
483 data = data.replace('#F_WGHT#', ('%8.2f' % (gcodeInt.calculateWeight() * 1000))[-8:])
484 cost = gcodeInt.calculateCost()
487 data = data.replace('#F_COST#', ('%8s' % (cost.split(' ')[0]))[-8:])
492 ### Get aleration raw contents. (Used internally in Cura)
493 def getAlterationFile(filename):
494 #Check if we have a configuration file loaded, else load the default.
495 if not globals().has_key('globalProfileParser'):
496 loadGlobalProfile(getDefaultProfilePath())
498 if not globalProfileParser.has_option('alterations', filename):
499 if filename in alterationDefault:
500 default = alterationDefault[filename]
502 print("Missing default alteration for: '" + filename + "'")
503 alterationDefault[filename] = ''
505 if not globalProfileParser.has_section('alterations'):
506 globalProfileParser.add_section('alterations')
507 #print("Using default for: %s" % (filename))
508 globalProfileParser.set('alterations', filename, default)
509 return unicode(globalProfileParser.get('alterations', filename), "utf-8")
511 def setAlterationFile(filename, value):
512 #Check if we have a configuration file loaded, else load the default.
513 if not globals().has_key('globalProfileParser'):
514 loadGlobalProfile(getDefaultProfilePath())
515 if not globalProfileParser.has_section('alterations'):
516 globalProfileParser.add_section('alterations')
517 globalProfileParser.set('alterations', filename, value.encode("utf-8"))
518 saveGlobalProfile(getDefaultProfilePath())
520 ### Get the alteration file for output. (Used by Skeinforge)
521 def getAlterationFileContents(filename):
524 alterationContents = getAlterationFile(filename)
525 if filename == 'start.gcode':
526 #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.
527 #We also set our steps per E here, if configured.
528 eSteps = getPreferenceFloat('steps_per_e')
530 prefix += 'M92 E%f\n' % (eSteps)
531 temp = getProfileSettingFloat('print_temperature')
533 if getPreference('has_heated_bed') == 'True':
534 bedTemp = getProfileSettingFloat('print_bed_temperature')
536 if bedTemp > 0 and not '{print_bed_temperature}' in alterationContents:
537 prefix += 'M140 S%f\n' % (bedTemp)
538 if temp > 0 and not '{print_temperature}' in alterationContents:
539 prefix += 'M109 S%f\n' % (temp)
540 if bedTemp > 0 and not '{print_bed_temperature}' in alterationContents:
541 prefix += 'M190 S%f\n' % (bedTemp)
542 elif filename == 'end.gcode':
543 #Append the profile string to the end of the GCode, so we can load it from the GCode file later.
544 postfix = ';CURA_PROFILE_STRING:%s\n' % (getGlobalProfileString())
545 elif filename == 'replace.csv':
546 #Always remove the extruder on/off M codes. These are no longer needed in 5D printing.
547 prefix = 'M101\nM103\n'
548 elif filename == 'support_start.gcode' or filename == 'support_end.gcode':
549 #Add support start/end code
550 if getProfileSetting('support_dual_extrusion') == 'True' and int(getPreference('extruder_amount')) > 1:
551 if filename == 'support_start.gcode':
552 setTempOverride('extruder', '1')
554 setTempOverride('extruder', '0')
555 alterationContents = getAlterationFileContents('switchExtruder.gcode')
556 clearTempOverride('extruder')
558 alterationContents = ''
559 return unicode(prefix + re.sub("(.)\{([^\}]*)\}", replaceTagMatch, alterationContents).rstrip() + '\n' + postfix).strip().encode('utf-8') + '\n'
563 def getPluginConfig():
565 return pickle.loads(getProfileSetting('plugin_config'))
569 def setPluginConfig(config):
570 putProfileSetting('plugin_config', pickle.dumps(config))
572 def getPluginBasePaths():
574 if platform.system() != "Windows":
575 ret.append(os.path.expanduser('~/.cura/plugins/'))
576 if platform.system() == "Darwin" and hasattr(sys, 'frozen'):
577 ret.append(os.path.normpath(os.path.join(resources.resourceBasePath, "Cura/plugins")))
579 ret.append(os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'plugins')))
584 for basePath in getPluginBasePaths():
585 for filename in glob.glob(os.path.join(basePath, '*.py')):
586 filename = os.path.basename(filename)
587 if filename.startswith('_'):
589 with open(os.path.join(basePath, filename), "r") as f:
590 item = {'filename': filename, 'name': None, 'info': None, 'type': None, 'params': []}
593 if not line.startswith('#'):
595 line = line[1:].split(':', 1)
598 if line[0].upper() == 'NAME':
599 item['name'] = line[1].strip()
600 elif line[0].upper() == 'INFO':
601 item['info'] = line[1].strip()
602 elif line[0].upper() == 'TYPE':
603 item['type'] = line[1].strip()
604 elif line[0].upper() == 'DEPEND':
606 elif line[0].upper() == 'PARAM':
607 m = re.match('([a-zA-Z][a-zA-Z0-9_]*)\(([a-zA-Z_]*)(?::([^\)]*))?\) +(.*)', line[1].strip())
609 item['params'].append({'name': m.group(1), 'type': m.group(2), 'default': m.group(3), 'description': m.group(4)})
611 print "Unknown item in effect meta data: %s %s" % (line[0], line[1])
612 if item['name'] != None and item['type'] == 'postprocess':
616 def runPostProcessingPlugins(gcodefilename):
617 pluginConfigList = getPluginConfig()
618 pluginList = getPluginList()
620 for pluginConfig in pluginConfigList:
622 for pluginTest in pluginList:
623 if pluginTest['filename'] == pluginConfig['filename']:
629 for basePath in getPluginBasePaths():
630 testFilename = os.path.join(basePath, pluginConfig['filename'])
631 if os.path.isfile(testFilename):
632 pythonFile = testFilename
633 if pythonFile is None:
636 locals = {'filename': gcodefilename}
637 for param in plugin['params']:
638 value = param['default']
639 if param['name'] in pluginConfig['params']:
640 value = pluginConfig['params'][param['name']]
642 if param['type'] == 'float':
646 value = float(param['default'])
648 locals[param['name']] = value
650 execfile(pythonFile, locals)
652 locationInfo = traceback.extract_tb(sys.exc_info()[2])[-1]
653 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])
656 def getSDcardDrives():
658 if platform.system() == "Windows":
659 from ctypes import windll
660 bitmask = windll.kernel32.GetLogicalDrives()
661 for letter in string.uppercase:
663 drives.append(letter + ':/')
665 if platform.system() == "Darwin":
667 for volume in glob.glob('/Volumes/*'):
668 if stat.S_ISLNK(os.lstat(volume).st_mode):
670 drives.append(volume)