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',
53 'model_rotate_base': '0',
54 'model_multiply_x': '1',
55 'model_multiply_y': '1',
56 'extra_base_wall_thickness': '0.0',
57 'sequence': 'Loops > Perimeter > Infill',
58 'force_first_layer_sequence': 'True',
59 'infill_type': 'Line',
63 'support_distance': '0.5',
64 'support_dual_extrusion': 'False',
66 'enable_skin': 'False',
67 'enable_raft': 'False',
68 'cool_min_feedrate': '10',
69 'bridge_speed': '100',
71 'raft_base_material_amount': '100',
72 'raft_interface_material_amount': '100',
73 'bottom_thickness': '0.3',
74 'hop_on_move': 'False',
76 'object_center_x': '-1',
77 'object_center_y': '-1',
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__)), '..', 'resources', 'example', 'UltimakerRobot_support.stl')),
153 'machine_width': '205',
154 'machine_depth': '205',
155 'machine_height': '200',
156 'machine_type': 'unknown',
157 'machine_center_is_zero': 'False',
158 'ultimaker_extruder_upgrade': 'False',
159 'has_heated_bed': 'False',
160 'extruder_amount': '1',
161 'extruder_offset_x1': '-22.0',
162 'extruder_offset_y1': '0.0',
163 'extruder_offset_x2': '0.0',
164 'extruder_offset_y2': '0.0',
165 'extruder_offset_x3': '0.0',
166 'extruder_offset_y3': '0.0',
167 'filament_density': '1300',
169 'serial_port': 'AUTO',
170 'serial_port_auto': '',
171 'serial_baud': 'AUTO',
172 'serial_baud_auto': '',
173 'slicer': 'Cura (Skeinforge based)',
174 'save_profile': 'False',
175 'filament_cost_kg': '0',
176 'filament_cost_meter': '0',
178 'sdshortnames': 'False',
179 'check_for_updates': 'True',
181 'planner_always_autoplace': 'True',
182 'extruder_head_size_min_x': '75.0',
183 'extruder_head_size_min_y': '18.0',
184 'extruder_head_size_max_x': '18.0',
185 'extruder_head_size_max_y': '35.0',
186 'extruder_head_size_height': '60.0',
188 'model_colour': '#72CB30',
189 'model_colour2': '#CB3030',
190 'model_colour3': '#DDD93C',
191 'model_colour4': '#4550D3',
194 #########################################################
195 ## Profile and preferences functions
196 #########################################################
200 if platform.system() == "Windows":
201 basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
202 #If we have a frozen python install, we need to step out of the library.zip
203 if hasattr(sys, 'frozen'):
204 basePath = os.path.normpath(os.path.join(basePath, ".."))
206 basePath = os.path.expanduser('~/.cura/%s' % version.getVersion(False))
207 if not os.path.isdir(basePath):
208 os.makedirs(basePath)
211 def getDefaultProfilePath():
212 return os.path.join(getBasePath(), 'current_profile.ini')
214 def loadGlobalProfile(filename):
215 #Read a configuration file as global config
216 global globalProfileParser
217 globalProfileParser = ConfigParser.ConfigParser()
218 globalProfileParser.read(filename)
220 def resetGlobalProfile():
221 #Read a configuration file as global config
222 global globalProfileParser
223 globalProfileParser = ConfigParser.ConfigParser()
225 if getPreference('machine_type') == 'ultimaker':
226 putProfileSetting('nozzle_size', '0.4')
227 if getPreference('ultimaker_extruder_upgrade') == 'True':
228 putProfileSetting('retraction_enable', 'True')
230 putProfileSetting('nozzle_size', '0.5')
232 def saveGlobalProfile(filename):
233 #Save the current profile to an ini file
234 globalProfileParser.write(open(filename, 'w'))
236 def loadGlobalProfileFromString(options):
237 global globalProfileParser
238 globalProfileParser = ConfigParser.ConfigParser()
239 globalProfileParser.add_section('profile')
240 globalProfileParser.add_section('alterations')
241 options = base64.b64decode(options)
242 options = zlib.decompress(options)
243 (profileOpts, alt) = options.split('\f', 1)
244 for option in profileOpts.split('\b'):
246 (key, value) = option.split('=', 1)
247 globalProfileParser.set('profile', key, value)
248 for option in alt.split('\b'):
250 (key, value) = option.split('=', 1)
251 globalProfileParser.set('alterations', key, value)
253 def getGlobalProfileString():
254 global globalProfileParser
255 if not globals().has_key('globalProfileParser'):
256 loadGlobalProfile(getDefaultProfilePath())
261 if globalProfileParser.has_section('profile'):
262 for key in globalProfileParser.options('profile'):
263 if key in tempOverride:
264 p.append(key + "=" + tempOverride[key])
267 p.append(key + "=" + globalProfileParser.get('profile', key))
268 if globalProfileParser.has_section('alterations'):
269 for key in globalProfileParser.options('alterations'):
270 if key in tempOverride:
271 p.append(key + "=" + tempOverride[key])
274 alt.append(key + "=" + globalProfileParser.get('alterations', key))
275 for key in tempOverride:
276 if key not in tempDone:
277 p.append(key + "=" + tempOverride[key])
278 ret = '\b'.join(p) + '\f' + '\b'.join(alt)
279 ret = base64.b64encode(zlib.compress(ret, 9))
282 def getProfileSetting(name):
283 if name in tempOverride:
284 return unicode(tempOverride[name], "utf-8")
285 #Check if we have a configuration file loaded, else load the default.
286 if not globals().has_key('globalProfileParser'):
287 loadGlobalProfile(getDefaultProfilePath())
288 if not globalProfileParser.has_option('profile', name):
289 if name in profileDefaultSettings:
290 default = profileDefaultSettings[name]
292 print("Missing default setting for: '" + name + "'")
293 profileDefaultSettings[name] = ''
295 if not globalProfileParser.has_section('profile'):
296 globalProfileParser.add_section('profile')
297 globalProfileParser.set('profile', name, str(default))
298 #print(name + " not found in profile, so using default: " + str(default))
300 return globalProfileParser.get('profile', name)
302 def getProfileSettingFloat(name):
304 setting = getProfileSetting(name).replace(',', '.')
305 return float(eval(setting, {}, {}))
306 except (ValueError, SyntaxError, TypeError):
309 def putProfileSetting(name, value):
310 #Check if we have a configuration file loaded, else load the default.
311 if not globals().has_key('globalProfileParser'):
312 loadGlobalProfile(getDefaultProfilePath())
313 if not globalProfileParser.has_section('profile'):
314 globalProfileParser.add_section('profile')
315 globalProfileParser.set('profile', name, str(value))
317 def isProfileSetting(name):
318 if name in profileDefaultSettings:
322 ## Preferences functions
323 global globalPreferenceParser
324 globalPreferenceParser = None
326 def getPreferencePath():
327 return os.path.join(getBasePath(), 'preferences.ini')
329 def getPreferenceFloat(name):
331 setting = getPreference(name).replace(',', '.')
332 return float(eval(setting, {}, {}))
333 except (ValueError, SyntaxError, TypeError):
336 def getPreferenceColour(name):
337 colorString = getPreference(name)
338 return [float(int(colorString[1:3], 16)) / 255, float(int(colorString[3:5], 16)) / 255, float(int(colorString[5:7], 16)) / 255, 1.0]
340 def getPreference(name):
341 if name in tempOverride:
342 return unicode(tempOverride[name])
343 global globalPreferenceParser
344 if globalPreferenceParser is None:
345 globalPreferenceParser = ConfigParser.ConfigParser()
346 globalPreferenceParser.read(getPreferencePath())
347 if not globalPreferenceParser.has_option('preference', name):
348 if name in preferencesDefaultSettings:
349 default = preferencesDefaultSettings[name]
351 print("Missing default setting for: '" + name + "'")
352 preferencesDefaultSettings[name] = ''
354 if not globalPreferenceParser.has_section('preference'):
355 globalPreferenceParser.add_section('preference')
356 globalPreferenceParser.set('preference', name, str(default))
357 #print(name + " not found in preferences, so using default: " + str(default))
359 return unicode(globalPreferenceParser.get('preference', name), "utf-8")
361 def putPreference(name, value):
362 #Check if we have a configuration file loaded, else load the default.
363 global globalPreferenceParser
364 if globalPreferenceParser == None:
365 globalPreferenceParser = ConfigParser.ConfigParser()
366 globalPreferenceParser.read(getPreferencePath())
367 if not globalPreferenceParser.has_section('preference'):
368 globalPreferenceParser.add_section('preference')
369 globalPreferenceParser.set('preference', name, unicode(value).encode("utf-8"))
370 globalPreferenceParser.write(open(getPreferencePath(), 'w'))
372 def isPreference(name):
373 if name in preferencesDefaultSettings:
377 ## Temp overrides for multi-extruder slicing and the project planner.
379 def setTempOverride(name, value):
380 tempOverride[name] = unicode(value).encode("utf-8")
381 def clearTempOverride(name):
382 del tempOverride[name]
383 def resetTempOverride():
386 #########################################################
387 ## Utility functions to calculate common profile values
388 #########################################################
389 def calculateEdgeWidth():
390 wallThickness = getProfileSettingFloat('wall_thickness')
391 nozzleSize = getProfileSettingFloat('nozzle_size')
393 if wallThickness < nozzleSize:
396 lineCount = int(wallThickness / nozzleSize + 0.0001)
397 lineWidth = wallThickness / lineCount
398 lineWidthAlt = wallThickness / (lineCount + 1)
399 if lineWidth > nozzleSize * 1.5:
403 def calculateLineCount():
404 wallThickness = getProfileSettingFloat('wall_thickness')
405 nozzleSize = getProfileSettingFloat('nozzle_size')
407 if wallThickness < nozzleSize:
410 lineCount = int(wallThickness / nozzleSize + 0.0001)
411 lineWidth = wallThickness / lineCount
412 lineWidthAlt = wallThickness / (lineCount + 1)
413 if lineWidth > nozzleSize * 1.5:
417 def calculateSolidLayerCount():
418 layerHeight = getProfileSettingFloat('layer_height')
419 solidThickness = getProfileSettingFloat('solid_layer_thickness')
420 return int(math.ceil(solidThickness / layerHeight - 0.0001))
422 def getMachineCenterCoords():
423 if getPreference('machine_center_is_zero') == 'True':
425 return [getPreferenceFloat('machine_width') / 2, getPreferenceFloat('machine_depth') / 2]
427 def getObjectMatrix():
428 rotate = getProfileSettingFloat('model_rotate_base')
429 rotate = rotate / 180.0 * math.pi
430 scaleX = getProfileSettingFloat('model_scale')
431 scaleY = getProfileSettingFloat('model_scale')
432 scaleZ = getProfileSettingFloat('model_scale')
433 if getProfileSetting('flip_x') == 'True':
435 if getProfileSetting('flip_y') == 'True':
437 if getProfileSetting('flip_z') == 'True':
439 mat00 = math.cos(rotate) * scaleX
440 mat01 =-math.sin(rotate) * scaleY
441 mat10 = math.sin(rotate) * scaleX
442 mat11 = math.cos(rotate) * scaleY
444 mat = [mat00,mat10,0, mat01,mat11,0, 0,0,scaleZ]
445 if getProfileSetting('swap_xz') == 'True':
446 mat = mat[6:9] + mat[3:6] + mat[0:3]
447 if getProfileSetting('swap_yz') == 'True':
448 mat = mat[0:3] + mat[6:9] + mat[3:6]
451 #########################################################
452 ## Alteration file functions
453 #########################################################
454 def replaceTagMatch(m):
458 return pre + time.strftime('%H:%M:%S').encode('utf-8', 'replace')
460 return pre + time.strftime('%d %b %Y').encode('utf-8', 'replace')
462 return pre + time.strftime('%a').encode('utf-8', 'replace')
463 if tag == 'print_time':
464 return pre + '#P_TIME#'
465 if tag == 'filament_amount':
466 return pre + '#F_AMNT#'
467 if tag == 'filament_weight':
468 return pre + '#F_WGHT#'
469 if tag == 'filament_cost':
470 return pre + '#F_COST#'
471 if pre == 'F' and tag in ['print_speed', 'retraction_speed', 'travel_speed', 'max_z_speed', 'bottom_layer_speed', 'cool_min_feedrate']:
472 f = getProfileSettingFloat(tag) * 60
473 elif isProfileSetting(tag):
474 f = getProfileSettingFloat(tag)
475 elif isPreference(tag):
476 f = getProfileSettingFloat(tag)
478 return '%s?%s?' % (pre, tag)
480 return pre + str(int(f))
483 def replaceGCodeTags(filename, gcodeInt):
484 f = open(filename, 'r+')
486 data = data.replace('#P_TIME#', ('%5d:%02d' % (int(gcodeInt.totalMoveTimeMinute / 60), int(gcodeInt.totalMoveTimeMinute % 60)))[-8:])
487 data = data.replace('#F_AMNT#', ('%8.2f' % (gcodeInt.extrusionAmount / 1000))[-8:])
488 data = data.replace('#F_WGHT#', ('%8.2f' % (gcodeInt.calculateWeight() * 1000))[-8:])
489 cost = gcodeInt.calculateCost()
492 data = data.replace('#F_COST#', ('%8s' % (cost.split(' ')[0]))[-8:])
497 ### Get aleration raw contents. (Used internally in Cura)
498 def getAlterationFile(filename):
499 #Check if we have a configuration file loaded, else load the default.
500 if not globals().has_key('globalProfileParser'):
501 loadGlobalProfile(getDefaultProfilePath())
503 if not globalProfileParser.has_option('alterations', filename):
504 if filename in alterationDefault:
505 default = alterationDefault[filename]
507 print("Missing default alteration for: '" + filename + "'")
508 alterationDefault[filename] = ''
510 if not globalProfileParser.has_section('alterations'):
511 globalProfileParser.add_section('alterations')
512 #print("Using default for: %s" % (filename))
513 globalProfileParser.set('alterations', filename, default)
514 return unicode(globalProfileParser.get('alterations', filename), "utf-8")
516 def setAlterationFile(filename, value):
517 #Check if we have a configuration file loaded, else load the default.
518 if not globals().has_key('globalProfileParser'):
519 loadGlobalProfile(getDefaultProfilePath())
520 if not globalProfileParser.has_section('alterations'):
521 globalProfileParser.add_section('alterations')
522 globalProfileParser.set('alterations', filename, value.encode("utf-8"))
523 saveGlobalProfile(getDefaultProfilePath())
525 ### Get the alteration file for output. (Used by Skeinforge)
526 def getAlterationFileContents(filename):
529 alterationContents = getAlterationFile(filename)
530 if filename == 'start.gcode':
531 #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.
532 #We also set our steps per E here, if configured.
533 eSteps = getPreferenceFloat('steps_per_e')
535 prefix += 'M92 E%f\n' % (eSteps)
536 temp = getProfileSettingFloat('print_temperature')
538 if getPreference('has_heated_bed') == 'True':
539 bedTemp = getProfileSettingFloat('print_bed_temperature')
541 if bedTemp > 0 and not '{print_bed_temperature}' in alterationContents:
542 prefix += 'M140 S%f\n' % (bedTemp)
543 if temp > 0 and not '{print_temperature}' in alterationContents:
544 prefix += 'M109 S%f\n' % (temp)
545 if bedTemp > 0 and not '{print_bed_temperature}' in alterationContents:
546 prefix += 'M190 S%f\n' % (bedTemp)
547 elif filename == 'end.gcode':
548 #Append the profile string to the end of the GCode, so we can load it from the GCode file later.
549 postfix = ';CURA_PROFILE_STRING:%s\n' % (getGlobalProfileString())
550 elif filename == 'replace.csv':
551 #Always remove the extruder on/off M codes. These are no longer needed in 5D printing.
552 prefix = 'M101\nM103\n'
553 elif filename == 'support_start.gcode' or filename == 'support_end.gcode':
554 #Add support start/end code
555 if getProfileSetting('support_dual_extrusion') == 'True' and int(getPreference('extruder_amount')) > 1:
556 if filename == 'support_start.gcode':
557 setTempOverride('extruder', '1')
559 setTempOverride('extruder', '0')
560 alterationContents = getAlterationFileContents('switchExtruder.gcode')
561 clearTempOverride('extruder')
563 alterationContents = ''
564 return unicode(prefix + re.sub("(.)\{([^\}]*)\}", replaceTagMatch, alterationContents).rstrip() + '\n' + postfix).strip().encode('utf-8') + '\n'
568 def getPluginConfig():
570 return pickle.loads(getProfileSetting('plugin_config'))
574 def setPluginConfig(config):
575 putProfileSetting('plugin_config', pickle.dumps(config))
577 def getPluginBasePaths():
579 if platform.system() != "Windows":
580 ret.append(os.path.expanduser('~/.cura/plugins/'))
581 if platform.system() == "Darwin" and hasattr(sys, 'frozen'):
582 ret.append(os.path.normpath(os.path.join(resources.resourceBasePath, "Cura/plugins")))
584 ret.append(os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'plugins')))
589 for basePath in getPluginBasePaths():
590 for filename in glob.glob(os.path.join(basePath, '*.py')):
591 filename = os.path.basename(filename)
592 if filename.startswith('_'):
594 with open(os.path.join(basePath, filename), "r") as f:
595 item = {'filename': filename, 'name': None, 'info': None, 'type': None, 'params': []}
598 if not line.startswith('#'):
600 line = line[1:].split(':', 1)
603 if line[0].upper() == 'NAME':
604 item['name'] = line[1].strip()
605 elif line[0].upper() == 'INFO':
606 item['info'] = line[1].strip()
607 elif line[0].upper() == 'TYPE':
608 item['type'] = line[1].strip()
609 elif line[0].upper() == 'DEPEND':
611 elif line[0].upper() == 'PARAM':
612 m = re.match('([a-zA-Z]*)\(([a-zA-Z_]*)(?::([^\)]*))?\) +(.*)', line[1].strip())
614 item['params'].append({'name': m.group(1), 'type': m.group(2), 'default': m.group(3), 'description': m.group(4)})
616 print "Unknown item in effect meta data: %s %s" % (line[0], line[1])
617 if item['name'] != None and item['type'] == 'postprocess':
621 def runPostProcessingPlugins(gcodefilename):
622 pluginConfigList = getPluginConfig()
623 pluginList = getPluginList()
625 for pluginConfig in pluginConfigList:
627 for pluginTest in pluginList:
628 if pluginTest['filename'] == pluginConfig['filename']:
634 for basePath in getPluginBasePaths():
635 testFilename = os.path.join(basePath, pluginConfig['filename'])
636 if os.path.isfile(testFilename):
637 pythonFile = testFilename
638 if pythonFile is None:
641 locals = {'filename': gcodefilename}
642 for param in plugin['params']:
643 value = param['default']
644 if param['name'] in pluginConfig['params']:
645 value = pluginConfig['params'][param['name']]
647 if param['type'] == 'float':
651 value = float(param['default'])
653 locals[param['name']] = value
655 execfile(pythonFile, locals)
657 locationInfo = traceback.extract_tb(sys.exc_info()[2])[-1]
658 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])
661 def getSDcardDrives():
663 if platform.system() == "Windows":
664 from ctypes import windll
665 bitmask = windll.kernel32.GetLogicalDrives()
666 for letter in string.uppercase:
668 drives.append(letter + ':/')
670 if platform.system() == "Darwin":
672 for volume in glob.glob('/Volumes/*'):
673 if stat.S_ISLNK(os.lstat(volume).st_mode):
675 drives.append(volume)