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',
71 'gcode_extension': 'gcode',
72 'alternative_center': '',
77 #######################################################################################
78 'start.gcode': """;Sliced {filename} at: {day} {date} {time}
79 ;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
80 ;Print time: {print_time}
81 ;Filament used: {filament_amount}m {filament_weight}g
82 ;Filament cost: {filament_cost}
84 G90 ;absolute positioning
85 M107 ;start with the fan off
87 G28 X0 Y0 ;move X/Y to min endstops
88 G28 Z0 ;move Z to min endstops
89 G92 X0 Y0 Z0 E0 ;reset software position to front/left/z=0.0
91 G1 Z15.0 F{max_z_speed} ;move the platform down 15mm
93 G92 E0 ;zero the extruded length
94 G1 F200 E3 ;extrude 3mm of feed stock
95 G92 E0 ;zero the extruded length again
98 #######################################################################################
99 'end.gcode': """;End GCode
100 M104 S0 ;extruder heater off
101 M140 S0 ;heated bed heater off (if you have it)
103 G91 ;relative positioning
104 G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
105 G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
106 G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
109 G90 ;absolute positioning
111 #######################################################################################
112 'support_start.gcode': '',
113 'support_end.gcode': '',
114 'cool_start.gcode': '',
115 'cool_end.gcode': '',
117 #######################################################################################
118 '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.
121 G91 ;relative positioning
122 G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
123 G1 Z+0.5 E-5 F{travel_speed} ;move Z up a bit and retract filament even more
124 G90 ;absolute positioning
126 G1 Z{clear_z} F{max_z_speed}
128 G1 X{object_center_x} Y{object_center_x} F{travel_speed}
132 #######################################################################################
133 'switchExtruder.gcode': """;Switch between the current extruder and the next extruder, when printing with multiple extruders.
142 preferencesDefaultSettings = {
143 'startMode': 'Simple',
144 'lastFile': os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'resources', 'example', 'UltimakerRobot_support.stl')),
145 'machine_width': '205',
146 'machine_depth': '205',
147 'machine_height': '200',
148 'machine_type': 'unknown',
149 'machine_center_is_zero': 'False',
150 'ultimaker_extruder_upgrade': 'False',
151 'has_heated_bed': 'False',
152 'extruder_amount': '1',
153 'extruder_offset_x1': '-22.0',
154 'extruder_offset_y1': '0.0',
155 'extruder_offset_x2': '0.0',
156 'extruder_offset_y2': '0.0',
157 'extruder_offset_x3': '0.0',
158 'extruder_offset_y3': '0.0',
159 'filament_density': '1300',
161 'serial_port': 'AUTO',
162 'serial_port_auto': '',
163 'serial_baud': 'AUTO',
164 'serial_baud_auto': '',
165 'slicer': 'Cura (Skeinforge based)',
166 'save_profile': 'False',
167 'filament_cost_kg': '0',
168 'filament_cost_meter': '0',
170 'sdshortnames': 'False',
171 'check_for_updates': 'True',
173 'planner_always_autoplace': 'True',
174 'extruder_head_size_min_x': '75.0',
175 'extruder_head_size_min_y': '18.0',
176 'extruder_head_size_max_x': '18.0',
177 'extruder_head_size_max_y': '35.0',
178 'extruder_head_size_height': '60.0',
180 'model_colour': '#72CB30',
181 'model_colour2': '#CB3030',
182 'model_colour3': '#DDD93C',
183 'model_colour4': '#4550D3',
186 #########################################################
187 ## Profile and preferences functions
188 #########################################################
192 if platform.system() == "Windows":
193 basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
194 #If we have a frozen python install, we need to step out of the library.zip
195 if hasattr(sys, 'frozen'):
196 basePath = os.path.normpath(os.path.join(basePath, ".."))
198 basePath = os.path.expanduser('~/.cura/%s' % version.getVersion(False))
199 if not os.path.isdir(basePath):
200 os.makedirs(basePath)
203 def getDefaultProfilePath():
204 return os.path.join(getBasePath(), 'current_profile.ini')
206 def loadGlobalProfile(filename):
207 #Read a configuration file as global config
208 global globalProfileParser
209 globalProfileParser = ConfigParser.ConfigParser()
210 globalProfileParser.read(filename)
212 def resetGlobalProfile():
213 #Read a configuration file as global config
214 global globalProfileParser
215 globalProfileParser = ConfigParser.ConfigParser()
217 if getPreference('machine_type') == 'ultimaker':
218 putProfileSetting('nozzle_size', '0.4')
219 if getPreference('ultimaker_extruder_upgrade') == 'True':
220 putProfileSetting('retraction_enable', 'True')
222 putProfileSetting('nozzle_size', '0.5')
224 def saveGlobalProfile(filename):
225 #Save the current profile to an ini file
226 globalProfileParser.write(open(filename, 'w'))
228 def loadGlobalProfileFromString(options):
229 global globalProfileParser
230 globalProfileParser = ConfigParser.ConfigParser()
231 globalProfileParser.add_section('profile')
232 globalProfileParser.add_section('alterations')
233 options = base64.b64decode(options)
234 options = zlib.decompress(options)
235 (profileOpts, alt) = options.split('\f', 1)
236 for option in profileOpts.split('\b'):
238 (key, value) = option.split('=', 1)
239 globalProfileParser.set('profile', key, value)
240 for option in alt.split('\b'):
242 (key, value) = option.split('=', 1)
243 globalProfileParser.set('alterations', key, value)
245 def getGlobalProfileString():
246 global globalProfileParser
247 if not globals().has_key('globalProfileParser'):
248 loadGlobalProfile(getDefaultProfilePath())
253 if globalProfileParser.has_section('profile'):
254 for key in globalProfileParser.options('profile'):
255 if key in tempOverride:
256 p.append(key + "=" + tempOverride[key])
259 p.append(key + "=" + globalProfileParser.get('profile', key))
260 if globalProfileParser.has_section('alterations'):
261 for key in globalProfileParser.options('alterations'):
262 if key in tempOverride:
263 p.append(key + "=" + tempOverride[key])
266 alt.append(key + "=" + globalProfileParser.get('alterations', key))
267 for key in tempOverride:
268 if key not in tempDone:
269 p.append(key + "=" + tempOverride[key])
270 ret = '\b'.join(p) + '\f' + '\b'.join(alt)
271 ret = base64.b64encode(zlib.compress(ret, 9))
274 def getProfileSetting(name):
275 if name in tempOverride:
276 return unicode(tempOverride[name], "utf-8")
277 #Check if we have a configuration file loaded, else load the default.
278 if not globals().has_key('globalProfileParser'):
279 loadGlobalProfile(getDefaultProfilePath())
280 if not globalProfileParser.has_option('profile', name):
281 if name in profileDefaultSettings:
282 default = profileDefaultSettings[name]
284 print("Missing default setting for: '" + name + "'")
285 profileDefaultSettings[name] = ''
287 if not globalProfileParser.has_section('profile'):
288 globalProfileParser.add_section('profile')
289 globalProfileParser.set('profile', name, str(default))
290 #print(name + " not found in profile, so using default: " + str(default))
292 return globalProfileParser.get('profile', name)
294 def getProfileSettingFloat(name):
296 setting = getProfileSetting(name).replace(',', '.')
297 return float(eval(setting, {}, {}))
298 except (ValueError, SyntaxError, TypeError):
301 def putProfileSetting(name, value):
302 #Check if we have a configuration file loaded, else load the default.
303 if not globals().has_key('globalProfileParser'):
304 loadGlobalProfile(getDefaultProfilePath())
305 if not globalProfileParser.has_section('profile'):
306 globalProfileParser.add_section('profile')
307 globalProfileParser.set('profile', name, str(value))
309 def isProfileSetting(name):
310 if name in profileDefaultSettings:
314 ## Preferences functions
315 global globalPreferenceParser
316 globalPreferenceParser = None
318 def getPreferencePath():
319 return os.path.join(getBasePath(), 'preferences.ini')
321 def getPreferenceFloat(name):
323 setting = getPreference(name).replace(',', '.')
324 return float(eval(setting, {}, {}))
325 except (ValueError, SyntaxError, TypeError):
328 def getPreferenceColour(name):
329 colorString = getPreference(name)
330 return [float(int(colorString[1:3], 16)) / 255, float(int(colorString[3:5], 16)) / 255, float(int(colorString[5:7], 16)) / 255, 1.0]
332 def getPreference(name):
333 if name in tempOverride:
334 return unicode(tempOverride[name])
335 global globalPreferenceParser
336 if globalPreferenceParser is None:
337 globalPreferenceParser = ConfigParser.ConfigParser()
338 globalPreferenceParser.read(getPreferencePath())
339 if not globalPreferenceParser.has_option('preference', name):
340 if name in preferencesDefaultSettings:
341 default = preferencesDefaultSettings[name]
343 print("Missing default setting for: '" + name + "'")
344 preferencesDefaultSettings[name] = ''
346 if not globalPreferenceParser.has_section('preference'):
347 globalPreferenceParser.add_section('preference')
348 globalPreferenceParser.set('preference', name, str(default))
349 #print(name + " not found in preferences, so using default: " + str(default))
351 return unicode(globalPreferenceParser.get('preference', name), "utf-8")
353 def putPreference(name, value):
354 #Check if we have a configuration file loaded, else load the default.
355 global globalPreferenceParser
356 if globalPreferenceParser == None:
357 globalPreferenceParser = ConfigParser.ConfigParser()
358 globalPreferenceParser.read(getPreferencePath())
359 if not globalPreferenceParser.has_section('preference'):
360 globalPreferenceParser.add_section('preference')
361 globalPreferenceParser.set('preference', name, unicode(value).encode("utf-8"))
362 globalPreferenceParser.write(open(getPreferencePath(), 'w'))
364 def isPreference(name):
365 if name in preferencesDefaultSettings:
369 ## Temp overrides for multi-extruder slicing and the project planner.
371 def setTempOverride(name, value):
372 tempOverride[name] = unicode(value).encode("utf-8")
373 def clearTempOverride(name):
374 del tempOverride[name]
375 def resetTempOverride():
378 #########################################################
379 ## Utility functions to calculate common profile values
380 #########################################################
381 def calculateEdgeWidth():
382 wallThickness = getProfileSettingFloat('wall_thickness')
383 nozzleSize = getProfileSettingFloat('nozzle_size')
385 if wallThickness < nozzleSize:
388 lineCount = int(wallThickness / nozzleSize + 0.0001)
389 lineWidth = wallThickness / lineCount
390 lineWidthAlt = wallThickness / (lineCount + 1)
391 if lineWidth > nozzleSize * 1.5:
395 def calculateLineCount():
396 wallThickness = getProfileSettingFloat('wall_thickness')
397 nozzleSize = getProfileSettingFloat('nozzle_size')
399 if wallThickness < nozzleSize:
402 lineCount = int(wallThickness / nozzleSize + 0.0001)
403 lineWidth = wallThickness / lineCount
404 lineWidthAlt = wallThickness / (lineCount + 1)
405 if lineWidth > nozzleSize * 1.5:
409 def calculateSolidLayerCount():
410 layerHeight = getProfileSettingFloat('layer_height')
411 solidThickness = getProfileSettingFloat('solid_layer_thickness')
412 return int(math.ceil(solidThickness / layerHeight - 0.0001))
414 def getMachineCenterCoords():
415 if getPreference('machine_center_is_zero') == 'True':
417 return [getPreferenceFloat('machine_width') / 2, getPreferenceFloat('machine_depth') / 2]
419 def getObjectMatrix():
420 return map(float, getProfileSetting('model_matrix').split(','))
422 #########################################################
423 ## Alteration file functions
424 #########################################################
425 def replaceTagMatch(m):
429 return pre + time.strftime('%H:%M:%S').encode('utf-8', 'replace')
431 return pre + time.strftime('%d %b %Y').encode('utf-8', 'replace')
433 return pre + time.strftime('%a').encode('utf-8', 'replace')
434 if tag == 'print_time':
435 return pre + '#P_TIME#'
436 if tag == 'filament_amount':
437 return pre + '#F_AMNT#'
438 if tag == 'filament_weight':
439 return pre + '#F_WGHT#'
440 if tag == 'filament_cost':
441 return pre + '#F_COST#'
442 if pre == 'F' and tag in ['print_speed', 'retraction_speed', 'travel_speed', 'max_z_speed', 'bottom_layer_speed', 'cool_min_feedrate']:
443 f = getProfileSettingFloat(tag) * 60
444 elif isProfileSetting(tag):
445 f = getProfileSettingFloat(tag)
446 elif isPreference(tag):
447 f = getProfileSettingFloat(tag)
449 return '%s?%s?' % (pre, tag)
451 return pre + str(int(f))
454 def replaceGCodeTags(filename, gcodeInt):
455 f = open(filename, 'r+')
457 data = data.replace('#P_TIME#', ('%5d:%02d' % (int(gcodeInt.totalMoveTimeMinute / 60), int(gcodeInt.totalMoveTimeMinute % 60)))[-8:])
458 data = data.replace('#F_AMNT#', ('%8.2f' % (gcodeInt.extrusionAmount / 1000))[-8:])
459 data = data.replace('#F_WGHT#', ('%8.2f' % (gcodeInt.calculateWeight() * 1000))[-8:])
460 cost = gcodeInt.calculateCost()
463 data = data.replace('#F_COST#', ('%8s' % (cost.split(' ')[0]))[-8:])
468 ### Get aleration raw contents. (Used internally in Cura)
469 def getAlterationFile(filename):
470 #Check if we have a configuration file loaded, else load the default.
471 if not globals().has_key('globalProfileParser'):
472 loadGlobalProfile(getDefaultProfilePath())
474 if not globalProfileParser.has_option('alterations', filename):
475 if filename in alterationDefault:
476 default = alterationDefault[filename]
478 print("Missing default alteration for: '" + filename + "'")
479 alterationDefault[filename] = ''
481 if not globalProfileParser.has_section('alterations'):
482 globalProfileParser.add_section('alterations')
483 #print("Using default for: %s" % (filename))
484 globalProfileParser.set('alterations', filename, default)
485 return unicode(globalProfileParser.get('alterations', filename), "utf-8")
487 def setAlterationFile(filename, value):
488 #Check if we have a configuration file loaded, else load the default.
489 if not globals().has_key('globalProfileParser'):
490 loadGlobalProfile(getDefaultProfilePath())
491 if not globalProfileParser.has_section('alterations'):
492 globalProfileParser.add_section('alterations')
493 globalProfileParser.set('alterations', filename, value.encode("utf-8"))
494 saveGlobalProfile(getDefaultProfilePath())
496 ### Get the alteration file for output. (Used by Skeinforge)
497 def getAlterationFileContents(filename):
500 alterationContents = getAlterationFile(filename)
501 if filename == 'start.gcode':
502 #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.
503 #We also set our steps per E here, if configured.
504 eSteps = getPreferenceFloat('steps_per_e')
506 prefix += 'M92 E%f\n' % (eSteps)
507 temp = getProfileSettingFloat('print_temperature')
509 if getPreference('has_heated_bed') == 'True':
510 bedTemp = getProfileSettingFloat('print_bed_temperature')
512 if bedTemp > 0 and not '{print_bed_temperature}' in alterationContents:
513 prefix += 'M140 S%f\n' % (bedTemp)
514 if temp > 0 and not '{print_temperature}' in alterationContents:
515 prefix += 'M109 S%f\n' % (temp)
516 if bedTemp > 0 and not '{print_bed_temperature}' in alterationContents:
517 prefix += 'M190 S%f\n' % (bedTemp)
518 elif filename == 'end.gcode':
519 #Append the profile string to the end of the GCode, so we can load it from the GCode file later.
520 postfix = ';CURA_PROFILE_STRING:%s\n' % (getGlobalProfileString())
521 elif filename == 'replace.csv':
522 #Always remove the extruder on/off M codes. These are no longer needed in 5D printing.
523 prefix = 'M101\nM103\n'
524 elif filename == 'support_start.gcode' or filename == 'support_end.gcode':
525 #Add support start/end code
526 if getProfileSetting('support_dual_extrusion') == 'True' and int(getPreference('extruder_amount')) > 1:
527 if filename == 'support_start.gcode':
528 setTempOverride('extruder', '1')
530 setTempOverride('extruder', '0')
531 alterationContents = getAlterationFileContents('switchExtruder.gcode')
532 clearTempOverride('extruder')
534 alterationContents = ''
535 return unicode(prefix + re.sub("(.)\{([^\}]*)\}", replaceTagMatch, alterationContents).rstrip() + '\n' + postfix).strip().encode('utf-8') + '\n'
539 def getPluginConfig():
541 return pickle.loads(getProfileSetting('plugin_config'))
545 def setPluginConfig(config):
546 putProfileSetting('plugin_config', pickle.dumps(config))
548 def getPluginBasePaths():
550 if platform.system() != "Windows":
551 ret.append(os.path.expanduser('~/.cura/plugins/'))
552 if platform.system() == "Darwin" and hasattr(sys, 'frozen'):
553 ret.append(os.path.normpath(os.path.join(resources.resourceBasePath, "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)