Commit 33cd617c authored by Guillaume Seguin's avatar Guillaume Seguin

Fix a shitton of flake8 warnings and errors

parent 5a0b0269
...@@ -17,14 +17,13 @@ ...@@ -17,14 +17,13 @@
# Set up Internationalization using gettext # Set up Internationalization using gettext
# searching for installed locales on /usr/share; uses relative folder if not found (windows) # searching for installed locales on /usr/share; uses relative folder if not found (windows)
import os, Queue, re import os
from printrun.printrun_utils import install_locale from printrun.printrun_utils import install_locale
install_locale('plater') install_locale('plater')
import wx import wx
import time import time
import random
import threading import threading
import math import math
import sys import sys
...@@ -102,8 +101,7 @@ class showstl(wx.Window): ...@@ -102,8 +101,7 @@ class showstl(wx.Window):
return False return False
name = self.parent.l.GetString(name) name = self.parent.l.GetString(name)
model = self.parent.models[name] model = self.parent.models[name]
model.offsets = [ model.offsets = [model.offsets[0] + delta[0],
model.offsets[0] + delta[0],
model.offsets[1] + delta[1], model.offsets[1] + delta[1],
model.offsets[2] model.offsets[2]
] ]
...@@ -114,9 +112,8 @@ class showstl(wx.Window): ...@@ -114,9 +112,8 @@ class showstl(wx.Window):
if event.ButtonUp(wx.MOUSE_BTN_LEFT): if event.ButtonUp(wx.MOUSE_BTN_LEFT):
if(self.initpos is not None): if(self.initpos is not None):
currentpos = event.GetPositionTuple() currentpos = event.GetPositionTuple()
delta = ( delta = (0.5 * (currentpos[0] - self.initpos[0]),
0.5 * (currentpos[0] - self.initpos[0]), -0.5 * (currentpos[1] - self.initpos[1])
- 0.5 * (currentpos[1] - self.initpos[1])
) )
self.move_shape(delta) self.move_shape(delta)
self.Refresh() self.Refresh()
...@@ -205,10 +202,8 @@ class showstl(wx.Window): ...@@ -205,10 +202,8 @@ class showstl(wx.Window):
self.paint(dc = dc) self.paint(dc = dc)
def paint(self, coord1 = "x", coord2 = "y", dc = None): def paint(self, coord1 = "x", coord2 = "y", dc = None):
coords = {"x": 0, "y": 1, "z": 2}
if dc is None: if dc is None:
dc = wx.ClientDC(self) dc = wx.ClientDC(self)
offset = [0, 0]
scale = 2 scale = 2
dc.SetPen(wx.Pen(wx.Colour(100, 100, 100))) dc.SetPen(wx.Pen(wx.Colour(100, 100, 100)))
for i in xrange(20): for i in xrange(20):
...@@ -220,7 +215,6 @@ class showstl(wx.Window): ...@@ -220,7 +215,6 @@ class showstl(wx.Window):
dc.DrawLine(i * scale * 50, 0, i * scale * 50, 400) dc.DrawLine(i * scale * 50, 0, i * scale * 50, 400)
dc.SetBrush(wx.Brush(wx.Colour(128, 255, 128))) dc.SetBrush(wx.Brush(wx.Colour(128, 255, 128)))
dc.SetPen(wx.Pen(wx.Colour(128, 128, 128))) dc.SetPen(wx.Pen(wx.Colour(128, 128, 128)))
t = time.time()
dcs = wx.MemoryDC() dcs = wx.MemoryDC()
for m in self.parent.models.values(): for m in self.parent.models.values():
b = m.bitmap b = m.bitmap
...@@ -241,7 +235,7 @@ class stlwin(wx.Frame): ...@@ -241,7 +235,7 @@ class stlwin(wx.Frame):
def __init__(self, filenames = [], size = (800, 580), callback = None, parent = None, build_dimensions = None): def __init__(self, filenames = [], size = (800, 580), callback = None, parent = None, build_dimensions = None):
wx.Frame.__init__(self, parent, title = _("Plate building tool"), size = size) wx.Frame.__init__(self, parent, title = _("Plate building tool"), size = size)
self.filenames = filenames self.filenames = filenames
if hasattr(sys,"frozen") and sys.frozen=="windows_exe": if hasattr(sys, "frozen") and sys.frozen == "windows_exe":
self.SetIcon(wx.Icon(sys.executable, wx.BITMAP_TYPE_ICO)) self.SetIcon(wx.Icon(sys.executable, wx.BITMAP_TYPE_ICO))
else: else:
self.SetIcon(wx.Icon(pixmapfile("plater.ico"), wx.BITMAP_TYPE_ICO)) self.SetIcon(wx.Icon(pixmapfile("plater.ico"), wx.BITMAP_TYPE_ICO))
...@@ -330,7 +324,8 @@ class stlwin(wx.Frame): ...@@ -330,7 +324,8 @@ class stlwin(wx.Frame):
self.Refresh() self.Refresh()
def clear(self, event): def clear(self, event):
result = wx.MessageBox(_('Are you sure you want to clear the grid? All unsaved changes will be lost.'), _('Clear the grid?'), result = wx.MessageBox(_('Are you sure you want to clear the grid? All unsaved changes will be lost.'),
_('Clear the grid?'),
wx.YES_NO | wx.ICON_QUESTION) wx.YES_NO | wx.ICON_QUESTION)
if (result == 2): if (result == 2):
self.models = {} self.models = {}
...@@ -442,7 +437,6 @@ class stlwin(wx.Frame): ...@@ -442,7 +437,6 @@ class stlwin(wx.Frame):
return return
path = os.path.split(name)[0] path = os.path.split(name)[0]
self.basedir = path self.basedir = path
t = time.time()
#print name #print name
if name.lower().endswith(".stl"): if name.lower().endswith(".stl"):
#Filter out the path, just show the STL filename. #Filter out the path, just show the STL filename.
......
This diff is collapsed.
...@@ -30,7 +30,6 @@ ...@@ -30,7 +30,6 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import re
import gcoder import gcoder
class GCodeAnalyzer(): class GCodeAnalyzer():
...@@ -81,9 +80,8 @@ class GCodeAnalyzer(): ...@@ -81,9 +80,8 @@ class GCodeAnalyzer():
self.lastY = self.y self.lastY = self.y
self.lastZ = self.z self.lastZ = self.z
self.lastE = self.e self.lastE = self.e
eChanged = False;
code_f = gline.f code_f = gline.f
if code_f != None: if code_f is not None:
self.f = code_f self.f = code_f
code_x = gline.x code_x = gline.x
...@@ -92,27 +90,24 @@ class GCodeAnalyzer(): ...@@ -92,27 +90,24 @@ class GCodeAnalyzer():
code_e = gline.e code_e = gline.e
if self.relative: if self.relative:
if code_x != None: self.x += code_x if code_x is not None: self.x += code_x
if code_y != None: self.y += code_y if code_y is not None: self.y += code_y
if code_z != None: self.z += code_z if code_z is not None: self.z += code_z
if code_e != None: if code_e is not None:
if code_e != 0: if code_e != 0:
eChanged = True
self.e += code_e self.e += code_e
else: else:
# absolute coordinates # absolute coordinates
if code_x != None: self.x = self.xOffset + code_x if code_x is not None: self.x = self.xOffset + code_x
if code_y != None: self.y = self.yOffset + code_y if code_y is not None: self.y = self.yOffset + code_y
if code_z != None: self.z = self.zOffset + code_z if code_z is not None: self.z = self.zOffset + code_z
if code_e != None: if code_e is not None:
if self.eRelative: if self.eRelative:
if code_e != 0: if code_e != 0:
eChanged = True
self.e += code_e self.e += code_e
else: else:
# e is absolute. Is it changed? # e is absolute. Is it changed?
if self.e != self.eOffset + code_e: if self.e != self.eOffset + code_e:
eChanged = True
self.e = self.eOffset + code_e self.e = self.eOffset + code_e
#limit checking #limit checking
""" """
...@@ -137,20 +132,20 @@ class GCodeAnalyzer(): ...@@ -137,20 +132,20 @@ class GCodeAnalyzer():
code_z = gline.z code_z = gline.z
code_e = gline.e code_e = gline.e
homeAll = False homeAll = False
if code_x == None and code_y == None and code_z == None: homeAll = True if code_x is None and code_y is None and code_z is None: homeAll = True
if code_x != None or homeAll: if code_x is not None or homeAll:
self.hasHomeX = True self.hasHomeX = True
self.xOffset = 0 self.xOffset = 0
self.x = self.homeX self.x = self.homeX
if code_y != None or homeAll: if code_y is not None or homeAll:
self.hasHomeY = True self.hasHomeY = True
self.yOffset = 0 self.yOffset = 0
self.y = self.homeY self.y = self.homeY
if code_z != None or homeAll: if code_z is not None or homeAll:
self.hasHomeZ = True self.hasHomeZ = True
self.zOffset = 0 self.zOffset = 0
self.z = self.homeZ self.z = self.homeZ
if code_e != None: if code_e is not None:
self.eOffset = 0 self.eOffset = 0
self.e = 0 self.e = 0
elif code_g == 162: elif code_g == 162:
...@@ -162,16 +157,16 @@ class GCodeAnalyzer(): ...@@ -162,16 +157,16 @@ class GCodeAnalyzer():
code_y = gline.y code_y = gline.y
code_z = gline.z code_z = gline.z
homeAll = False homeAll = False
if code_x == None and code_y == None and code_z == None: homeAll = True if code_x is None and code_y is None and code_z is None: homeAll = True
if code_x != None or homeAll: if code_x is not None or homeAll:
self.hasHomeX = True self.hasHomeX = True
self.xOffset = 0 self.xOffset = 0
self.x = self.maxX self.x = self.maxX
if code_y != None or homeAll: if code_y is not None or homeAll:
self.hasHomeY = True self.hasHomeY = True
self.yOffset = 0 self.yOffset = 0
self.y = self.maxY self.y = self.maxY
if code_z != None or homeAll: if code_z is not None or homeAll:
self.hasHomeZ = True self.hasHomeZ = True
self.zOffset = 0 self.zOffset = 0
self.z = self.maxZ self.z = self.maxZ
...@@ -182,20 +177,20 @@ class GCodeAnalyzer(): ...@@ -182,20 +177,20 @@ class GCodeAnalyzer():
code_y = gline.y code_y = gline.y
code_z = gline.z code_z = gline.z
code_e = gline.e code_e = gline.e
if code_x != None: if code_x is not None:
self.xOffset = self.x - float(code_x) self.xOffset = self.x - float(code_x)
self.x = self.xOffset self.x = self.xOffset
if code_y != None: if code_y is not None:
self.yOffset = self.y - float(code_y) self.yOffset = self.y - float(code_y)
self.y = self.yOffset self.y = self.yOffset
if code_z != None: if code_z is not None:
self.zOffset = self.z - float(code_z) self.zOffset = self.z - float(code_z)
self.z = self.zOffset self.z = self.zOffset
if code_e != None: if code_e is not None:
self.xOffset = self.e - float(code_e) self.xOffset = self.e - float(code_e)
self.e = self.eOffset self.e = self.eOffset
#End code_g != None #End code_g is not None
if code_m != None: if code_m is not None:
if code_m == 82: self.eRelative = False if code_m == 82: self.eRelative = False
elif code_m == 83: self.eRelative = True elif code_m == 83: self.eRelative = True
......
...@@ -38,15 +38,14 @@ class SkeinforgeQuickEditDialog(wx.Dialog): ...@@ -38,15 +38,14 @@ class SkeinforgeQuickEditDialog(wx.Dialog):
NOTE: Skeinforge is tightly integrated with Tkinter and there appears to be a dependency which stops radio-button values from being saved. NOTE: Skeinforge is tightly integrated with Tkinter and there appears to be a dependency which stops radio-button values from being saved.
Perhaps this can be solved, but at the moment this dialog cannot modify radio button values. One will have to use the main Skeinforge application. Perhaps this can be solved, but at the moment this dialog cannot modify radio button values. One will have to use the main Skeinforge application.
""" """
self.moduleSettingsMap = { self.moduleSettingsMap = {'dimension': ['Filament Diameter (mm):', 'Retraction Distance (millimeters):', 'Retraction Distance (millimeters):', 'Extruder Retraction Speed (mm/s):'],
'dimension':['Filament Diameter (mm):','Retraction Distance (millimeters):', 'Retraction Distance (millimeters):','Extruder Retraction Speed (mm/s):'], 'carve': ['Layer Height = Extrusion Thickness (mm):', 'Extrusion Width (mm):'],
'carve':['Layer Height = Extrusion Thickness (mm):', 'Extrusion Width (mm):'], 'chamber': ['Heated PrintBed Temperature (Celcius):', 'Turn print Bed Heater Off at Shut Down', 'Turn Extruder Heater Off at Shut Down'],
'chamber':['Heated PrintBed Temperature (Celcius):', 'Turn print Bed Heater Off at Shut Down', 'Turn Extruder Heater Off at Shut Down'], 'cool': ['Activate Cool.. but use with a fan!', 'Use Cool if layer takes shorter than(seconds):'],
'cool':['Activate Cool.. but use with a fan!', 'Use Cool if layer takes shorter than(seconds):'], 'fill': ['Activate Fill:', 'Infill Solidity (ratio):', 'Fully filled Layers (each top and bottom):', 'Extra Shells on Sparse Layer (layers):', 'Extra Shells on Alternating Solid Layer (layers):'],
'fill':['Activate Fill:', 'Infill Solidity (ratio):', 'Fully filled Layers (each top and bottom):', 'Extra Shells on Sparse Layer (layers):', 'Extra Shells on Alternating Solid Layer (layers):'], 'multiply': ['Number of Columns (integer):', 'Number of Rows (integer):'],
'multiply':['Number of Columns (integer):', 'Number of Rows (integer):'], 'raft': ['First Layer Main Feedrate (mm/s):', 'First Layer Perimeter Feedrate (mm/s):', 'First Layer Flow Rate Infill(scaler):', 'First Layer Flow Rate Perimeter(scaler):'],
'raft':['First Layer Main Feedrate (mm/s):','First Layer Perimeter Feedrate (mm/s):','First Layer Flow Rate Infill(scaler):','First Layer Flow Rate Perimeter(scaler):',], 'speed': ['Main Feed Rate (mm/s):', 'Main Flow Rate (scaler):', 'Perimeter Feed Rate (mm/s):', 'Perimeter Flow Rate (scaler):', 'Travel Feed Rate (mm/s):']
'speed':['Main Feed Rate (mm/s):','Main Flow Rate (scaler):','Perimeter Feed Rate (mm/s):','Perimeter Flow Rate (scaler):','Travel Feed Rate (mm/s):']
} }
self.scrollbarPanel = wx.ScrolledWindow(self, -1, style = wx.TAB_TRAVERSAL) self.scrollbarPanel = wx.ScrolledWindow(self, -1, style = wx.TAB_TRAVERSAL)
...@@ -140,7 +139,7 @@ class SkeinforgeQuickEditDialog(wx.Dialog): ...@@ -140,7 +139,7 @@ class SkeinforgeQuickEditDialog(wx.Dialog):
isDirty = False isDirty = False
for setting in settings.getReadRepository(repo).preferences: for setting in settings.getReadRepository(repo).preferences:
if setting.name == settingName: if setting.name == settingName:
if setting.value == None or str(x.GetValue()) != str(setting.value): if setting.value is None or str(x.GetValue()) != str(setting.value):
print('Saving ... ' + settingName + ' = ' + str(x.GetValue())) print('Saving ... ' + settingName + ' = ' + str(x.GetValue()))
setting.value = x.GetValue() setting.value = x.GetValue()
isDirty = True isDirty = True
......
...@@ -62,14 +62,14 @@ class BufferedCanvas(wx.Panel): ...@@ -62,14 +62,14 @@ class BufferedCanvas(wx.Panel):
ID=-1, ID=-1,
pos = wx.DefaultPosition, pos = wx.DefaultPosition,
size = wx.DefaultSize, size = wx.DefaultSize,
style = wx.NO_FULL_REPAINT_ON_RESIZE|wx.WANTS_CHARS): style = wx.NO_FULL_REPAINT_ON_RESIZE | wx.WANTS_CHARS):
wx.Panel.__init__(self, parent, ID, pos, size, style) wx.Panel.__init__(self, parent, ID, pos, size, style)
# Bind events # Bind events
self.Bind(wx.EVT_PAINT, self.onPaint) self.Bind(wx.EVT_PAINT, self.onPaint)
# Disable background erasing (flicker-licious) # Disable background erasing (flicker-licious)
def disable_event(*pargs,**kwargs): def disable_event(*pargs, **kwargs):
pass # the sauce, please pass # the sauce, please
self.Bind(wx.EVT_ERASE_BACKGROUND, disable_event) self.Bind(wx.EVT_ERASE_BACKGROUND, disable_event)
......
...@@ -17,27 +17,30 @@ ...@@ -17,27 +17,30 @@
#Interactive RepRap e axis calibration program #Interactive RepRap e axis calibration program
#(C) Nathan Zadoks 2011 #(C) Nathan Zadoks 2011
s = 300 #Extrusion speed (mm/min) s = 300 # Extrusion speed (mm/min)
n = 100 #Default length to extrude n = 100 # Default length to extrude
m= 0 #User-entered measured extrusion length m = 0 # User-entered measured extrusion length
k = 300 #Default amount of steps per mm k = 300 # Default amount of steps per mm
port='/dev/ttyUSB0' #Default serial port to connect to printer port = '/dev/ttyUSB0' # Default serial port to connect to printer
temp = 210 #Default extrusion temperature temp = 210 # Default extrusion temperature
tempmax = 250 #Maximum extrusion temperature tempmax = 250 # Maximum extrusion temperature
t = int(n*60)/s #Time to wait for extrusion t = int(n * 60) / s # Time to wait for extrusion
try: try:
from printdummy import printcore from printdummy import printcore
except ImportError: except ImportError:
from printcore import printcore from printcore import printcore
import time, getopt, sys, os
import time
import getopt
import sys
import os
def float_input(prompt=''): def float_input(prompt=''):
import sys
f = None f = None
while f == None: while f is None:
s = raw_input(prompt) s = raw_input(prompt)
try: try:
f = float(s) f = float(s)
...@@ -46,14 +49,13 @@ def float_input(prompt=''): ...@@ -46,14 +49,13 @@ def float_input(prompt=''):
sys.stderr.flush() sys.stderr.flush()
return f return f
def wait(t, m=''): def wait(t, m=''):
import time, sys sys.stdout.write(m + '[' + (' ' * t) + ']\r' + m + '[')
sys.stdout.write(m+'['+(' '*t)+']\r'+m+'[')
sys.stdout.flush() sys.stdout.flush()
for i in range(t): for i in range(t):
for s in ['|\b','/\b','-\b','\\\b','|']: for s in ['|\b', '/\b', '-\b', '\\\b', '|']:
sys.stdout.write(s) sys.stdout.write(s)
sys.stdout.flush() sys.stdout.flush()
time.sleep(1.0/5) time.sleep(1.0 / 5)
print print
def w(s): def w(s):
sys.stdout.write(s) sys.stdout.write(s)
...@@ -62,31 +64,31 @@ def w(s): ...@@ -62,31 +64,31 @@ def w(s):
def heatup(p, temp, s = 0): def heatup(p, temp, s = 0):
curtemp = gettemp(p) curtemp = gettemp(p)
p.send_now('M109 S%03d'%temp) p.send_now('M109 S%03d' % temp)
p.temp = 0 p.temp = 0
if not s: w("Heating extruder up..") if not s: w("Heating extruder up..")
f = False f = False
while curtemp<=(temp-1): while curtemp <= (temp - 1):
p.send_now('M105') p.send_now('M105')
time.sleep(0.5) time.sleep(0.5)
if not f: if not f:
time.sleep(1.5) time.sleep(1.5)
f = True f = True
curtemp = gettemp(p) curtemp = gettemp(p)
if curtemp: w(u"\rHeating extruder up.. %3d \xb0C"%curtemp) if curtemp: w(u"\rHeating extruder up.. %3d \xb0C" % curtemp)
if s: print if s: print
else: print "\nReady." else: print "\nReady."
def gettemp(p): def gettemp(p):
try: p.logl try: p.logl
except: setattr(p,'logl',0) except: setattr(p, 'logl', 0)
try: p.temp try: p.temp
except: setattr(p,'temp',0) except: setattr(p, 'temp', 0)
for n in range(p.logl, len(p.log)): for n in range(p.logl, len(p.log)):
line = p.log[n] line = p.log[n]
if 'T:' in line: if 'T:' in line:
try: try:
setattr(p,'temp',int(line.split('T:')[1].split()[0])) setattr(p, 'temp', int(line.split('T:')[1].split()[0]))
except: print line except: print line
p.logl = len(p.log) p.logl = len(p.log)
return p.temp return p.temp
...@@ -101,35 +103,35 @@ help = u""" ...@@ -101,35 +103,35 @@ help = u"""
-t --temp Extrusion temperature in degrees Celsius (default: %d \xb0C, max %d \xb0C) -t --temp Extrusion temperature in degrees Celsius (default: %d \xb0C, max %d \xb0C)
-p --port Serial port the printer is connected to (default: %s) -p --port Serial port the printer is connected to (default: %s)
-h --help This cruft. -h --help This cruft.
"""[1:-1].encode('utf-8')%(sys.argv[0], n, k, temp, tempmax, port if port else 'auto') """[1:-1].encode('utf-8') % (sys.argv[0], n, k, temp, tempmax, port if port else 'auto')
try: try:
opts, args = getopt.getopt(sys.argv[1:],"hl:s:t:p:",["help", "length=", "steps=", "temp=", "port="]) opts, args = getopt.getopt(sys.argv[1:], "hl:s:t:p:", ["help", "length=", "steps=", "temp=", "port="])
except getopt.GetoptError, err: except getopt.GetoptError, err:
print str(err) print str(err)
print help print help
sys.exit(2) sys.exit(2)
for o, a in opts: for o, a in opts:
if o in ('-h','--help'): if o in ('-h', '--help'):
print help print help
sys.exit() sys.exit()
elif o in ('-l','--length'): elif o in ('-l', '--length'):
n = float(a) n = float(a)
elif o in ('-s','--steps'): elif o in ('-s', '--steps'):
k = int(a) k = int(a)
elif o in ('-t','--temp'): elif o in ('-t', '--temp'):
temp = int(a) temp = int(a)
if temp>=tempmax: if temp >= tempmax:
print (u'%d \xb0C? Are you insane?'.encode('utf-8')%temp)+(" That's over nine thousand!" if temp>9000 else '') print (u'%d \xb0C? Are you insane?'.encode('utf-8') % temp) + (" That's over nine thousand!" if temp > 9000 else '')
sys.exit(255) sys.exit(255)
elif o in ('-p','--port'): elif o in ('-p', '--port'):
port = a port = a
#Show initial parameters #Show initial parameters
print "Initial parameters" print "Initial parameters"
print "Steps per mm: %3d steps"%k print "Steps per mm: %3d steps" % k
print "Length extruded: %3d mm"%n print "Length extruded: %3d mm" % n
print print
print "Serial port: %s"%(port if port else 'auto') print "Serial port: %s" % (port if port else 'auto')
p = None p = None
try: try:
...@@ -148,18 +150,18 @@ try: ...@@ -148,18 +150,18 @@ try:
heatup(p, temp) heatup(p, temp)
#Calibration loop #Calibration loop
while n!=m: while n != m:
heatup(p, temp, True) heatup(p, temp, True)
p.send_now("G92 E0") #Reset e axis p.send_now("G92 E0") # Reset e axis
p.send_now("G1 E%d F%d"%(n, s)) #Extrude length of filament p.send_now("G1 E%d F%d" % (n, s)) # Extrude length of filament
wait(t,'Extruding.. ') wait(t, 'Extruding.. ')
m = float_input("How many millimeters of filament were extruded? ") m = float_input("How many millimeters of filament were extruded? ")
if m == 0: continue if m == 0: continue
if n!=m: if n != m:
k = (n/m)*k k = (n / m) * k
p.send_now("M92 E%d"%int(round(k))) #Set new step count p.send_now("M92 E%d" % int(round(k))) # Set new step count
print "Steps per mm: %3d steps"%k #Tell user print "Steps per mm: %3d steps" % k # Tell user
print 'Calibration completed.' #Yay! print 'Calibration completed.' # Yay!
except KeyboardInterrupt: except KeyboardInterrupt:
pass pass
finally: finally:
......
...@@ -24,7 +24,10 @@ class ExcluderWindow(gviz.GvizWindow): ...@@ -24,7 +24,10 @@ class ExcluderWindow(gviz.GvizWindow):
def __init__(self, excluder, *args, **kwargs): def __init__(self, excluder, *args, **kwargs):
super(ExcluderWindow, self).__init__(*args, **kwargs) super(ExcluderWindow, self).__init__(*args, **kwargs)
self.SetTitle(_("Part excluder: draw rectangles where print instructions should be ignored")) self.SetTitle(_("Part excluder: draw rectangles where print instructions should be ignored"))
self.toolbar.AddLabelTool(128, " " + _("Reset selection"), wx.Image(imagefile('reset.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap(), shortHelp = _("Reset selection"), longHelp = "") self.toolbar.AddLabelTool(128, " " + _("Reset selection"),
wx.Image(imagefile('reset.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap(),
shortHelp = _("Reset selection"),
longHelp = "")
self.Bind(wx.EVT_TOOL, self.reset_selection, id = 128) self.Bind(wx.EVT_TOOL, self.reset_selection, id = 128)
self.parent = excluder self.parent = excluder
self.p.paint_overlay = self.paint_selection self.p.paint_overlay = self.paint_selection
...@@ -39,7 +42,8 @@ class ExcluderWindow(gviz.GvizWindow): ...@@ -39,7 +42,8 @@ class ExcluderWindow(gviz.GvizWindow):
self.p.build_dimensions[1] - (y - self.p.build_dimensions[4])) self.p.build_dimensions[1] - (y - self.p.build_dimensions[4]))
def mouse(self, event): def mouse(self, event):
if event.ButtonUp(wx.MOUSE_BTN_LEFT) or event.ButtonUp(wx.MOUSE_BTN_RIGHT): if event.ButtonUp(wx.MOUSE_BTN_LEFT) \
or event.ButtonUp(wx.MOUSE_BTN_RIGHT):
self.initpos = None self.initpos = None
elif event.Dragging() and event.RightIsDown(): elif event.Dragging() and event.RightIsDown():
e = event.GetPositionTuple() e = event.GetPositionTuple()
...@@ -74,11 +78,11 @@ class ExcluderWindow(gviz.GvizWindow): ...@@ -74,11 +78,11 @@ class ExcluderWindow(gviz.GvizWindow):
def _line_scaler(self, orig): def _line_scaler(self, orig):
x0, y0 = self.gcode_to_real(orig[0], orig[1]) x0, y0 = self.gcode_to_real(orig[0], orig[1])
x0 = self.p.scale[0]*x0 + self.p.translate[0] x0 = self.p.scale[0] * x0 + self.p.translate[0]
y0 = self.p.scale[1]*y0 + self.p.translate[1] y0 = self.p.scale[1] * y0 + self.p.translate[1]
x1, y1 = self.gcode_to_real(orig[2], orig[3]) x1, y1 = self.gcode_to_real(orig[2], orig[3])
x1 = self.p.scale[0]*x1 + self.p.translate[0] x1 = self.p.scale[0] * x1 + self.p.translate[0]
y1 = self.p.scale[1]*y1 + self.p.translate[1] y1 = self.p.scale[1] * y1 + self.p.translate[1]
width = max(x0, x1) - min(x0, x1) + 1 width = max(x0, x1) - min(x0, x1) + 1
height = max(y0, y1) - min(y0, y1) + 1 height = max(y0, y1) - min(y0, y1) + 1
return (min(x0, x1), min(y0, y1), width, height,) return (min(x0, x1), min(y0, y1), width, height,)
...@@ -86,7 +90,8 @@ class ExcluderWindow(gviz.GvizWindow): ...@@ -86,7 +90,8 @@ class ExcluderWindow(gviz.GvizWindow):
def paint_selection(self, dc): def paint_selection(self, dc):
dc = wx.GCDC(dc) dc = wx.GCDC(dc)
dc.SetPen(wx.TRANSPARENT_PEN) dc.SetPen(wx.TRANSPARENT_PEN)
dc.DrawRectangleList([self._line_scaler(rect) for rect in self.parent.rectangles], dc.DrawRectangleList([self._line_scaler(rect)
for rect in self.parent.rectangles],
None, wx.Brush((200, 200, 200, 150))) None, wx.Brush((200, 200, 200, 150)))
def reset_selection(self, event): def reset_selection(self, event):
...@@ -117,6 +122,7 @@ class Excluder(object): ...@@ -117,6 +122,7 @@ class Excluder(object):
if __name__ == '__main__': if __name__ == '__main__':
import sys import sys
import gcoder
gcode = gcoder.GCode(open(sys.argv[1])) gcode = gcoder.GCode(open(sys.argv[1]))
app = wx.App(False) app = wx.App(False)
ex = Excluder() ex = Excluder()
......
...@@ -30,10 +30,11 @@ move_gcodes = ["G0", "G1", "G2", "G3"] ...@@ -30,10 +30,11 @@ move_gcodes = ["G0", "G1", "G2", "G3"]
class PyLine(object): class PyLine(object):
__slots__ = ('x','y','z','e','f','i','j', __slots__ = ('x', 'y', 'z', 'e', 'f', 'i', 'j',
'raw', 'command', 'is_move', 'raw', 'command', 'is_move',
'relative','relative_e', 'relative', 'relative_e',
'current_x', 'current_y', 'current_z', 'extruding', 'current_tool', 'current_x', 'current_y', 'current_z', 'extruding',
'current_tool',
'gcview_end_vertex') 'gcview_end_vertex')
def __init__(self, l): def __init__(self, l):
...@@ -75,7 +76,7 @@ def parse_coordinates(line, split_raw, imperial = False, force = False): ...@@ -75,7 +76,7 @@ def parse_coordinates(line, split_raw, imperial = False, force = False):
for bit in split_raw: for bit in split_raw:
code = bit[0] code = bit[0]
if code not in gcode_parsed_nonargs and bit[1]: if code not in gcode_parsed_nonargs and bit[1]:
setattr(line, code, unit_factor*float(bit[1])) setattr(line, code, unit_factor * float(bit[1]))
class Layer(list): class Layer(list):
...@@ -92,8 +93,6 @@ class Layer(list): ...@@ -92,8 +93,6 @@ class Layer(list):
xmax = float("-inf") xmax = float("-inf")
ymax = float("-inf") ymax = float("-inf")
zmax = float("-inf") zmax = float("-inf")
relative = False
relative_e = False
for line in self: for line in self:
if not line.is_move and line.command != "G92": if not line.is_move and line.command != "G92":
...@@ -131,7 +130,8 @@ class Layer(list): ...@@ -131,7 +130,8 @@ class Layer(list):
line.current_x = current_x line.current_x = current_x
line.current_y = current_y line.current_y = current_y
line.current_z = current_z line.current_z = current_z
return (current_x, current_y, current_z), (xmin, xmax), (ymin, ymax), (zmin, zmax) return ((current_x, current_y, current_z),
(xmin, xmax), (ymin, ymax), (zmin, zmax))
class GCode(object): class GCode(object):
...@@ -161,7 +161,7 @@ class GCode(object): ...@@ -161,7 +161,7 @@ class GCode(object):
est_layer_height = None est_layer_height = None
def __init__(self,data): def __init__(self, data):
self.lines = [Line(l2) for l2 in self.lines = [Line(l2) for l2 in
(l.strip() for l in data) (l.strip() for l in data)
if l2] if l2]
...@@ -190,7 +190,7 @@ class GCode(object): ...@@ -190,7 +190,7 @@ class GCode(object):
return gline return gline
def _preprocess_lines(self, lines = None): def _preprocess_lines(self, lines = None):
"""Checks for G20, G21, G90 and G91, sets imperial and relative flags""" """Checks for imperial/relativeness settings and tool changes"""
if not lines: if not lines:
lines = self.lines lines = self.lines
imperial = self.imperial imperial = self.imperial
...@@ -236,7 +236,7 @@ class GCode(object): ...@@ -236,7 +236,7 @@ class GCode(object):
max_e = 0 max_e = 0
for line in lines: for line in lines:
if line.e == None: if line.e is None:
continue continue
if line.is_move: if line.is_move:
if line.relative_e: if line.relative_e:
...@@ -268,23 +268,24 @@ class GCode(object): ...@@ -268,23 +268,24 @@ class GCode(object):
cur_z = None cur_z = None
cur_lines = [] cur_lines = []
for line in self.lines: for line in self.lines:
if line.command == "G92" and line.z != None: if line.command == "G92" and line.z is not None:
cur_z = line.z cur_z = line.z
elif line.is_move: elif line.is_move:
if line.z != None: if line.z is not None:
if line.relative: if line.relative:
cur_z += line.z cur_z += line.z
else: else:
cur_z = line.z cur_z = line.z
# FIXME: the logic behind this code seems to work, but it might be broken # FIXME: the logic behind this code seems to work, but it might be
# broken
if cur_z != prev_z: if cur_z != prev_z:
if prev_z is not None and last_layer_z is not None: if prev_z is not None and last_layer_z is not None:
offset = self.est_layer_height if self.est_layer_height else 0.01 offset = self.est_layer_height if self.est_layer_height else 0.01
if abs(prev_z - last_layer_z) < offset: if abs(prev_z - last_layer_z) < offset:
if self.est_layer_height is None: if self.est_layer_height is None:
zs = sorted([l.z for l in all_layers if l.z != None]) zs = sorted([l.z for l in all_layers if l.z is not None])
heights = [round(zs[i+1] - zs[i], 3) for i in range(len(zs) - 1)] heights = [round(zs[i + 1] - zs[i], 3) for i in range(len(zs) - 1)]
if len(heights) >= 2: self.est_layer_height = heights[1] if len(heights) >= 2: self.est_layer_height = heights[1]
elif heights: self.est_layer_height = heights[0] elif heights: self.est_layer_height = heights[0]
else: self.est_layer_height = 0.1 else: self.est_layer_height = 0.1
...@@ -322,7 +323,7 @@ class GCode(object): ...@@ -322,7 +323,7 @@ class GCode(object):
cur_lines = layers[zindex] cur_lines = layers[zindex]
has_movement = False has_movement = False
for l in layers[zindex]: for l in layers[zindex]:
if l.is_move and l.e != None: if l.is_move and l.e is not None:
has_movement = True has_movement = True
break break
if has_movement: if has_movement:
...@@ -357,7 +358,8 @@ class GCode(object): ...@@ -357,7 +358,8 @@ class GCode(object):
current_z = 0 current_z = 0
for l in self.all_layers: for l in self.all_layers:
(current_x, current_y, current_z), (xm, xM), (ym, yM), (zm, zM) = l._preprocess(current_x, current_y, current_z) (current_x, current_y, current_z), (xm, xM), (ym, yM), (zm, zM) = \
l._preprocess(current_x, current_y, current_z)
xmin = min(xm, xmin) xmin = min(xm, xmin)
xmax = max(xM, xmax) xmax = max(xM, xmax)
ymin = min(ym, ymin) ymin = min(ym, ymin)
...@@ -376,18 +378,16 @@ class GCode(object): ...@@ -376,18 +378,16 @@ class GCode(object):
self.height = self.zmax - self.zmin self.height = self.zmax - self.zmin
def estimate_duration(self): def estimate_duration(self):
lastx = lasty = lastz = laste = lastf = 0.0 lastx = lasty = laste = lastf = 0.0
x = y = z = e = f = 0.0 x = y = e = f = 0.0
currenttravel = 0.0 currenttravel = 0.0
totaltravel = 0.0
moveduration = 0.0 moveduration = 0.0
totalduration = 0.0 totalduration = 0.0
acceleration = 1500.0 #mm/s/s ASSUMING THE DEFAULT FROM SPRINTER !!!! acceleration = 1500.0 # mm/s/s ASSUMING THE DEFAULT FROM SPRINTER !!!
layerduration = 0.0
layerbeginduration = 0.0 layerbeginduration = 0.0
layercount = 0
#TODO: #TODO:
# get device caps from firmware: max speed, acceleration/axis (including extruder) # get device caps from firmware: max speed, acceleration/axis
# (including extruder)
# calculate the maximum move duration accounting for above ;) # calculate the maximum move duration accounting for above ;)
for layer in self.all_layers: for layer in self.all_layers:
for line in layer: for line in layer:
...@@ -400,19 +400,30 @@ class GCode(object): ...@@ -400,19 +400,30 @@ class GCode(object):
else: else:
moveduration /= 1000.0 moveduration /= 1000.0
else: else:
x = line.x if line.x != None else lastx x = line.x if line.x is not None else lastx
y = line.y if line.y != None else lasty y = line.y if line.y is not None else lasty
e = line.e if line.e != None else laste e = line.e if line.e is not None else laste
f = line.f / 60.0 if line.f != None else lastf # mm/s vs mm/m => divide by 60 # mm/s vs mm/m => divide by 60
f = line.f / 60.0 if line.f is not None else lastf
# given last feedrate and current feedrate calculate the distance needed to achieve current feedrate.
# if travel is longer than req'd distance, then subtract distance to achieve full speed, and add the time it took to get there. # given last feedrate and current feedrate calculate the
# then calculate the time taken to complete the remaining distance # distance needed to achieve current feedrate.
# if travel is longer than req'd distance, then subtract
# distance to achieve full speed, and add the time it took
# to get there.
# then calculate the time taken to complete the remaining
# distance
# FIXME: this code has been proven to be super wrong when 2
# subsquent moves are in opposite directions, as requested
# speed is constant but printer has to fully decellerate
# and reaccelerate
currenttravel = math.hypot(x - lastx, y - lasty) currenttravel = math.hypot(x - lastx, y - lasty)
if currenttravel == 0 and line.e != None: if currenttravel == 0 and line.e is not None:
currenttravel = abs(line.e) if line.relative_e else abs(line.e - laste) currenttravel = abs(line.e) if line.relative_e else abs(line.e - laste)
if f == lastf: # Feedrate hasn't changed, no acceleration/decceleration planned # Feedrate hasn't changed, no acceleration/decceleration planned
if f == lastf:
moveduration = currenttravel / f if f != 0 else 0. moveduration = currenttravel / f if f != 0 else 0.
else: else:
# FIXME: review this better # FIXME: review this better
...@@ -437,7 +448,8 @@ class GCode(object): ...@@ -437,7 +448,8 @@ class GCode(object):
layer.duration = totalduration - layerbeginduration layer.duration = totalduration - layerbeginduration
layerbeginduration = totalduration layerbeginduration = totalduration
return "%d layers, %s" % (len(self.layers), str(datetime.timedelta(seconds = int(totalduration)))) totaltime = datetime.timedelta(seconds = int(totalduration))
return "%d layers, %s" % (len(self.layers), str(totaltime))
def main(): def main():
if len(sys.argv) < 2: if len(sys.argv) < 2:
...@@ -448,9 +460,12 @@ def main(): ...@@ -448,9 +460,12 @@ def main():
gcode = GCode(open(sys.argv[1])) gcode = GCode(open(sys.argv[1]))
print "Dimensions:" print "Dimensions:"
print "\tX: %0.02f - %0.02f (%0.02f)" % (gcode.xmin,gcode.xmax,gcode.width) xdims = (gcode.xmin, gcode.xmax, gcode.width)
print "\tY: %0.02f - %0.02f (%0.02f)" % (gcode.ymin,gcode.ymax,gcode.depth) print "\tX: %0.02f - %0.02f (%0.02f)" % xdims
print "\tZ: %0.02f - %0.02f (%0.02f)" % (gcode.zmin,gcode.zmax,gcode.height) ydims = (gcode.ymin, gcode.ymax, gcode.depth)
print "\tY: %0.02f - %0.02f (%0.02f)" % ydims
zdims = (gcode.zmin, gcode.zmax, gcode.height)
print "\tZ: %0.02f - %0.02f (%0.02f)" % zdims
print "Filament used: %0.02fmm" % gcode.filament_length print "Filament used: %0.02fmm" % gcode.filament_length
print "Number of layers: %d" % gcode.num_layers() print "Number of layers: %d" % gcode.num_layers()
print "Estimated duration: %s" % gcode.estimate_duration() print "Estimated duration: %s" % gcode.estimate_duration()
......
...@@ -15,23 +15,17 @@ ...@@ -15,23 +15,17 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with Printrun. If not, see <http://www.gnu.org/licenses/>. # along with Printrun. If not, see <http://www.gnu.org/licenses/>.
import os
import math
import wx import wx
from wx import glcanvas
import pyglet
pyglet.options['debug_gl'] = True
from pyglet.gl import *
from pyglet import gl
from . import gcoder from . import gcoder
from .gl.panel import wxGLPanel from .gl.panel import wxGLPanel
from .gl.trackball import trackball, mulquat, build_rotmatrix from .gl.trackball import trackball, mulquat, build_rotmatrix
from .gl.libtatlin import actors from .gl.libtatlin import actors
from pyglet.gl import glPushMatrix, glPopMatrix, \
glTranslatef, glRotatef, glScalef, glMultMatrixd
from .gviz import GvizBaseFrame from .gviz import GvizBaseFrame
from printrun_utils import imagefile, install_locale from printrun_utils import imagefile, install_locale
...@@ -39,9 +33,10 @@ install_locale('pronterface') ...@@ -39,9 +33,10 @@ install_locale('pronterface')
class GcodeViewPanel(wxGLPanel): class GcodeViewPanel(wxGLPanel):
def __init__(self, parent, id = wx.ID_ANY, build_dimensions = None, realparent = None): def __init__(self, parent, id = wx.ID_ANY,
super(GcodeViewPanel, self).__init__(parent, id, wx.DefaultPosition, wx.DefaultSize, 0) build_dimensions = None, realparent = None):
self.batches = [] super(GcodeViewPanel, self).__init__(parent, id, wx.DefaultPosition,
wx.DefaultSize, 0)
self.canvas.Bind(wx.EVT_MOUSE_EVENTS, self.move) self.canvas.Bind(wx.EVT_MOUSE_EVENTS, self.move)
self.canvas.Bind(wx.EVT_LEFT_DCLICK, self.double) self.canvas.Bind(wx.EVT_LEFT_DCLICK, self.double)
self.canvas.Bind(wx.EVT_KEY_DOWN, self.keypress) self.canvas.Bind(wx.EVT_KEY_DOWN, self.keypress)
...@@ -79,12 +74,17 @@ class GcodeViewPanel(wxGLPanel): ...@@ -79,12 +74,17 @@ class GcodeViewPanel(wxGLPanel):
glTranslatef(0, 0, -3 * self.dist) # Move back glTranslatef(0, 0, -3 * self.dist) # Move back
else: else:
glTranslatef(0, 0, -self.dist) # Move back glTranslatef(0, 0, -self.dist) # Move back
glMultMatrixd(build_rotmatrix(self.basequat)) # Rotate according to trackball # Rotate according to trackball
glTranslatef(- self.build_dimensions[3] - self.parent.platform.width/2, glMultMatrixd(build_rotmatrix(self.basequat))
- self.build_dimensions[4] - self.parent.platform.depth/2, 0) # Move origin to bottom left of platform # Move origin to bottom left of platform
platformx0 = -self.build_dimensions[3] - self.parent.platform.width / 2
platformy0 = -self.build_dimensions[4] - self.parent.platform.depth / 2
glTranslatef(platformx0, platformy0, 0)
for obj in self.parent.objects: for obj in self.parent.objects:
if not obj.model or not obj.model.loaded or not obj.model.initialized: if not obj.model \
or not obj.model.loaded \
or not obj.model.initialized:
continue continue
glPushMatrix() glPushMatrix()
glTranslatef(*(obj.offsets)) glTranslatef(*(obj.offsets))
...@@ -100,7 +100,7 @@ class GcodeViewPanel(wxGLPanel): ...@@ -100,7 +100,7 @@ class GcodeViewPanel(wxGLPanel):
self.parent.clickcb(event) self.parent.clickcb(event)
def handle_rotation(self, event): def handle_rotation(self, event):
if self.initpos == None: if self.initpos is None:
self.initpos = event.GetPositionTuple() self.initpos = event.GetPositionTuple()
else: else:
p1 = self.initpos p1 = self.initpos
...@@ -194,7 +194,7 @@ class GcodeViewPanel(wxGLPanel): ...@@ -194,7 +194,7 @@ class GcodeViewPanel(wxGLPanel):
if delta > 0: if delta > 0:
self.zoom(factor, (x, y)) self.zoom(factor, (x, y))
else: else:
self.zoom(1/factor, (x, y)) self.zoom(1 / factor, (x, y))
def fit(self): def fit(self):
if not self.parent.model or not self.parent.model.loaded: if not self.parent.model or not self.parent.model.loaded:
...@@ -257,13 +257,13 @@ class GCObject(object): ...@@ -257,13 +257,13 @@ class GCObject(object):
self.rot = 0 self.rot = 0
self.curlayer = 0.0 self.curlayer = 0.0
self.scale = [1.0, 1.0, 1.0] self.scale = [1.0, 1.0, 1.0]
self.batch = pyglet.graphics.Batch()
self.model = model self.model = model
class GcodeViewMainWrapper(object): class GcodeViewMainWrapper(object):
def __init__(self, parent, build_dimensions): def __init__(self, parent, build_dimensions):
self.glpanel = GcodeViewPanel(parent, realparent = self, build_dimensions = build_dimensions) self.glpanel = GcodeViewPanel(parent, realparent = self,
build_dimensions = build_dimensions)
self.glpanel.SetMinSize((150, 150)) self.glpanel.SetMinSize((150, 150))
self.clickcb = None self.clickcb = None
self.widget = self.glpanel self.widget = self.glpanel
...@@ -306,7 +306,8 @@ class GcodeViewFrame(GvizBaseFrame): ...@@ -306,7 +306,8 @@ class GcodeViewFrame(GvizBaseFrame):
def __init__(self, parent, ID, title, build_dimensions, objects = None, def __init__(self, parent, ID, title, build_dimensions, objects = None,
pos = wx.DefaultPosition, size = wx.DefaultSize, pos = wx.DefaultPosition, size = wx.DefaultSize,
style = wx.DEFAULT_FRAME_STYLE): style = wx.DEFAULT_FRAME_STYLE):
super(GcodeViewFrame, self).__init__(parent, ID, title, pos, size, style) super(GcodeViewFrame, self).__init__(parent, ID, title,
pos, size, style)
panel, vbox = self.create_base_ui() panel, vbox = self.create_base_ui()
...@@ -320,14 +321,18 @@ class GcodeViewFrame(GvizBaseFrame): ...@@ -320,14 +321,18 @@ class GcodeViewFrame(GvizBaseFrame):
self.model = None self.model = None
self.objects = [GCObject(self.platform), GCObject(None)] self.objects = [GCObject(self.platform), GCObject(None)]
self.toolbar.AddLabelTool(6, " " + _("Fit to plate"), wx.Image(imagefile('fit.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap(), shortHelp = _("Fit to plate [F]"), longHelp = '') fit_image = wx.Image(imagefile('fit.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap()
self.toolbar.AddLabelTool(6, " " + _("Fit to plate"), fit_image,
shortHelp = _("Fit to plate [F]"),
longHelp = '')
self.toolbar.Realize() self.toolbar.Realize()
self.glpanel = GcodeViewPanel(panel, build_dimensions = build_dimensions, self.glpanel = GcodeViewPanel(panel,
build_dimensions = build_dimensions,
realparent = self) realparent = self)
vbox.Add(self.glpanel, 1, flag = wx.EXPAND) vbox.Add(self.glpanel, 1, flag = wx.EXPAND)
self.Bind(wx.EVT_TOOL, lambda x: self.glpanel.zoom_to_center(1.2), id = 1) self.Bind(wx.EVT_TOOL, lambda x: self.glpanel.zoom_to_center(1.2), id = 1)
self.Bind(wx.EVT_TOOL, lambda x: self.glpanel.zoom_to_center(1/1.2), id = 2) self.Bind(wx.EVT_TOOL, lambda x: self.glpanel.zoom_to_center(1 / 1.2), id = 2)
self.Bind(wx.EVT_TOOL, lambda x: self.glpanel.layerup(), id = 3) self.Bind(wx.EVT_TOOL, lambda x: self.glpanel.layerup(), id = 3)
self.Bind(wx.EVT_TOOL, lambda x: self.glpanel.layerdown(), id = 4) self.Bind(wx.EVT_TOOL, lambda x: self.glpanel.layerdown(), id = 4)
self.Bind(wx.EVT_TOOL, lambda x: self.glpanel.resetview(), id = 5) self.Bind(wx.EVT_TOOL, lambda x: self.glpanel.resetview(), id = 5)
...@@ -367,7 +372,9 @@ if __name__ == "__main__": ...@@ -367,7 +372,9 @@ if __name__ == "__main__":
import sys import sys
app = wx.App(redirect = False) app = wx.App(redirect = False)
build_dimensions = [200, 200, 100, 0, 0, 0] build_dimensions = [200, 200, 100, 0, 0, 0]
frame = GcodeViewFrame(None, wx.ID_ANY, 'Gcode view, shift to move view, mousewheel to set layer', size = (400, 400), build_dimensions = build_dimensions) title = 'Gcode view, shift to move view, mousewheel to set layer'
frame = GcodeViewFrame(None, wx.ID_ANY, title, size = (400, 400),
build_dimensions = build_dimensions)
gcode = gcoder.GCode(open(sys.argv[1])) gcode = gcoder.GCode(open(sys.argv[1]))
frame.addfile(gcode) frame.addfile(gcode)
...@@ -377,14 +384,15 @@ if __name__ == "__main__": ...@@ -377,14 +384,15 @@ if __name__ == "__main__":
first_move = gcode.lines[i] first_move = gcode.lines[i]
break break
last_move = None last_move = None
for i in range(len(gcode.lines)-1,-1,-1): for i in range(len(gcode.lines) - 1, -1, -1):
if gcode.lines[i].is_move: if gcode.lines[i].is_move:
last_move = gcode.lines[i] last_move = gcode.lines[i]
break break
nsteps = 20 nsteps = 20
steptime = 500 steptime = 500
lines = [first_move] + [gcode.lines[int(float(i)*(len(gcode.lines)-1)/nsteps)] for i in range(1, nsteps)] + [last_move] lines = [first_move] + [gcode.lines[int(float(i) * (len(gcode.lines) - 1) / nsteps)] for i in range(1, nsteps)] + [last_move]
current_line = 0 current_line = 0
def setLine(): def setLine():
global current_line global current_line
frame.set_current_gline(lines[current_line]) frame.set_current_gline(lines[current_line])
......
...@@ -21,8 +21,13 @@ import numpy ...@@ -21,8 +21,13 @@ import numpy
import math import math
import logging import logging
from pyglet.gl import * from pyglet.gl import glPushMatrix, glPopMatrix, glTranslatef, \
from pyglet import gl glGenLists, glNewList, GL_COMPILE, glEndList, glCallList, \
GL_ARRAY_BUFFER, GL_STATIC_DRAW, glColor4f, glVertex3f, glRectf, \
glBegin, glEnd, GL_LINES, glEnable, glDisable, glGetFloatv, \
GL_LINE_SMOOTH, glLineWidth, GL_LINE_WIDTH, GLfloat, GL_FLOAT, \
glVertexPointer, glColorPointer, glDrawArrays, \
glEnableClientState, glDisableClientState, GL_VERTEX_ARRAY, GL_COLOR_ARRAY
from pyglet.graphics.vertexbuffer import create_buffer, VertexBufferObject from pyglet.graphics.vertexbuffer import create_buffer, VertexBufferObject
from printrun.printrun_utils import install_locale from printrun.printrun_utils import install_locale
...@@ -253,14 +258,13 @@ class GcodeModel(Model): ...@@ -253,14 +258,13 @@ class GcodeModel(Model):
def load_data(self, model_data, callback=None): def load_data(self, model_data, callback=None):
t_start = time.time() t_start = time.time()
self.dims = ((model_data.xmin,model_data.xmax,model_data.width), self.dims = ((model_data.xmin, model_data.xmax, model_data.width),
(model_data.ymin,model_data.ymax,model_data.depth), (model_data.ymin, model_data.ymax, model_data.depth),
(model_data.zmin,model_data.zmax,model_data.height)) (model_data.zmin, model_data.zmax, model_data.height))
vertex_list = [] vertex_list = []
color_list = [] color_list = []
self.layer_stops = [0] self.layer_stops = [0]
arrow_list = []
num_layers = len(model_data.all_layers) num_layers = len(model_data.all_layers)
prev_pos = (0, 0, 0) prev_pos = (0, 0, 0)
...@@ -413,4 +417,3 @@ class GcodeModel(Model): ...@@ -413,4 +417,3 @@ class GcodeModel(Model):
self.vertex_buffer.unbind() self.vertex_buffer.unbind()
self.vertex_color_buffer.unbind() self.vertex_color_buffer.unbind()
...@@ -15,9 +15,6 @@ ...@@ -15,9 +15,6 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with Printrun. If not, see <http://www.gnu.org/licenses/>. # along with Printrun. If not, see <http://www.gnu.org/licenses/>.
import os
import math
import wx import wx
from wx import glcanvas from wx import glcanvas
...@@ -64,7 +61,7 @@ class wxGLPanel(wx.Panel): ...@@ -64,7 +61,7 @@ class wxGLPanel(wx.Panel):
def processSizeEvent(self, event): def processSizeEvent(self, event):
'''Process the resize event.''' '''Process the resize event.'''
if (wx.VERSION > (2,9) and self.canvas.IsShownOnScreen()) or self.canvas.GetContext(): if (wx.VERSION > (2, 9) and self.canvas.IsShownOnScreen()) or self.canvas.GetContext():
# Make sure the frame is shown before calling SetCurrent. # Make sure the frame is shown before calling SetCurrent.
self.canvas.SetCurrent(self.context) self.canvas.SetCurrent(self.context)
self.OnReshape() self.OnReshape()
...@@ -110,7 +107,7 @@ class wxGLPanel(wx.Panel): ...@@ -110,7 +107,7 @@ class wxGLPanel(wx.Panel):
self.OnReshape() self.OnReshape()
def OnReshape(self): def OnReshape(self):
'''Reshape the OpenGL viewport based on the dimensions of the window.''' """Reshape the OpenGL viewport based on the size of the window"""
size = self.GetClientSize() size = self.GetClientSize()
oldwidth, oldheight = self.width, self.height oldwidth, oldheight = self.width, self.height
width, height = size.width, size.height width, height = size.width, size.height
...@@ -174,7 +171,8 @@ class wxGLPanel(wx.Panel): ...@@ -174,7 +171,8 @@ class wxGLPanel(wx.Panel):
def mouse_to_3d(self, x, y, z = 1.0): def mouse_to_3d(self, x, y, z = 1.0):
x = float(x) x = float(x)
y = self.height - float(y) y = self.height - float(y)
# The following could work if we were not initially scaling to zoom on the bed # The following could work if we were not initially scaling to zoom on
# the bed
#if self.orthographic: #if self.orthographic:
# return (x - self.width / 2, y - self.height / 2, 0) # return (x - self.width / 2, y - self.height / 2, 0)
pmat = (GLdouble * 16)() pmat = (GLdouble * 16)()
...@@ -183,7 +181,7 @@ class wxGLPanel(wx.Panel): ...@@ -183,7 +181,7 @@ class wxGLPanel(wx.Panel):
px = (GLdouble)() px = (GLdouble)()
py = (GLdouble)() py = (GLdouble)()
pz = (GLdouble)() pz = (GLdouble)()
glGetIntegerv(GL_VIEWPORT, viewport); glGetIntegerv(GL_VIEWPORT, viewport)
glGetDoublev(GL_PROJECTION_MATRIX, pmat) glGetDoublev(GL_PROJECTION_MATRIX, pmat)
glGetDoublev(GL_MODELVIEW_MATRIX, mvmat) glGetDoublev(GL_MODELVIEW_MATRIX, mvmat)
gluUnProject(x, y, z, mvmat, pmat, viewport, px, py, pz) gluUnProject(x, y, z, mvmat, pmat, viewport, px, py, pz)
......
...@@ -17,10 +17,12 @@ ...@@ -17,10 +17,12 @@
import math import math
from pyglet.gl import * from pyglet.gl import GLdouble
def cross(v1, v2): def cross(v1, v2):
return [v1[1]*v2[2]-v1[2]*v2[1], v1[2]*v2[0]-v1[0]*v2[2], v1[0]*v2[1]-v1[1]*v2[0]] return [v1[1] * v2[2] - v1[2] * v2[1],
v1[2] * v2[0] - v1[0] * v2[2],
v1[0] * v2[1] - v1[1] * v2[0]]
def trackball(p1x, p1y, p2x, p2y, r): def trackball(p1x, p1y, p2x, p2y, r):
TRACKBALLSIZE = r TRACKBALLSIZE = r
......
This diff is collapsed.
This diff is collapsed.
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
from Queue import Queue from Queue import Queue
from collections import deque from collections import deque
import wx, time import wx
from printrun import gcoder from printrun import gcoder
from printrun_utils import imagefile, install_locale from printrun_utils import imagefile, install_locale
...@@ -76,10 +76,10 @@ class GvizWindow(GvizBaseFrame): ...@@ -76,10 +76,10 @@ class GvizWindow(GvizBaseFrame):
vbox.Add(self.p, 1, wx.EXPAND) vbox.Add(self.p, 1, wx.EXPAND)
self.SetMinSize(self.ClientToWindowSize(vbox.GetMinSize())) self.SetMinSize(self.ClientToWindowSize(vbox.GetMinSize()))
self.Bind(wx.EVT_TOOL, lambda x:self.p.zoom(-1, -1, 1.2), id = 1) self.Bind(wx.EVT_TOOL, lambda x: self.p.zoom(-1, -1, 1.2), id = 1)
self.Bind(wx.EVT_TOOL, lambda x:self.p.zoom(-1, -1, 1/1.2), id = 2) self.Bind(wx.EVT_TOOL, lambda x: self.p.zoom(-1, -1, 1 / 1.2), id = 2)
self.Bind(wx.EVT_TOOL, lambda x:self.p.layerup(), id = 3) self.Bind(wx.EVT_TOOL, lambda x: self.p.layerup(), id = 3)
self.Bind(wx.EVT_TOOL, lambda x:self.p.layerdown(), id = 4) self.Bind(wx.EVT_TOOL, lambda x: self.p.layerdown(), id = 4)
self.Bind(wx.EVT_TOOL, self.resetview, id = 5) self.Bind(wx.EVT_TOOL, self.resetview, id = 5)
#self.Bind(wx.EVT_TOOL, lambda x:self.p.inject(), id = 6) #self.Bind(wx.EVT_TOOL, lambda x:self.p.inject(), id = 6)
...@@ -140,7 +140,7 @@ class GvizWindow(GvizBaseFrame): ...@@ -140,7 +140,7 @@ class GvizWindow(GvizBaseFrame):
if x in kzi: if x in kzi:
self.p.zoom(cx, cy, 1.2) self.p.zoom(cx, cy, 1.2)
if x in kzo: if x in kzo:
self.p.zoom(cx, cy, 1/1.2) self.p.zoom(cx, cy, 1 / 1.2)
def zoom(self, event): def zoom(self, event):
z = event.GetWheelRotation() z = event.GetWheelRotation()
...@@ -149,14 +149,16 @@ class GvizWindow(GvizBaseFrame): ...@@ -149,14 +149,16 @@ class GvizWindow(GvizBaseFrame):
elif z < 0: self.p.layerup() elif z < 0: self.p.layerup()
else: else:
if z > 0: self.p.zoom(event.GetX(), event.GetY(), 1.2) if z > 0: self.p.zoom(event.GetX(), event.GetY(), 1.2)
elif z < 0: self.p.zoom(event.GetX(), event.GetY(), 1/1.2) elif z < 0: self.p.zoom(event.GetX(), event.GetY(), 1 / 1.2)
class Gviz(wx.Panel): class Gviz(wx.Panel):
# Mark canvas as dirty when setting showall # Mark canvas as dirty when setting showall
_showall = 0 _showall = 0
def _get_showall(self): def _get_showall(self):
return self._showall return self._showall
def _set_showall(self, showall): def _set_showall(self, showall):
if showall != self._showall: if showall != self._showall:
self.dirty = 1 self.dirty = 1
...@@ -168,7 +170,7 @@ class Gviz(wx.Panel): ...@@ -168,7 +170,7 @@ class Gviz(wx.Panel):
self.widget = self self.widget = self
size = [max(1.0, x) for x in size] size = [max(1.0, x) for x in size]
ratio = size[0] / size[1] ratio = size[0] / size[1]
self.SetMinSize((150, 150/ratio)) self.SetMinSize((150, 150 / ratio))
self.parent = realparent if realparent else parent self.parent = realparent if realparent else parent
self.size = size self.size = size
self.build_dimensions = build_dimensions self.build_dimensions = build_dimensions
...@@ -186,14 +188,14 @@ class Gviz(wx.Panel): ...@@ -186,14 +188,14 @@ class Gviz(wx.Panel):
self.filament_width = extrusion_width # set it to 0 to disable scaling lines with zoom self.filament_width = extrusion_width # set it to 0 to disable scaling lines with zoom
self.update_basescale() self.update_basescale()
self.scale = self.basescale self.scale = self.basescale
penwidth = max(1.0, self.filament_width*((self.scale[0]+self.scale[1])/2.0)) penwidth = max(1.0, self.filament_width * ((self.scale[0] + self.scale[1]) / 2.0))
self.translate = [0.0, 0.0] self.translate = [0.0, 0.0]
self.mainpen = wx.Pen(wx.Colour(0, 0, 0), penwidth) self.mainpen = wx.Pen(wx.Colour(0, 0, 0), penwidth)
self.arcpen = wx.Pen(wx.Colour(255, 0, 0), penwidth) self.arcpen = wx.Pen(wx.Colour(255, 0, 0), penwidth)
self.travelpen = wx.Pen(wx.Colour(10, 80, 80), penwidth) self.travelpen = wx.Pen(wx.Colour(10, 80, 80), penwidth)
self.hlpen = wx.Pen(wx.Colour(200, 50, 50), penwidth) self.hlpen = wx.Pen(wx.Colour(200, 50, 50), penwidth)
self.fades = [wx.Pen(wx.Colour(250-0.6**i*100, 250-0.6**i*100, 200-0.4**i*50), penwidth) for i in xrange(6)] self.fades = [wx.Pen(wx.Colour(250 - 0.6 ** i * 100, 250 - 0.6 ** i * 100, 200 - 0.4 ** i * 50), penwidth) for i in xrange(6)]
self.penslist = [self.mainpen, self.travelpen, self.hlpen]+self.fades self.penslist = [self.mainpen, self.travelpen, self.hlpen] + self.fades
self.showall = 0 self.showall = 0
self.hilight = deque() self.hilight = deque()
self.hilightarcs = deque() self.hilightarcs = deque()
...@@ -207,8 +209,8 @@ class Gviz(wx.Panel): ...@@ -207,8 +209,8 @@ class Gviz(wx.Panel):
def inject(self): def inject(self):
#import pdb; pdb.set_trace() #import pdb; pdb.set_trace()
print"Inject code here..." print "Inject code here..."
print "Layer "+str(self.layerindex +1)+" - Z = "+str(self.layers[self.layerindex])+" mm" print "Layer " + str(self.layerindex + 1) + " - Z = " + str(self.layers[self.layerindex]) + " mm"
def clearhilights(self): def clearhilights(self):
self.hilight.clear() self.hilight.clear()
...@@ -255,8 +257,8 @@ class Gviz(wx.Panel): ...@@ -255,8 +257,8 @@ class Gviz(wx.Panel):
wx.CallAfter(self.Refresh) wx.CallAfter(self.Refresh)
def update_basescale(self): def update_basescale(self):
self.basescale = 2*[min(float(self.size[0] - 1)/self.build_dimensions[0], self.basescale = 2 * [min(float(self.size[0] - 1) / self.build_dimensions[0],
float(self.size[1] - 1)/self.build_dimensions[1])] float(self.size[1] - 1) / self.build_dimensions[1])]
def resize(self, event): def resize(self, event):
old_basescale = self.basescale old_basescale = self.basescale
...@@ -273,25 +275,25 @@ class Gviz(wx.Panel): ...@@ -273,25 +275,25 @@ class Gviz(wx.Panel):
self.translate = [x - (x - self.translate[0]) * factor, self.translate = [x - (x - self.translate[0]) * factor,
y - (y - self.translate[1]) * factor] y - (y - self.translate[1]) * factor]
penwidth = max(1.0, self.filament_width*((self.scale[0]+self.scale[1])/2.0)) penwidth = max(1.0, self.filament_width * ((self.scale[0] + self.scale[1]) / 2.0))
for pen in self.penslist: for pen in self.penslist:
pen.SetWidth(penwidth) pen.SetWidth(penwidth)
self.dirty = 1 self.dirty = 1
wx.CallAfter(self.Refresh) wx.CallAfter(self.Refresh)
def _line_scaler(self, x): def _line_scaler(self, x):
return (self.scale[0]*x[0], return (self.scale[0] * x[0],
self.scale[1]*x[1], self.scale[1] * x[1],
self.scale[0]*x[2], self.scale[0] * x[2],
self.scale[1]*x[3],) self.scale[1] * x[3],)
def _arc_scaler(self, x): def _arc_scaler(self, x):
return (self.scale[0]*x[0], return (self.scale[0] * x[0],
self.scale[1]*x[1], self.scale[1] * x[1],
self.scale[0]*x[2], self.scale[0] * x[2],
self.scale[1]*x[3], self.scale[1] * x[3],
self.scale[0]*x[4], self.scale[0] * x[4],
self.scale[1]*x[5],) self.scale[1] * x[5],)
def _drawlines(self, dc, lines, pens): def _drawlines(self, dc, lines, pens):
scaled_lines = map(self._line_scaler, lines) scaled_lines = map(self._line_scaler, lines)
...@@ -305,8 +307,8 @@ class Gviz(wx.Panel): ...@@ -305,8 +307,8 @@ class Gviz(wx.Panel):
dc.DrawArc(*scaled_arcs[i]) dc.DrawArc(*scaled_arcs[i])
def repaint_everything(self): def repaint_everything(self):
width = self.scale[0]*self.build_dimensions[0] width = self.scale[0] * self.build_dimensions[0]
height = self.scale[1]*self.build_dimensions[1] height = self.scale[1] * self.build_dimensions[1]
self.blitmap = wx.EmptyBitmap(width + 1, height + 1, -1) self.blitmap = wx.EmptyBitmap(width + 1, height + 1, -1)
dc = wx.MemoryDC() dc = wx.MemoryDC()
dc.SelectObject(self.blitmap) dc.SelectObject(self.blitmap)
...@@ -315,21 +317,21 @@ class Gviz(wx.Panel): ...@@ -315,21 +317,21 @@ class Gviz(wx.Panel):
dc.SetPen(wx.Pen(wx.Colour(180, 180, 150))) dc.SetPen(wx.Pen(wx.Colour(180, 180, 150)))
for grid_unit in self.grid: for grid_unit in self.grid:
if grid_unit > 0: if grid_unit > 0:
for x in xrange(int(self.build_dimensions[0]/grid_unit)+1): for x in xrange(int(self.build_dimensions[0] / grid_unit) + 1):
draw_x = self.scale[0]*x*grid_unit draw_x = self.scale[0] * x * grid_unit
dc.DrawLine(draw_x, 0, draw_x, height) dc.DrawLine(draw_x, 0, draw_x, height)
for y in xrange(int(self.build_dimensions[1]/grid_unit)+1): for y in xrange(int(self.build_dimensions[1] / grid_unit) + 1):
draw_y = self.scale[1]*(self.build_dimensions[1]-y*grid_unit) draw_y = self.scale[1] * (self.build_dimensions[1] - y * grid_unit)
dc.DrawLine(0, draw_y, width, draw_y) dc.DrawLine(0, draw_y, width, draw_y)
dc.SetPen(wx.Pen(wx.Colour(0, 0, 0))) dc.SetPen(wx.Pen(wx.Colour(0, 0, 0)))
if not self.showall: if not self.showall:
# Draw layer gauge # Draw layer gauge
dc.SetBrush(wx.Brush((43, 144, 255))) dc.SetBrush(wx.Brush((43, 144, 255)))
dc.DrawRectangle(width-15, 0, 15, height) dc.DrawRectangle(width - 15, 0, 15, height)
dc.SetBrush(wx.Brush((0, 255, 0))) dc.SetBrush(wx.Brush((0, 255, 0)))
if self.layers: if self.layers:
dc.DrawRectangle(width-14, (1.0-(1.0*(self.layerindex+1))/len(self.layers))*height, 13, height-1) dc.DrawRectangle(width - 14, (1.0 - (1.0 * (self.layerindex + 1)) / len(self.layers)) * height, 13, height - 1)
if self.showall: if self.showall:
for i in self.layers: for i in self.layers:
...@@ -393,6 +395,7 @@ class Gviz(wx.Panel): ...@@ -393,6 +395,7 @@ class Gviz(wx.Panel):
def add_parsed_gcodes(self, gcode): def add_parsed_gcodes(self, gcode):
def _y(y): def _y(y):
return self.build_dimensions[1] - (y - self.build_dimensions[4]) return self.build_dimensions[1] - (y - self.build_dimensions[4])
def _x(x): def _x(x):
return x - self.build_dimensions[3] return x - self.build_dimensions[3]
...@@ -419,14 +422,14 @@ class Gviz(wx.Panel): ...@@ -419,14 +422,14 @@ class Gviz(wx.Panel):
target[2] = gline.current_z target[2] = gline.current_z
target[5] = 0.0 target[5] = 0.0
target[6] = 0.0 target[6] = 0.0
if gline.e != None: if gline.e is not None:
if gline.relative_e: if gline.relative_e:
target[3] += gline.e target[3] += gline.e
else: else:
target[3] = gline.e target[3] = gline.e
if gline.f != None: target[4] = gline.f if gline.f is not None: target[4] = gline.f
if gline.i != None: target[5] = gline.i if gline.i is not None: target[5] = gline.i
if gline.j != None: target[6] = gline.j if gline.j is not None: target[6] = gline.j
start_pos = self.lastpos[:] start_pos = self.lastpos[:]
...@@ -460,6 +463,7 @@ class Gviz(wx.Panel): ...@@ -460,6 +463,7 @@ class Gviz(wx.Panel):
def _y(y): def _y(y):
return self.build_dimensions[1] - (y - self.build_dimensions[4]) return self.build_dimensions[1] - (y - self.build_dimensions[4])
def _x(x): def _x(x):
return x - self.build_dimensions[3] return x - self.build_dimensions[3]
...@@ -471,13 +475,13 @@ class Gviz(wx.Panel): ...@@ -471,13 +475,13 @@ class Gviz(wx.Panel):
target = start_pos[:] target = start_pos[:]
target[5] = 0.0 target[5] = 0.0
target[6] = 0.0 target[6] = 0.0
if gline.x != None: target[0] = gline.x if gline.x is not None: target[0] = gline.x
if gline.y != None: target[1] = gline.y if gline.y is not None: target[1] = gline.y
if gline.z != None: target[2] = gline.z if gline.z is not None: target[2] = gline.z
if gline.e != None: target[3] = gline.e if gline.e is not None: target[3] = gline.e
if gline.f != None: target[4] = gline.f if gline.f is not None: target[4] = gline.f
if gline.i != None: target[5] = gline.i if gline.i is not None: target[5] = gline.i
if gline.j != None: target[6] = gline.j if gline.j is not None: target[6] = gline.j
z = target[2] z = target[2]
if not hilight and z not in self.layers: if not hilight and z not in self.layers:
......
...@@ -13,25 +13,30 @@ ...@@ -13,25 +13,30 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with Printrun. If not, see <http://www.gnu.org/licenses/>. # along with Printrun. If not, see <http://www.gnu.org/licenses/>.
import os, sys import os
import sys
import gettext import gettext
# Set up Internationalization using gettext # Set up Internationalization using gettext
# searching for installed locales on /usr/share; uses relative folder if not found (windows) # searching for installed locales on /usr/share; uses relative folder if not
# found (windows)
def install_locale(domain): def install_locale(domain):
if os.path.exists('/usr/share/pronterface/locale'): if os.path.exists('/usr/share/pronterface/locale'):
gettext.install(domain, '/usr/share/pronterface/locale', unicode = 1) gettext.install(domain, '/usr/share/pronterface/locale', unicode = 1)
elif os.path.exists('/usr/local/share/pronterface/locale'): elif os.path.exists('/usr/local/share/pronterface/locale'):
gettext.install(domain, '/usr/local/share/pronterface/locale', unicode = 1) gettext.install(domain, '/usr/local/share/pronterface/locale',
unicode = 1)
else: else:
gettext.install(domain, './locale', unicode = 1) gettext.install(domain, './locale', unicode = 1)
def imagefile(filename): def imagefile(filename):
for prefix in ['/usr/local/share/pronterface/images', '/usr/share/pronterface/images']: for prefix in ['/usr/local/share/pronterface/images',
'/usr/share/pronterface/images']:
candidate = os.path.join(prefix, filename) candidate = os.path.join(prefix, filename)
if os.path.exists(candidate): if os.path.exists(candidate):
return candidate return candidate
local_candidate = os.path.join(os.path.dirname(sys.argv[0]), "images", filename) local_candidate = os.path.join(os.path.dirname(sys.argv[0]),
"images", filename)
if os.path.exists(local_candidate): if os.path.exists(local_candidate):
return local_candidate return local_candidate
else: else:
...@@ -49,13 +54,15 @@ def lookup_file(filename, prefixes): ...@@ -49,13 +54,15 @@ def lookup_file(filename, prefixes):
return filename return filename
def pixmapfile(filename): def pixmapfile(filename):
return lookup_file(filename, ['/usr/local/share/pixmaps', '/usr/share/pixmaps']) return lookup_file(filename, ['/usr/local/share/pixmaps',
'/usr/share/pixmaps'])
def sharedfile(filename): def sharedfile(filename):
return lookup_file(filename, ['/usr/local/share/pronterface', '/usr/share/pronterface']) return lookup_file(filename, ['/usr/local/share/pronterface',
'/usr/share/pronterface'])
def configfile(filename): def configfile(filename):
return lookup_file(filename, [os.path.expanduser("~/.printrun/"),]) return lookup_file(filename, [os.path.expanduser("~/.printrun/"), ])
class RemainingTimeEstimator(object): class RemainingTimeEstimator(object):
...@@ -88,7 +95,7 @@ class RemainingTimeEstimator(object): ...@@ -88,7 +95,7 @@ class RemainingTimeEstimator(object):
if idx == self.last_idx: if idx == self.last_idx:
return self.last_estimate return self.last_estimate
layer, line = self.gcode.idxs(idx) layer, line = self.gcode.idxs(idx)
layer_progress = (1 - (float(line+1) / self.current_layer_lines)) layer_progress = (1 - (float(line + 1) / self.current_layer_lines))
remaining = layer_progress * self.current_layer_estimate + self.remaining_layers_estimate remaining = layer_progress * self.current_layer_estimate + self.remaining_layers_estimate
estimate = self.drift * remaining estimate = self.drift * remaining
total = estimate + printtime total = estimate + printtime
......
This diff is collapsed.
...@@ -13,19 +13,21 @@ ...@@ -13,19 +13,21 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with Printrun. If not, see <http://www.gnu.org/licenses/>. # along with Printrun. If not, see <http://www.gnu.org/licenses/>.
import sys, struct, math import sys
import struct
import math
def cross(v1, v2): def cross(v1, v2):
return [v1[1]*v2[2]-v1[2]*v2[1], v1[2]*v2[0]-v1[0]*v2[2], v1[0]*v2[1]-v1[1]*v2[0]] return [v1[1] * v2[2] - v1[2] * v2[1], v1[2] * v2[0] - v1[0] * v2[2], v1[0] * v2[1] - v1[1] * v2[0]]
def genfacet(v): def genfacet(v):
veca = [v[1][0]-v[0][0], v[1][1]-v[0][1], v[1][2]-v[0][2]] veca = [v[1][0] - v[0][0], v[1][1] - v[0][1], v[1][2] - v[0][2]]
vecb = [v[2][0]-v[1][0], v[2][1]-v[1][1], v[2][2]-v[1][2]] vecb = [v[2][0] - v[1][0], v[2][1] - v[1][1], v[2][2] - v[1][2]]
vecx = cross(veca, vecb) vecx = cross(veca, vecb)
vlen = math.sqrt(sum(map(lambda x:x*x, vecx))) vlen = math.sqrt(sum(map(lambda x: x * x, vecx)))
if vlen == 0: if vlen == 0:
vlen = 1 vlen = 1
normal = map(lambda x:x/vlen, vecx) normal = map(lambda x: x / vlen, vecx)
return [normal, v] return [normal, v]
I = [ I = [
...@@ -40,14 +42,14 @@ def transpose(matrix): ...@@ -40,14 +42,14 @@ def transpose(matrix):
#return [[v[i] for v in matrix] for i in xrange(len(matrix[0]))] #return [[v[i] for v in matrix] for i in xrange(len(matrix[0]))]
def multmatrix(vector, matrix): def multmatrix(vector, matrix):
return map(sum, transpose(map(lambda x:[x[0]*p for p in x[1]], zip(vector, transpose(matrix))))) return map(sum, transpose(map(lambda x: [x[0] * p for p in x[1]], zip(vector, transpose(matrix)))))
def applymatrix(facet, matrix = I): def applymatrix(facet, matrix = I):
#return facet #return facet
#return [map(lambda x:-1.0*x, multmatrix(facet[0]+[1], matrix)[:3]), map(lambda x:multmatrix(x+[1], matrix)[:3], facet[1])] #return [map(lambda x:-1.0*x, multmatrix(facet[0]+[1], matrix)[:3]), map(lambda x:multmatrix(x+[1], matrix)[:3], facet[1])]
return genfacet(map(lambda x:multmatrix(x+[1], matrix)[:3], facet[1])) return genfacet(map(lambda x: multmatrix(x + [1], matrix)[:3], facet[1]))
f = [[0, 0, 0],[[-3.022642, 0.642482, -9.510565],[-3.022642, 0.642482, -9.510565],[-3.022642, 0.642482, -9.510565]]] f = [[0, 0, 0], [[-3.022642, 0.642482, -9.510565], [-3.022642, 0.642482, -9.510565], [-3.022642, 0.642482, -9.510565]]]
m = [ m = [
[1, 0, 0, 0], [1, 0, 0, 0],
[0, 1, 0, 0], [0, 1, 0, 0],
...@@ -60,37 +62,35 @@ def emitstl(filename, facets = [], objname = "stltool_export", binary = 1): ...@@ -60,37 +62,35 @@ def emitstl(filename, facets = [], objname = "stltool_export", binary = 1):
return return
if binary: if binary:
f = open(filename, "wb") f = open(filename, "wb")
buf = "".join(["\0"]*80) buf = "".join(["\0"] * 80)
buf+=struct.pack("<I", len(facets)) buf += struct.pack("<I", len(facets))
facetformat = struct.Struct("<ffffffffffffH") facetformat = struct.Struct("<ffffffffffffH")
for i in facets: for i in facets:
l = list(i[0][:]) l = list(i[0][:])
for j in i[1]: for j in i[1]:
l+=j[:] l += j[:]
l+=[0] l += [0]
#print len(l) #print len(l)
buf+=facetformat.pack(*l) buf += facetformat.pack(*l)
f.write(buf) f.write(buf)
f.close() f.close()
return return
f = open(filename, "w") f = open(filename, "w")
f.write("solid "+objname+"\n") f.write("solid " + objname + "\n")
for i in facets: for i in facets:
f.write(" facet normal "+" ".join(map(str, i[0]))+"\n outer loop\n") f.write(" facet normal " + " ".join(map(str, i[0])) + "\n outer loop\n")
for j in i[1]: for j in i[1]:
f.write(" vertex "+" ".join(map(str, j))+"\n") f.write(" vertex " + " ".join(map(str, j)) + "\n")
f.write(" endloop"+"\n") f.write(" endloop" + "\n")
f.write(" endfacet"+"\n") f.write(" endfacet" + "\n")
f.write("endsolid "+objname+"\n") f.write("endsolid " + objname + "\n")
f.close() f.close()
class stl(object): class stl(object):
def __init__(self, filename = None): def __init__(self, filename = None):
self.facet = [[0, 0, 0],[[0, 0, 0],[0, 0, 0],[0, 0, 0]]] self.facet = [[0, 0, 0], [[0, 0, 0], [0, 0, 0], [0, 0, 0]]]
self.facets = [] self.facets = []
self.facetsminz = [] self.facetsminz = []
self.facetsmaxz = [] self.facetsmaxz = []
...@@ -129,16 +129,15 @@ class stl(object): ...@@ -129,16 +129,15 @@ class stl(object):
buf += newdata buf += newdata
fd = list(facetformat.unpack(buf)) fd = list(facetformat.unpack(buf))
self.name = "binary soloid" self.name = "binary soloid"
facet = [fd[:3],[fd[3:6], fd[6:9], fd[9:12]]] facet = [fd[:3], [fd[3:6], fd[6:9], fd[9:12]]]
self.facets.append(facet) self.facets.append(facet)
self.facetsminz.append((min(map(lambda x:x[2], facet[1])), facet)) self.facetsminz.append((min(map(lambda x: x[2], facet[1])), facet))
self.facetsmaxz.append((max(map(lambda x:x[2], facet[1])), facet)) self.facetsmaxz.append((max(map(lambda x: x[2], facet[1])), facet))
f.close() f.close()
return return
def translate(self, v = [0, 0, 0]): def translate(self, v = [0, 0, 0]):
matrix = [ matrix = [[1, 0, 0, v[0]],
[1, 0, 0, v[0]],
[0, 1, 0, v[1]], [0, 1, 0, v[1]],
[0, 0, 1, v[2]], [0, 0, 1, v[2]],
[0, 0, 0, 1] [0, 0, 0, 1]
...@@ -148,22 +147,19 @@ class stl(object): ...@@ -148,22 +147,19 @@ class stl(object):
def rotate(self, v = [0, 0, 0]): def rotate(self, v = [0, 0, 0]):
import math import math
z = v[2] z = v[2]
matrix1 = [ matrix1 = [[math.cos(math.radians(z)), -math.sin(math.radians(z)), 0, 0],
[math.cos(math.radians(z)),-math.sin(math.radians(z)), 0, 0],
[math.sin(math.radians(z)), math.cos(math.radians(z)), 0, 0], [math.sin(math.radians(z)), math.cos(math.radians(z)), 0, 0],
[0, 0, 1, 0], [0, 0, 1, 0],
[0, 0, 0, 1] [0, 0, 0, 1]
] ]
y = v[0] y = v[0]
matrix2 = [ matrix2 = [[1, 0, 0, 0],
[1, 0, 0, 0], [0, math.cos(math.radians(y)), -math.sin(math.radians(y)), 0],
[0, math.cos(math.radians(y)),-math.sin(math.radians(y)), 0],
[0, math.sin(math.radians(y)), math.cos(math.radians(y)), 0], [0, math.sin(math.radians(y)), math.cos(math.radians(y)), 0],
[0, 0, 0, 1] [0, 0, 0, 1]
] ]
x = v[1] x = v[1]
matrix3 = [ matrix3 = [[math.cos(math.radians(x)), 0, -math.sin(math.radians(x)), 0],
[math.cos(math.radians(x)), 0,-math.sin(math.radians(x)), 0],
[0, 1, 0, 0], [0, 1, 0, 0],
[math.sin(math.radians(x)), 0, math.cos(math.radians(x)), 0], [math.sin(math.radians(x)), 0, math.cos(math.radians(x)), 0],
[0, 0, 0, 1] [0, 0, 0, 1]
...@@ -171,15 +167,13 @@ class stl(object): ...@@ -171,15 +167,13 @@ class stl(object):
return self.transform(matrix1).transform(matrix2).transform(matrix3) return self.transform(matrix1).transform(matrix2).transform(matrix3)
def scale(self, v = [0, 0, 0]): def scale(self, v = [0, 0, 0]):
matrix = [ matrix = [[v[0], 0, 0, 0],
[v[0], 0, 0, 0],
[0, v[1], 0, 0], [0, v[1], 0, 0],
[0, 0, v[2], 0], [0, 0, v[2], 0],
[0, 0, 0, 1] [0, 0, 0, 1]
] ]
return self.transform(matrix) return self.transform(matrix)
def transform(self, m = I): def transform(self, m = I):
s = stl() s = stl()
s.facets = [applymatrix(i, m) for i in self.facets] s.facets = [applymatrix(i, m) for i in self.facets]
...@@ -189,20 +183,20 @@ class stl(object): ...@@ -189,20 +183,20 @@ class stl(object):
s.facetloc = 0 s.facetloc = 0
s.name = self.name s.name = self.name
for facet in s.facets: for facet in s.facets:
s.facetsminz+=[(min(map(lambda x:x[2], facet[1])), facet)] s.facetsminz += [(min(map(lambda x:x[2], facet[1])), facet)]
s.facetsmaxz+=[(max(map(lambda x:x[2], facet[1])), facet)] s.facetsmaxz += [(max(map(lambda x:x[2], facet[1])), facet)]
return s return s
def export(self, f = sys.stdout): def export(self, f = sys.stdout):
f.write("solid "+self.name+"\n") f.write("solid " + self.name + "\n")
for i in self.facets: for i in self.facets:
f.write(" facet normal "+" ".join(map(str, i[0]))+"\n") f.write(" facet normal " + " ".join(map(str, i[0])) + "\n")
f.write(" outer loop"+"\n") f.write(" outer loop" + "\n")
for j in i[1]: for j in i[1]:
f.write(" vertex "+" ".join(map(str, j))+"\n") f.write(" vertex " + " ".join(map(str, j)) + "\n")
f.write(" endloop"+"\n") f.write(" endloop" + "\n")
f.write(" endfacet"+"\n") f.write(" endfacet" + "\n")
f.write("endsolid "+self.name+"\n") f.write("endsolid " + self.name + "\n")
f.flush() f.flush()
def parseline(self, l): def parseline(self, l):
...@@ -216,33 +210,34 @@ class stl(object): ...@@ -216,33 +210,34 @@ class stl(object):
self.insolid = 0 self.insolid = 0
return 0 return 0
elif l.startswith("facet normal"): elif l.startswith("facet normal"):
l = l.replace(", ",".") l = l.replace(", ", ".")
self.infacet = 11 self.infacet = 11
self.facetloc = 0 self.facetloc = 0
self.facet = [[0, 0, 0],[[0, 0, 0],[0, 0, 0],[0, 0, 0]]] self.facet = [[0, 0, 0], [[0, 0, 0], [0, 0, 0], [0, 0, 0]]]
self.facet[0]=map(float, l.split()[2:]) self.facet[0] = map(float, l.split()[2:])
elif l.startswith("endfacet"): elif l.startswith("endfacet"):
self.infacet = 0 self.infacet = 0
self.facets+=[self.facet] self.facets += [self.facet]
facet = self.facet facet = self.facet
self.facetsminz+=[(min(map(lambda x:x[2], facet[1])), facet)] self.facetsminz += [(min(map(lambda x:x[2], facet[1])), facet)]
self.facetsmaxz+=[(max(map(lambda x:x[2], facet[1])), facet)] self.facetsmaxz += [(max(map(lambda x:x[2], facet[1])), facet)]
elif l.startswith("vertex"): elif l.startswith("vertex"):
l = l.replace(", ",".") l = l.replace(", ", ".")
self.facet[1][self.facetloc]=map(float, l.split()[1:]) self.facet[1][self.facetloc] = map(float, l.split()[1:])
self.facetloc+=1 self.facetloc += 1
return 1 return 1
if __name__ == "__main__": if __name__ == "__main__":
s = stl("../../Downloads/frame-vertex-neo-foot-x4.stl") s = stl("../../Downloads/frame-vertex-neo-foot-x4.stl")
for i in xrange(11, 11): for i in xrange(11, 11):
working = s.facets[:] working = s.facets[:]
for j in reversed(sorted(s.facetsminz)): for j in reversed(sorted(s.facetsminz)):
if(j[0]>i): if(j[0] > i):
working.remove(j[1]) working.remove(j[1])
else: else:
break break
for j in (sorted(s.facetsmaxz)): for j in (sorted(s.facetsmaxz)):
if(j[0]<i): if(j[0] < i):
working.remove(j[1]) working.remove(j[1])
else: else:
break break
......
...@@ -15,11 +15,7 @@ ...@@ -15,11 +15,7 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with Printrun. If not, see <http://www.gnu.org/licenses/>. # along with Printrun. If not, see <http://www.gnu.org/licenses/>.
import os
import math
import stltool
import wx import wx
from wx import glcanvas
import time import time
import threading import threading
...@@ -140,7 +136,7 @@ class StlViewPanel(wxGLPanel): ...@@ -140,7 +136,7 @@ class StlViewPanel(wxGLPanel):
v = map(lambda m, w, b: b * m / w, p, sz, self.build_dimensions[0:2]) v = map(lambda m, w, b: b * m / w, p, sz, self.build_dimensions[0:2])
v[1] = self.build_dimensions[1] - v[1] v[1] = self.build_dimensions[1] - v[1]
v += [300] v += [300]
print "Double-click at "+str(v)+" in " print "Double-click at " + str(v) + " in "
print self print self
def forceresize(self): def forceresize(self):
...@@ -160,8 +156,7 @@ class StlViewPanel(wxGLPanel): ...@@ -160,8 +156,7 @@ class StlViewPanel(wxGLPanel):
name = self.parent.l.GetString(name) name = self.parent.l.GetString(name)
model = self.parent.models[name] model = self.parent.models[name]
model.offsets = [ model.offsets = [model.offsets[0] + delta[0],
model.offsets[0] + delta[0],
model.offsets[1] + delta[1], model.offsets[1] + delta[1],
model.offsets[2] model.offsets[2]
] ]
...@@ -178,7 +173,7 @@ class StlViewPanel(wxGLPanel): ...@@ -178,7 +173,7 @@ class StlViewPanel(wxGLPanel):
""" """
self.mousepos = event.GetPositionTuple() self.mousepos = event.GetPositionTuple()
if event.Dragging() and event.LeftIsDown(): if event.Dragging() and event.LeftIsDown():
if self.initpos == None: if self.initpos is None:
self.initpos = event.GetPositionTuple() self.initpos = event.GetPositionTuple()
else: else:
if not event.ShiftDown(): if not event.ShiftDown():
...@@ -251,7 +246,7 @@ class StlViewPanel(wxGLPanel): ...@@ -251,7 +246,7 @@ class StlViewPanel(wxGLPanel):
if delta > 0: if delta > 0:
self.zoom(factor, (x, y)) self.zoom(factor, (x, y))
else: else:
self.zoom(1/factor, (x, y)) self.zoom(1 / factor, (x, y))
def keypress(self, event): def keypress(self, event):
"""gets keypress events and moves/rotates acive shape""" """gets keypress events and moves/rotates acive shape"""
...@@ -283,8 +278,7 @@ class StlViewPanel(wxGLPanel): ...@@ -283,8 +278,7 @@ class StlViewPanel(wxGLPanel):
event.Skip() event.Skip()
def update(self): def update(self):
while(1): while True:
dt = 0.05
time.sleep(0.05) time.sleep(0.05)
try: try:
wx.CallAfter(self.Refresh) wx.CallAfter(self.Refresh)
...@@ -321,7 +315,7 @@ class StlViewPanel(wxGLPanel): ...@@ -321,7 +315,7 @@ class StlViewPanel(wxGLPanel):
def drawmodel(self, m, n): def drawmodel(self, m, n):
batch = pyglet.graphics.Batch() batch = pyglet.graphics.Batch()
stl = stlview(m.facets, batch = batch) stlview(m.facets, batch = batch)
m.batch = batch m.batch = batch
m.animoffset = 300 m.animoffset = 300
#print m #print m
...@@ -340,8 +334,8 @@ class StlViewPanel(wxGLPanel): ...@@ -340,8 +334,8 @@ class StlViewPanel(wxGLPanel):
glTranslatef(0, 0, -self.dist) glTranslatef(0, 0, -self.dist)
glMultMatrixd(build_rotmatrix(self.basequat)) # Rotate according to trackball glMultMatrixd(build_rotmatrix(self.basequat)) # Rotate according to trackball
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.2, 0.2, 0.2, 1)) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.2, 0.2, 0.2, 1))
glTranslatef(- self.build_dimensions[3] - self.platform.width/2, glTranslatef(- self.build_dimensions[3] - self.platform.width / 2,
- self.build_dimensions[4] - self.platform.depth/2, 0) # Move origin to bottom left of platform - self.build_dimensions[4] - self.platform.depth / 2, 0) # Move origin to bottom left of platform
# Draw platform # Draw platform
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
self.platform.draw() self.platform.draw()
...@@ -378,7 +372,7 @@ class StlViewPanel(wxGLPanel): ...@@ -378,7 +372,7 @@ class StlViewPanel(wxGLPanel):
def main(): def main():
app = wx.App(redirect = False) app = wx.App(redirect = False)
frame = wx.Frame(None, -1, "GL Window", size = (400, 400)) frame = wx.Frame(None, -1, "GL Window", size = (400, 400))
panel = StlViewPanel(frame) StlViewPanel(frame)
frame.Show(True) frame.Show(True)
app.MainLoop() app.MainLoop()
app.Destroy() app.Destroy()
......
This diff is collapsed.
...@@ -13,9 +13,10 @@ ...@@ -13,9 +13,10 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with Printrun. If not, see <http://www.gnu.org/licenses/>. # along with Printrun. If not, see <http://www.gnu.org/licenses/>.
import wx, os, math import wx
from bufferedcanvas import * import math
from printrun_utils import * from bufferedcanvas import BufferedCanvas
from printrun_utils import imagefile
def sign(n): def sign(n):
if n < 0: return -1 if n < 0: return -1
...@@ -83,11 +84,11 @@ class ZButtons(BufferedCanvas): ...@@ -83,11 +84,11 @@ class ZButtons(BufferedCanvas):
fudge = 11 fudge = 11
x = 0 + fudge x = 0 + fudge
w = 59 - fudge*2 w = 59 - fudge * 2
if rng >= 0: if rng >= 0:
k = 1 if dir > 0 else 0 k = 1 if dir > 0 else 0
y = ZButtons.center[1] - (dir * ZButtons.button_ydistances[rng+k]) y = ZButtons.center[1] - (dir * ZButtons.button_ydistances[rng + k])
h = ZButtons.button_ydistances[rng+1] - ZButtons.button_ydistances[rng] h = ZButtons.button_ydistances[rng + 1] - ZButtons.button_ydistances[rng]
gc.DrawRoundedRectangle(x, y, w, h, 4) gc.DrawRoundedRectangle(x, y, w, h, 4)
# gc.DrawRectangle(x, y, w, h) # gc.DrawRectangle(x, y, w, h)
# self.drawPartialPie(dc, center, r1-inner_ring_radius, r2-inner_ring_radius, a1+fudge, a2-fudge) # self.drawPartialPie(dc, center, r1-inner_ring_radius, r2-inner_ring_radius, a1+fudge, a2-fudge)
...@@ -107,16 +108,16 @@ class ZButtons(BufferedCanvas): ...@@ -107,16 +108,16 @@ class ZButtons(BufferedCanvas):
if self.enabled: if self.enabled:
# Draw label overlays # Draw label overlays
gc.SetPen(wx.Pen(wx.Colour(255, 255, 255, 128), 1)) gc.SetPen(wx.Pen(wx.Colour(255, 255, 255, 128), 1))
gc.SetBrush(wx.Brush(wx.Colour(255, 255, 255, 128+64))) gc.SetBrush(wx.Brush(wx.Colour(255, 255, 255, 128 + 64)))
for idx, kpos in ZButtons.label_overlay_positions.items(): for idx, kpos in ZButtons.label_overlay_positions.items():
if kpos and idx != self.range: if kpos and idx != self.range:
r = kpos[2] r = kpos[2]
gc.DrawEllipse(ZButtons.center[0]-kpos[0]-r, ZButtons.center[1]-kpos[1]-r, r*2, r*2) gc.DrawEllipse(ZButtons.center[0] - kpos[0] - r, ZButtons.center[1] - kpos[1] - r, r * 2, r * 2)
# Top 'layer' is the mouse-over highlights # Top 'layer' is the mouse-over highlights
gc.SetPen(wx.Pen(wx.Colour(100, 100, 100, 172), 4)) gc.SetPen(wx.Pen(wx.Colour(100, 100, 100, 172), 4))
gc.SetBrush(wx.Brush(wx.Colour(0, 0, 0, 128))) gc.SetBrush(wx.Brush(wx.Colour(0, 0, 0, 128)))
if self.range != None and self.direction != None: if self.range is not None and self.direction is not None:
self.highlight(gc, self.range, self.direction) self.highlight(gc, self.range, self.direction)
else: else:
gc.SetPen(wx.Pen(self.bgcolor, 0)) gc.SetPen(wx.Pen(self.bgcolor, 0))
......
...@@ -13,44 +13,39 @@ ...@@ -13,44 +13,39 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with Printrun. If not, see <http://www.gnu.org/licenses/>. # along with Printrun. If not, see <http://www.gnu.org/licenses/>.
import wx, math import wx
from stltool import * from stltool import stl, genfacet, emitstl
a = wx.App() a = wx.App()
def genscape(data = [[0, 1, 0, 0],[1, 0, 2, 0],[1, 0, 0, 0],[0, 1, 0, 1]], pscale = 1.0, bheight = 1.0, zscale = 1.0): def genscape(data = [[0, 1, 0, 0], [1, 0, 2, 0], [1, 0, 0, 0], [0, 1, 0, 1]],
pscale = 1.0, bheight = 1.0, zscale = 1.0):
o = stl(None) o = stl(None)
datal = len(data) datal = len(data)
datah = len(data[0]) datah = len(data[0])
#create bottom: #create bottom:
bmidpoint = (pscale*(datal-1)/2.0, pscale*(datah-1)/2.0) bmidpoint = (pscale * (datal - 1) / 2.0, pscale * (datah - 1) / 2.0)
#print range(datal), bmidpoint #print range(datal), bmidpoint
for i in zip(range(datal+1)[:-1], range(datal+1)[1:])[:-1]: for i in zip(range(datal + 1)[:-1], range(datal + 1)[1:])[:-1]:
#print (pscale*i[0], pscale*i[1]) #print (pscale*i[0], pscale*i[1])
o.facets+=[[[0, 0,-1],[[0.0, pscale*i[0], 0.0],[0.0, pscale*i[1], 0.0],[bmidpoint[0], bmidpoint[1], 0.0]]]] o.facets += [[[0, 0, -1], [[0.0, pscale * i[0], 0.0], [0.0, pscale * i[1], 0.0], [bmidpoint[0], bmidpoint[1], 0.0]]]]
o.facets+=[[[0, 0,-1],[[2.0*bmidpoint[1], pscale*i[1], 0.0],[2.0*bmidpoint[1], pscale*i[0], 0.0],[bmidpoint[0], bmidpoint[1], 0.0]]]] o.facets += [[[0, 0, -1], [[2.0 * bmidpoint[1], pscale * i[1], 0.0], [2.0 * bmidpoint[1], pscale * i[0], 0.0], [bmidpoint[0], bmidpoint[1], 0.0]]]]
o.facets+=[genfacet([[0.0, pscale*i[0], data[i[0]][0]*zscale+bheight],[0.0, pscale*i[1], data[i[1]][0]*zscale+bheight],[0.0, pscale*i[1], 0.0]])] o.facets += [genfacet([[0.0, pscale * i[0], data[i[0]][0] * zscale + bheight], [0.0, pscale * i[1], data[i[1]][0] * zscale + bheight], [0.0, pscale * i[1], 0.0]])]
o.facets+=[genfacet([[2.0*bmidpoint[1], pscale*i[1], data[i[1]][datah-1]*zscale+bheight],[2.0*bmidpoint[1], pscale*i[0], data[i[0]][datah-1]*zscale+bheight],[2.0*bmidpoint[1], pscale*i[1], 0.0]])] o.facets += [genfacet([[2.0 * bmidpoint[1], pscale * i[1], data[i[1]][datah - 1] * zscale + bheight], [2.0 * bmidpoint[1], pscale * i[0], data[i[0]][datah - 1] * zscale + bheight], [2.0 * bmidpoint[1], pscale * i[1], 0.0]])]
o.facets+=[genfacet([[0.0, pscale*i[0], data[i[0]][0]*zscale+bheight],[0.0, pscale*i[1], 0.0],[0.0, pscale*i[0], 0.0]])] o.facets += [genfacet([[0.0, pscale * i[0], data[i[0]][0] * zscale + bheight], [0.0, pscale * i[1], 0.0], [0.0, pscale * i[0], 0.0]])]
o.facets+=[genfacet([[2.0*bmidpoint[1], pscale*i[1], 0.0],[2.0*bmidpoint[1], pscale*i[0], data[i[0]][datah-1]*zscale+bheight],[2.0*bmidpoint[1], pscale*i[0], 0.0]])] o.facets += [genfacet([[2.0 * bmidpoint[1], pscale * i[1], 0.0], [2.0 * bmidpoint[1], pscale * i[0], data[i[0]][datah - 1] * zscale + bheight], [2.0 * bmidpoint[1], pscale * i[0], 0.0]])]
for i in zip(range(datah + 1)[: - 1], range(datah + 1)[1:])[: - 1]:
#print (pscale * i[0], pscale * i[1])
o.facets += [[[0, 0, -1], [[pscale * i[1], 0.0, 0.0], [pscale * i[0], 0.0, 0.0], [bmidpoint[0], bmidpoint[1], 0.0]]]]
o.facets += [[[0, 0, -1], [[pscale * i[0], 2.0 * bmidpoint[0], 0.0], [pscale * i[1], 2.0 * bmidpoint[0], 0.0], [bmidpoint[0], bmidpoint[1], 0.0]]]]
o.facets += [genfacet([[pscale * i[1], 0.0, data[0][i[1]] * zscale + bheight], [pscale * i[0], 0.0, data[0][i[0]] * zscale + bheight], [pscale * i[1], 0.0, 0.0]])]
o.facets += [genfacet([[pscale * i[0], 2.0 * bmidpoint[0], data[datal - 1][i[0]] * zscale + bheight], [pscale * i[1], 2.0 * bmidpoint[0], data[datal - 1][i[1]] * zscale + bheight], [pscale * i[1], 2.0 * bmidpoint[0], 0.0]])]
o.facets += [genfacet([[pscale * i[1], 0.0, 0.0], [pscale * i[0], 0.0, data[0][i[0]] * zscale + bheight], [pscale * i[0], 0.0, 0.0]])]
o.facets += [genfacet([[pscale * i[0], 2.0 * bmidpoint[0], data[datal - 1][i[0]] * zscale + bheight], [pscale * i[1], 2.0 * bmidpoint[0], 0.0], [pscale * i[0], 2.0 * bmidpoint[0], 0.0]])]
for i in xrange(datah - 1):
for j in xrange(datal - 1):
o.facets += [genfacet([[pscale * i, pscale * j, data[j][i] * zscale + bheight], [pscale * (i + 1), pscale * (j), data[j][i + 1] * zscale + bheight], [pscale * (i + 1), pscale * (j + 1), data[j + 1][i + 1] * zscale + bheight]])]
o.facets += [genfacet([[pscale * (i), pscale * (j + 1), data[j + 1][i] * zscale + bheight], [pscale * i, pscale * j, data[j][i] * zscale + bheight], [pscale * (i + 1), pscale * (j + 1), data[j + 1][i + 1] * zscale + bheight]])]
#print o.facets[-1] #print o.facets[-1]
pass
#print o.facets[-4:]
for i in zip(range(datah+1)[:-1], range(datah+1)[1:])[:-1]:
#print (pscale*i[0], pscale*i[1])
o.facets+=[[[0, 0,-1],[[pscale*i[1], 0.0, 0.0],[pscale*i[0], 0.0, 0.0],[bmidpoint[0], bmidpoint[1], 0.0]]]]
o.facets+=[[[0, 0,-1],[[pscale*i[0], 2.0*bmidpoint[0], 0.0],[pscale*i[1], 2.0*bmidpoint[0], 0.0],[bmidpoint[0], bmidpoint[1], 0.0]]]]
o.facets+=[genfacet([[pscale*i[1], 0.0, data[0][i[1]]*zscale+bheight],[pscale*i[0], 0.0, data[0][i[0]]*zscale+bheight],[pscale*i[1], 0.0, 0.0]])]
#break
o.facets+=[genfacet([[pscale*i[0], 2.0*bmidpoint[0], data[datal-1][i[0]]*zscale+bheight],[pscale*i[1], 2.0*bmidpoint[0], data[datal-1][i[1]]*zscale+bheight],[pscale*i[1], 2.0*bmidpoint[0], 0.0]])]
o.facets+=[genfacet([[pscale*i[1], 0.0, 0.0],[pscale*i[0], 0.0, data[0][i[0]]*zscale+bheight],[pscale*i[0], 0.0, 0.0]])]
o.facets+=[genfacet([[pscale*i[0], 2.0*bmidpoint[0], data[datal-1][i[0]]*zscale+bheight],[pscale*i[1], 2.0*bmidpoint[0], 0.0],[pscale*i[0], 2.0*bmidpoint[0], 0.0]])]
pass
for i in xrange(datah-1):
for j in xrange(datal-1):
o.facets+=[genfacet([[pscale*i, pscale*j, data[j][i]*zscale+bheight],[pscale*(i+1), pscale*(j), data[j][i+1]*zscale+bheight],[pscale*(i+1), pscale*(j+1), data[j+1][i+1]*zscale+bheight]])]
o.facets+=[genfacet([[pscale*(i), pscale*(j+1), data[j+1][i]*zscale+bheight],[pscale*i, pscale*j, data[j][i]*zscale+bheight],[pscale*(i+1), pscale*(j+1), data[j+1][i+1]*zscale+bheight]])]
#print o.facets[-1]
facet = [[0, 0, 0],[[0, 0, 0],[0, 0, 0],[0, 0, 0]]]
return o return o
def zimage(name, out): def zimage(name, out):
i = wx.Image(name) i = wx.Image(name)
...@@ -59,14 +54,15 @@ def zimage(name, out): ...@@ -59,14 +54,15 @@ def zimage(name, out):
b = map(ord, i.GetData()[::3]) b = map(ord, i.GetData()[::3])
data = [] data = []
for i in xrange(s[0]): for i in xrange(s[0]):
data+=[b[i*s[1]:(i+1)*s[1]]] data += [b[i * s[1]:(i + 1) * s[1]]]
#data = [i[::5] for i in data[::5]] #data = [i[::5] for i in data[::5]]
emitstl(out, genscape(data, zscale = 0.1).facets, name) emitstl(out, genscape(data, zscale = 0.1).facets, name)
""" """
class scapewin(wx.Frame): class scapewin(wx.Frame):
def __init__(self, size = (400, 530)): def __init__(self, size = (400, 530)):
wx.Frame.__init__(self, None, title = "Right-click to load an image", size = size) wx.Frame.__init__(self, None,
title = "Right-click to load an image", size = size)
self.SetIcon(wx.Icon("plater.ico", wx.BITMAP_TYPE_ICO)) self.SetIcon(wx.Icon("plater.ico", wx.BITMAP_TYPE_ICO))
self.SetClientSize(size) self.SetClientSize(size)
self.panel = wx.Panel(self, size = size) self.panel = wx.Panel(self, size = size)
......
This diff is collapsed.
This diff is collapsed.
...@@ -15,9 +15,9 @@ ...@@ -15,9 +15,9 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with Printrun. If not, see <http://www.gnu.org/licenses/>. # along with Printrun. If not, see <http://www.gnu.org/licenses/>.
import sys, os, glob import sys
import subprocess import os
from stat import * from stat import S_IRUSR, S_IWUSR, S_IRGRP, S_IROTH
from distutils.core import setup from distutils.core import setup
from distutils.command.install import install as _install from distutils.command.install import install as _install
from distutils.command.install_data import install_data as _install_data from distutils.command.install_data import install_data as _install_data
...@@ -33,93 +33,93 @@ INSTALLED_FILES = "installed_files" ...@@ -33,93 +33,93 @@ INSTALLED_FILES = "installed_files"
class install (_install): class install (_install):
def run (self): def run(self):
_install.run (self) _install.run(self)
outputs = self.get_outputs () outputs = self.get_outputs()
length = 0 length = 0
if self.root: if self.root:
length += len (self.root) length += len(self.root)
if self.prefix: if self.prefix:
length += len (self.prefix) length += len(self.prefix)
if length: if length:
for counter in xrange (len (outputs)): for counter in xrange(len(outputs)):
outputs[counter] = outputs[counter][length:] outputs[counter] = outputs[counter][length:]
data = "\n".join (outputs) data = "\n".join(outputs)
try: try:
file = open (INSTALLED_FILES, "w") file = open(INSTALLED_FILES, "w")
except: except:
self.warn ("Could not write installed files list %s" % \ self.warn("Could not write installed files list %s" %
INSTALLED_FILES) INSTALLED_FILES)
return return
file.write (data) file.write(data)
file.close () file.close()
class install_data (_install_data): class install_data(_install_data):
def run (self): def run(self):
def chmod_data_file (file): def chmod_data_file(file):
try: try:
os.chmod (file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) os.chmod(file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
except: except:
self.warn ("Could not chmod data file %s" % file) self.warn("Could not chmod data file %s" % file)
_install_data.run (self) _install_data.run(self)
map (chmod_data_file, self.get_outputs ()) map(chmod_data_file, self.get_outputs())
class uninstall (_install): class uninstall(_install):
def run (self): def run(self):
try: try:
file = open (INSTALLED_FILES, "r") file = open(INSTALLED_FILES, "r")
except: except:
self.warn ("Could not read installed files list %s" % \ self.warn("Could not read installed files list %s" %
INSTALLED_FILES) INSTALLED_FILES)
return return
files = file.readlines () files = file.readlines()
file.close () file.close()
prepend = "" prepend = ""
if self.root: if self.root:
prepend += self.root prepend += self.root
if self.prefix: if self.prefix:
prepend += self.prefix prepend += self.prefix
if len (prepend): if len(prepend):
for counter in xrange (len (files)): for counter in xrange(len(files)):
files[counter] = prepend + files[counter].rstrip () files[counter] = prepend + files[counter].rstrip()
for file in files: for file in files:
print "Uninstalling %s" % file print "Uninstalling", file
try: try:
os.unlink (file) os.unlink(file)
except: except:
self.warn ("Could not remove file %s" % file) self.warn("Could not remove file %s" % file)
ops = ("install", "build", "sdist", "uninstall", "clean", "build_ext") ops = ("install", "build", "sdist", "uninstall", "clean", "build_ext")
if len (sys.argv) < 2 or sys.argv[1] not in ops: if len(sys.argv) < 2 or sys.argv[1] not in ops:
print "Please specify operation : %s" % " | ".join (ops) print "Please specify operation : %s" % " | ".join(ops)
raise SystemExit raise SystemExit
prefix = None prefix = None
if len (sys.argv) > 2: if len(sys.argv) > 2:
i = 0 i = 0
for o in sys.argv: for o in sys.argv:
if o.startswith ("--prefix"): if o.startswith("--prefix"):
if o == "--prefix": if o == "--prefix":
if len (sys.argv) >= i: if len(sys.argv) >= i:
prefix = sys.argv[i + 1] prefix = sys.argv[i + 1]
sys.argv.remove (prefix) sys.argv.remove(prefix)
elif o.startswith ("--prefix=") and len (o[9:]): elif o.startswith("--prefix=") and len(o[9:]):
prefix = o[9:] prefix = o[9:]
sys.argv.remove (o) sys.argv.remove(o)
i += 1 i += 1
if not prefix and "PREFIX" in os.environ: if not prefix and "PREFIX" in os.environ:
prefix = os.environ["PREFIX"] prefix = os.environ["PREFIX"]
if not prefix or not len (prefix): if not prefix or not len(prefix):
prefix = sys.prefix prefix = sys.prefix
if sys.argv[1] in ("install", "uninstall") and len (prefix): if sys.argv[1] in("install", "uninstall") and len(prefix):
sys.argv += ["--prefix", prefix] sys.argv += ["--prefix", prefix]
target_images_path = "share/pronterface/images/" target_images_path = "share/pronterface/images/"
data_files = [('share/pixmaps/', ['P-face.ico','plater.ico','pronsole.ico'])] data_files = [('share/pixmaps/', ['P-face.ico', 'plater.ico', 'pronsole.ico'])]
for basedir, subdirs, files in os.walk("images"): for basedir, subdirs, files in os.walk("images"):
images = [] images = []
...@@ -135,23 +135,22 @@ for basedir, subdirs, files in os.walk("locale"): ...@@ -135,23 +135,22 @@ for basedir, subdirs, files in os.walk("locale"):
destpath = os.path.join("share", "pronterface", basedir) destpath = os.path.join("share", "pronterface", basedir)
files = filter(lambda x: x.endswith(".mo"), files) files = filter(lambda x: x.endswith(".mo"), files)
files = map(lambda x: os.path.join(basedir, x), files) files = map(lambda x: os.path.join(basedir, x), files)
data_files.append ((destpath, files)) data_files.append((destpath, files))
extra_data_dirs = ["css"] extra_data_dirs = ["css"]
for extra_data_dir in extra_data_dirs: for extra_data_dir in extra_data_dirs:
for basedir, subdirs, files in os.walk(extra_data_dir): for basedir, subdirs, files in os.walk(extra_data_dir):
files = map(lambda x: os.path.join(basedir, x), files) files = map(lambda x: os.path.join(basedir, x), files)
destpath = os.path.join("share", "pronterface", basedir) destpath = os.path.join("share", "pronterface", basedir)
data_files.append ((destpath, files)) data_files.append((destpath, files))
cmdclass = {"uninstall" : uninstall, cmdclass = {"uninstall": uninstall,
"install" : install, "install": install,
"install_data" : install_data} "install_data": install_data}
if build_ext: if build_ext:
cmdclass['build_ext'] = build_ext cmdclass['build_ext'] = build_ext
setup ( setup(name = "Printrun",
name = "Printrun",
description = "Host software for 3D printers", description = "Host software for 3D printers",
author = "Kliment Yanev", author = "Kliment Yanev",
url = "http://github.com/kliment/Printrun/", url = "http://github.com/kliment/Printrun/",
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment