Commit b631c3ba authored by Václav 'Ax' Hůla's avatar Václav 'Ax' Hůla

reformated stlview to be more pep8 conformant ('official' python formating style)

parent 9e354d85
#!/usr/bin/python #!/usr/bin/python
import os import os
import wx,math,stltool import math
import stltool
import wx
from wx import glcanvas from wx import glcanvas
import time import time
import threading import threading
...@@ -8,11 +10,10 @@ import threading ...@@ -8,11 +10,10 @@ import threading
import pyglet import pyglet
pyglet.options['shadow_window'] = False pyglet.options['shadow_window'] = False
pyglet.options['debug_gl'] = False pyglet.options['debug_gl'] = False
from pyglet import gl
from pyglet.gl import * from pyglet.gl import *
class GLPanel(wx.Panel):
class GLPanel(wx.Panel):
'''A simple class for using OpenGL with wxPython.''' '''A simple class for using OpenGL with wxPython.'''
def __init__(self, parent, id, pos=wx.DefaultPosition, def __init__(self, parent, id, pos=wx.DefaultPosition,
...@@ -95,12 +96,12 @@ class GLPanel(wx.Panel): ...@@ -95,12 +96,12 @@ class GLPanel(wx.Panel):
def OnInitGL(self): def OnInitGL(self):
'''Initialize OpenGL for use in the window.''' '''Initialize OpenGL for use in the window.'''
#create a pyglet context for this panel #create a pyglet context for this panel
self.pmat=(GLdouble * 16)() self.pmat = (GLdouble * 16)()
self.mvmat=(GLdouble * 16)() self.mvmat = (GLdouble * 16)()
self.pygletcontext = Context(current_context) self.pygletcontext = Context(current_context)
self.pygletcontext.set_current() self.pygletcontext.set_current()
self.dist=1000 self.dist = 1000
self.vpmat=None self.vpmat = None
#normal gl init #normal gl init
glClearColor(0, 0, 0, 1) glClearColor(0, 0, 0, 1)
glColor3f(1, 0, 0) glColor3f(1, 0, 0)
...@@ -130,20 +131,18 @@ class GLPanel(wx.Panel): ...@@ -130,20 +131,18 @@ class GLPanel(wx.Panel):
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.5, 0, 0.3, 1)) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.5, 0, 0.3, 1))
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, vec(1, 1, 1, 1)) glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, vec(1, 1, 1, 1))
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 50) glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 50)
glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, vec(0,0.1,0,0.9)) glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, vec(0, 0.1, 0, 0.9))
#create objects to draw #create objects to draw
#self.create_objects() #self.create_objects()
def OnReshape(self, width, height): def OnReshape(self, width, height):
'''Reshape the OpenGL viewport based on the dimensions of the window.''' '''Reshape the OpenGL viewport based on the dimensions of the window.'''
if not self.GLinitialized: if not self.GLinitialized:
self.OnInitGL() self.OnInitGL()
self.GLinitialized = True self.GLinitialized = True
self.pmat=(GLdouble * 16)() self.pmat = (GLdouble * 16)()
self.mvmat=(GLdouble * 16)() self.mvmat = (GLdouble * 16)()
glViewport(0, 0, width, height) glViewport(0, 0, width, height)
glMatrixMode(GL_PROJECTION) glMatrixMode(GL_PROJECTION)
glLoadIdentity() glLoadIdentity()
...@@ -151,12 +150,11 @@ class GLPanel(wx.Panel): ...@@ -151,12 +150,11 @@ class GLPanel(wx.Panel):
glMatrixMode(GL_MODELVIEW) glMatrixMode(GL_MODELVIEW)
glLoadIdentity() glLoadIdentity()
#pyglet stuff #pyglet stuff
self.vpmat=(GLint * 4)(0,0,*list(self.GetClientSize())) self.vpmat = (GLint * 4)(0, 0, *list(self.GetClientSize()))
glGetDoublev(GL_PROJECTION_MATRIX,self.pmat) glGetDoublev(GL_PROJECTION_MATRIX, self.pmat)
glGetDoublev(GL_MODELVIEW_MATRIX,self.mvmat) glGetDoublev(GL_MODELVIEW_MATRIX, self.mvmat)
#glMatrixMode(GL_PROJECTION) #glMatrixMode(GL_PROJECTION)
# Wrap text to the width of the window # Wrap text to the width of the window
if self.GLinitialized: if self.GLinitialized:
self.pygletcontext.set_current() self.pygletcontext.set_current()
...@@ -167,7 +165,7 @@ class GLPanel(wx.Panel): ...@@ -167,7 +165,7 @@ class GLPanel(wx.Panel):
#clear the context #clear the context
self.canvas.SetCurrent() self.canvas.SetCurrent()
self.pygletcontext.set_current() self.pygletcontext.set_current()
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
#draw objects #draw objects
self.draw_objects() self.draw_objects()
#update screen #update screen
...@@ -188,6 +186,7 @@ class GLPanel(wx.Panel): ...@@ -188,6 +186,7 @@ class GLPanel(wx.Panel):
'''called in the middle of ondraw after the buffer has been cleared''' '''called in the middle of ondraw after the buffer has been cleared'''
pass pass
class stlview(object): class stlview(object):
def __init__(self, facets, batch): def __init__(self, facets, batch):
# Create the vertex and normal arrays. # Create the vertex and normal arrays.
...@@ -200,11 +199,11 @@ class stlview(object): ...@@ -200,11 +199,11 @@ class stlview(object):
normals.extend(i[0]) normals.extend(i[0])
# Create a list of triangle indices. # Create a list of triangle indices.
indices = range(3*len(facets))#[[3*i,3*i+1,3*i+2] for i in xrange(len(facets))] indices = range(3 * len(facets)) # [[3*i,3*i+1,3*i+2] for i in xrange(len(facets))]
#print indices[:10] #print indices[:10]
self.vertex_list = batch.add_indexed(len(vertices)//3, self.vertex_list = batch.add_indexed(len(vertices) // 3,
GL_TRIANGLES, GL_TRIANGLES,
None,#group, None, # group,
indices, indices,
('v3f/static', vertices), ('v3f/static', vertices),
('n3f/static', normals)) ('n3f/static', normals))
...@@ -212,8 +211,9 @@ class stlview(object): ...@@ -212,8 +211,9 @@ class stlview(object):
def delete(self): def delete(self):
self.vertex_list.delete() self.vertex_list.delete()
def vdiff(v,o):
return [x[0]-x[1] for x in zip(v,o)] def vdiff(v, o):
return [x[0] - x[1] for x in zip(v, o)]
class gcview(object): class gcview(object):
...@@ -221,213 +221,227 @@ class gcview(object): ...@@ -221,213 +221,227 @@ class gcview(object):
# Create the vertex and normal arrays. # Create the vertex and normal arrays.
vertices = [] vertices = []
normals = [] normals = []
self.prev=[0.001,0.001,0.001,0.001] self.prev = [0.001, 0.001, 0.001, 0.001]
self.fline=1 self.fline = 1
self.vlists=[] self.vlists = []
self.layers={} self.layers = {}
t0=time.time() t0 = time.time()
lines=[self.transform(i) for i in lines] lines = [self.transform(i) for i in lines]
lines=[i for i in lines if i is not None] lines = [i for i in lines if i is not None]
print "transformed lines in %fs"%(time.time()-t0) print "transformed lines in %fs" % (time.time() - t0)
t0=time.time() t0 = time.time()
layertemp={} layertemp = {}
lasth=None lasth = None
counter=0 counter = 0
if len(lines)==0: if len(lines) == 0:
return return
for i in lines: for i in lines:
counter+=1 counter += 1
if i[0][2] not in layertemp: if i[0][2] not in layertemp:
layertemp[i[0][2]]=[[],[]] layertemp[i[0][2]] = [[], []]
if lasth is not None: if lasth is not None:
self.layers[lasth]=pyglet.graphics.Batch() self.layers[lasth] = pyglet.graphics.Batch()
lt=layertemp[lasth][0] lt = layertemp[lasth][0]
indices = range(len(layertemp[lasth][0])//3)#[[3*i,3*i+1,3*i+2] for i in xrange(len(facets))] indices = range(len(layertemp[lasth][0]) // 3) # [[3*i,3*i+1,3*i+2] for i in xrange(len(facets))]
self.vlists.append(self.layers[lasth].add_indexed(len(layertemp[lasth][0])//3, self.vlists.append(self.layers[lasth].add_indexed(len(layertemp[lasth][0]) // 3,
GL_TRIANGLES, GL_TRIANGLES,
None,#group, None, # group,
indices, indices,
('v3f/static', layertemp[lasth][0]), ('v3f/static', layertemp[lasth][0]),
('n3f/static', layertemp[lasth][1]))) ('n3f/static', layertemp[lasth][1])))
lasth=i[0][2] lasth = i[0][2]
spoints,epoints,S,E=self.genline(i,h,w) spoints, epoints, S, E = self.genline(i, h, w)
verticestoadd=[[spoints[(j+1)%8],epoints[(j)%8],spoints[j],epoints[j],spoints[(j+1)%8],epoints[(j+1)%8]] for j in xrange(8)] verticestoadd = [[
normalstoadd=[map(vdiff,v,[S,E,S,E,S,E]) for v in verticestoadd] spoints[(j + 1) % 8],
v1=[] epoints[(j) % 8],
map(v1.extend,verticestoadd) spoints[j],
v2=[] epoints[j],
map(v2.extend,v1) spoints[(j + 1) % 8],
n1=[] epoints[(j + 1) % 8]
map(n1.extend,normalstoadd) ] for j in xrange(8)]
n2=[] normalstoadd = [map(vdiff, v, [S, E, S, E, S, E]) for v in verticestoadd]
map(n2.extend,n1) v1 = []
map(v1.extend, verticestoadd)
layertemp[i[0][2]][0]+=v2 v2 = []
vertices+=v2 map(v2.extend, v1)
layertemp[i[0][2]][1]+=n2 n1 = []
normals+=n2 map(n1.extend, normalstoadd)
print "appended lines in %fs"%(time.time()-t0) n2 = []
t0=time.time() map(n2.extend, n1)
layertemp[i[0][2]][0] += v2
vertices += v2
layertemp[i[0][2]][1] += n2
normals += n2
print "appended lines in %fs" % (time.time() - t0)
t0 = time.time()
# Create a list of triangle indices. # Create a list of triangle indices.
indices = range(3*16*len(lines))#[[3*i,3*i+1,3*i+2] for i in xrange(len(facets))] indices = range(3 * 16 * len(lines)) # [[3*i,3*i+1,3*i+2] for i in xrange(len(facets))]
self.vlists.append(batch.add_indexed(len(vertices)//3, self.vlists.append(batch.add_indexed(len(vertices) // 3,
GL_TRIANGLES, GL_TRIANGLES,
None,#group, None, # group,
indices, indices,
('v3f/static', vertices), ('v3f/static', vertices),
('n3f/static', normals))) ('n3f/static', normals)))
if lasth is not None: if lasth is not None:
self.layers[lasth]=pyglet.graphics.Batch() self.layers[lasth] = pyglet.graphics.Batch()
indices = range(len(layertemp[lasth][0]))#[[3*i,3*i+1,3*i+2] for i in xrange(len(facets))] indices = range(len(layertemp[lasth][0])) # [[3*i,3*i+1,3*i+2] for i in xrange(len(facets))]
self.vlists.append(self.layers[lasth].add_indexed(len(layertemp[lasth][0])//3, self.vlists.append(self.layers[lasth].add_indexed(len(layertemp[lasth][0]) // 3,
GL_TRIANGLES, GL_TRIANGLES,
None,#group, None, # group,
indices, indices,
('v3f/static', layertemp[lasth][0]), ('v3f/static', layertemp[lasth][0]),
('n3f/static', layertemp[lasth][1]))) ('n3f/static', layertemp[lasth][1])))
def genline(self, i, h, w):
def genline(self,i,h,w): S = i[0][:3]
S=i[0][:3] E = i[1][:3]
E=i[1][:3] v = map(lambda x, y: x - y, E, S)
v=map(lambda x,y:x-y,E,S) vlen = math.sqrt(float(sum(map(lambda a: a * a, v[:3]))))
vlen=math.sqrt(float(sum(map(lambda a:a*a, v[:3]))))
if vlen == 0:
if vlen==0: vlen = 0.01
vlen=0.01 sq2 = math.sqrt(2.0) / 2.0
sq2=math.sqrt(2.0)/2.0 htw = float(h) / w
htw=float(h)/w d = w / 2.0
d=w/2.0 if i[1][3] == i[0][3]:
if i[1][3]==i[0][3]: d = 0.05
d=0.05 points = [[d, 0, 0],
points=[[d,0,0], [sq2 * d, sq2 * d, 0],
[sq2*d,sq2*d,0], [0, d, 0],
[0,d,0], [-sq2 * d, sq2 * d, 0],
[-sq2*d,sq2*d,0], [-d, 0, 0],
[-d,0,0], [-sq2 * d, -sq2 * d, 0],
[-sq2*d,-sq2*d,0], [0, -d, 0],
[0,-d,0], [sq2 * d, -sq2 * d, 0]
[sq2*d,-sq2*d,0]
] ]
axis=stltool.cross([0,0,1],v) axis = stltool.cross([0, 0, 1], v)
alen=math.sqrt(float(sum(map(lambda a:a*a, v[:3])))) alen = math.sqrt(float(sum(map(lambda a: a * a, v[:3]))))
if alen>0: if alen > 0:
axis=map(lambda m:m/alen,axis) axis = map(lambda m: m / alen, axis)
angle=math.acos(v[2]/vlen) angle = math.acos(v[2] / vlen)
def vrot(v,axis,angle):
kxv=stltool.cross(axis,v) def vrot(v, axis, angle):
kdv=sum(map(lambda x,y:x*y,axis,v)) kxv = stltool.cross(axis, v)
return map(lambda x,y,z:x*math.cos(angle)+y*math.sin(angle)+z*kdv*(1.0-math.cos(angle)),v,kxv,axis) kdv = sum(map(lambda x, y: x * y, axis, v))
points=map(lambda x:vrot(x,axis,angle),points) return map(lambda x, y, z: x * math.cos(angle) + y * math.sin(angle) + z * kdv * (1.0 - math.cos(angle)), v, kxv, axis)
points=map(lambda x:[x[0],x[1],htw*x[2]],points)
points = map(lambda x: vrot(x, axis, angle), points)
def vadd(v,o): points = map(lambda x: [x[0], x[1], htw * x[2]], points)
return map(sum,zip(v,o))
spoints=map(lambda x:vadd(S,x),points) def vadd(v, o):
epoints=map(lambda x:vadd(E,x),points) return map(sum, zip(v, o))
return spoints,epoints,S,E spoints = map(lambda x: vadd(S, x), points)
epoints = map(lambda x: vadd(E, x), points)
def transform(self,line): return spoints, epoints, S, E
line=line.split(";")[0]
cur=self.prev[:] def transform(self, line):
if len(line)>0: line = line.split(";")[0]
cur = self.prev[:]
if len(line) > 0:
if "G1" in line or "G0" in line or "G92" in line: if "G1" in line or "G0" in line or "G92" in line:
if("X" in line): if("X" in line):
cur[0]=float(line.split("X")[1].split(" ")[0]) cur[0] = float(line.split("X")[1].split(" ")[0])
if("Y" in line): if("Y" in line):
cur[1]=float(line.split("Y")[1].split(" ")[0]) cur[1] = float(line.split("Y")[1].split(" ")[0])
if("Z" in line): if("Z" in line):
cur[2]=float(line.split("Z")[1].split(" ")[0]) cur[2] = float(line.split("Z")[1].split(" ")[0])
if("E" in line): if("E" in line):
cur[3]=float(line.split("E")[1].split(" ")[0]) cur[3] = float(line.split("E")[1].split(" ")[0])
if self.prev==cur: if self.prev == cur:
return None return None
if self.fline or "G92" in line: if self.fline or "G92" in line:
self.prev=cur self.prev = cur
self.fline=0 self.fline = 0
return None return None
else: else:
r=[self.prev,cur] r = [self.prev, cur]
self.prev=cur self.prev = cur
return r return r
def delete(self): def delete(self):
for i in self.vlists: for i in self.vlists:
i.delete() i.delete()
self.vlists=[] self.vlists = []
def trackball(p1x, p1y, p2x, p2y, r): def trackball(p1x, p1y, p2x, p2y, r):
TRACKBALLSIZE=r TRACKBALLSIZE = r
#float a[3]; /* Axis of rotation */ #float a[3]; /* Axis of rotation */
#float phi; /* how much to rotate about axis */ #float phi; /* how much to rotate about axis */
#float p1[3], p2[3], d[3]; #float p1[3], p2[3], d[3];
#float t; #float t;
if (p1x == p2x and p1y == p2y): if (p1x == p2x and p1y == p2y):
return [0.0,0.0,0.0,1.0] return [0.0, 0.0, 0.0, 1.0]
p1=[p1x,p1y,project_to_sphere(TRACKBALLSIZE,p1x,p1y)] p1 = [p1x, p1y, project_to_sphere(TRACKBALLSIZE, p1x, p1y)]
p2=[p2x,p2y,project_to_sphere(TRACKBALLSIZE,p2x,p2y)] p2 = [p2x, p2y, project_to_sphere(TRACKBALLSIZE, p2x, p2y)]
a=stltool.cross(p2,p1) a = stltool.cross(p2, p1)
d=map(lambda x,y:x-y,p1,p2) d = map(lambda x, y: x - y, p1, p2)
t = math.sqrt(sum(map(lambda x:x*x, d))) / (2.0*TRACKBALLSIZE) t = math.sqrt(sum(map(lambda x: x * x, d))) / (2.0 * TRACKBALLSIZE)
if (t > 1.0): t = 1.0 if (t > 1.0):
if (t < -1.0): t = -1.0 t = 1.0
if (t < -1.0):
t = -1.0
phi = 2.0 * math.asin(t) phi = 2.0 * math.asin(t)
return axis_to_quat(a,phi) return axis_to_quat(a, phi)
def vec(*args): def vec(*args):
return (GLfloat * len(args))(*args) return (GLfloat * len(args))(*args)
def axis_to_quat(a,phi):
def axis_to_quat(a, phi):
#print a, phi #print a, phi
lena=math.sqrt(sum(map(lambda x:x*x, a))) lena = math.sqrt(sum(map(lambda x: x * x, a)))
q=map(lambda x:x*(1/lena),a) q = map(lambda x: x * (1 / lena), a)
q=map(lambda x:x*math.sin(phi/2.0),q) q = map(lambda x: x * math.sin(phi / 2.0), q)
q.append(math.cos(phi/2.0)) q.append(math.cos(phi / 2.0))
return q return q
def build_rotmatrix(q): def build_rotmatrix(q):
m=(GLdouble * 16)() m = (GLdouble * 16)()
m[0] = 1.0 - 2.0 * (q[1] * q[1] + q[2] * q[2]) m[0] = 1.0 - 2.0 * (q[1] * q[1] + q[2] * q[2])
m[1] = 2.0 * (q[0] * q[1] - q[2] * q[3]); m[1] = 2.0 * (q[0] * q[1] - q[2] * q[3])
m[2] = 2.0 * (q[2] * q[0] + q[1] * q[3]); m[2] = 2.0 * (q[2] * q[0] + q[1] * q[3])
m[3] = 0.0; m[3] = 0.0
m[4] = 2.0 * (q[0] * q[1] + q[2] * q[3]); m[4] = 2.0 * (q[0] * q[1] + q[2] * q[3])
m[5]= 1.0 - 2.0 * (q[2] * q[2] + q[0] * q[0]); m[5] = 1.0 - 2.0 * (q[2] * q[2] + q[0] * q[0])
m[6] = 2.0 * (q[1] * q[2] - q[0] * q[3]); m[6] = 2.0 * (q[1] * q[2] - q[0] * q[3])
m[7] = 0.0; m[7] = 0.0
m[8] = 2.0 * (q[2] * q[0] - q[1] * q[3]); m[8] = 2.0 * (q[2] * q[0] - q[1] * q[3])
m[9] = 2.0 * (q[1] * q[2] + q[0] * q[3]); m[9] = 2.0 * (q[1] * q[2] + q[0] * q[3])
m[10] = 1.0 - 2.0 * (q[1] * q[1] + q[0] * q[0]); m[10] = 1.0 - 2.0 * (q[1] * q[1] + q[0] * q[0])
m[11] = 0.0; m[11] = 0.0
m[12] = 0.0; m[12] = 0.0
m[13] = 0.0; m[13] = 0.0
m[14] = 0.0; m[14] = 0.0
m[15] = 1.0; m[15] = 1.0
return m return m
def project_to_sphere(r, x, y): def project_to_sphere(r, x, y):
d = math.sqrt(x*x + y*y) d = math.sqrt(x * x + y * y)
if (d < r * 0.70710678118654752440): if (d < r * 0.70710678118654752440):
return math.sqrt(r*r - d*d) return math.sqrt(r * r - d * d)
else: else:
t = r / 1.41421356237309504880 t = r / 1.41421356237309504880
return t*t / d return t * t / d
def mulquat(q1,rq):
def mulquat(q1, rq):
return [q1[3] * rq[0] + q1[0] * rq[3] + q1[1] * rq[2] - q1[2] * rq[1], return [q1[3] * rq[0] + q1[0] * rq[3] + q1[1] * rq[2] - q1[2] * rq[1],
q1[3] * rq[1] + q1[1] * rq[3] + q1[2] * rq[0] - q1[0] * rq[2], q1[3] * rq[1] + q1[1] * rq[3] + q1[2] * rq[0] - q1[0] * rq[2],
q1[3] * rq[2] + q1[2] * rq[3] + q1[0] * rq[1] - q1[1] * rq[0], q1[3] * rq[2] + q1[2] * rq[3] + q1[0] * rq[1] - q1[1] * rq[0],
...@@ -436,38 +450,37 @@ def mulquat(q1,rq): ...@@ -436,38 +450,37 @@ def mulquat(q1,rq):
class TestGlPanel(GLPanel): class TestGlPanel(GLPanel):
def __init__(self, parent, size,id=wx.ID_ANY,): def __init__(self, parent, size, id=wx.ID_ANY):
super(TestGlPanel, self).__init__(parent, id, wx.DefaultPosition, size, 0) super(TestGlPanel, self).__init__(parent, id, wx.DefaultPosition, size, 0)
self.batches=[] self.batches = []
self.rot=0 self.rot = 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.initialized=1 self.initialized = 1
self.canvas.Bind(wx.EVT_MOUSEWHEEL,self.wheel) self.canvas.Bind(wx.EVT_MOUSEWHEEL, self.wheel)
self.parent=parent self.parent = parent
self.initpos=None self.initpos = None
self.dist=200 self.dist = 200
self.bedsize=[200,200] self.bedsize = [200, 200]
self.transv=[0, 0, -self.dist] self.transv = [0, 0, -self.dist]
self.basequat=[0,0,0,1] self.basequat = [0, 0, 0, 1]
wx.CallAfter(self.forceresize) wx.CallAfter(self.forceresize)
self.mousepos=[0,0] self.mousepos = [0, 0]
def double(self, event): def double(self, event):
p=event.GetPositionTuple() p = event.GetPositionTuple()
sz=self.GetClientSize() sz = self.GetClientSize()
v=map(lambda m,w,b:b*m/w,p,sz,self.bedsize) v = map(lambda m, w, b: b * m / w, p, sz, self.bedsize)
v[1]=self.bedsize[1]-v[1] v[1] = self.bedsize[1] - v[1]
v+=[300] v += [300]
print v print v
self.add_file("../prusa/metric-prusa/x-end-idler.stl",v) self.add_file("../prusa/metric-prusa/x-end-idler.stl", v)
def forceresize(self): def forceresize(self):
self.SetClientSize((self.GetClientSize()[0],self.GetClientSize()[1]+1)) self.SetClientSize((self.GetClientSize()[0], self.GetClientSize()[1] + 1))
self.SetClientSize((self.GetClientSize()[0],self.GetClientSize()[1]-1)) self.SetClientSize((self.GetClientSize()[0], self.GetClientSize()[1] - 1))
threading.Thread(target=self.update).start() threading.Thread(target=self.update).start()
self.initialized=0 self.initialized = 0
def move_shape(self, delta): def move_shape(self, delta):
"""moves shape (selected in l, which is list ListBox of shapes) """moves shape (selected in l, which is list ListBox of shapes)
...@@ -497,8 +510,8 @@ class TestGlPanel(GLPanel): ...@@ -497,8 +510,8 @@ class TestGlPanel(GLPanel):
with shift move viewport with shift move viewport
""" """
if event.Dragging() and event.LeftIsDown(): if event.Dragging() and event.LeftIsDown():
if self.initpos==None: if self.initpos == None:
self.initpos=event.GetPositionTuple() self.initpos = event.GetPositionTuple()
else: else:
if not event.ShiftDown(): if not event.ShiftDown():
currentpos = event.GetPositionTuple() currentpos = event.GetPositionTuple()
...@@ -507,69 +520,68 @@ class TestGlPanel(GLPanel): ...@@ -507,69 +520,68 @@ class TestGlPanel(GLPanel):
-(currentpos[1] - self.initpos[1]) -(currentpos[1] - self.initpos[1])
) )
self.move_shape(delta) self.move_shape(delta)
self.initpos=None self.initpos = None
return return
#print self.initpos #print self.initpos
p1=self.initpos p1 = self.initpos
self.initpos=None self.initpos = None
p2=event.GetPositionTuple() p2 = event.GetPositionTuple()
sz=self.GetClientSize() sz = self.GetClientSize()
p1x=(float(p1[0])-sz[0]/2)/(sz[0]/2) p1x = (float(p1[0]) - sz[0] / 2) / (sz[0] / 2)
p1y=-(float(p1[1])-sz[1]/2)/(sz[1]/2) p1y = -(float(p1[1]) - sz[1] / 2) / (sz[1] / 2)
p2x=(float(p2[0])-sz[0]/2)/(sz[0]/2) p2x = (float(p2[0]) - sz[0] / 2) / (sz[0] / 2)
p2y=-(float(p2[1])-sz[1]/2)/(sz[1]/2) p2y = -(float(p2[1]) - sz[1] / 2) / (sz[1] / 2)
#print p1x,p1y,p2x,p2y #print p1x,p1y,p2x,p2y
quat=trackball(p1x, p1y, p2x, p2y, -self.transv[2]/250.0) quat = trackball(p1x, p1y, p2x, p2y, -self.transv[2] / 250.0)
if self.rot: if self.rot:
self.basequat=mulquat(self.basequat,quat) self.basequat = mulquat(self.basequat, quat)
#else: #else:
glGetDoublev(GL_MODELVIEW_MATRIX,self.mvmat) glGetDoublev(GL_MODELVIEW_MATRIX, self.mvmat)
#self.basequat=quatx #self.basequat = quatx
mat=build_rotmatrix(self.basequat) mat = build_rotmatrix(self.basequat)
glLoadIdentity() glLoadIdentity()
glTranslatef(self.transv[0],self.transv[1],0) glTranslatef(self.transv[0], self.transv[1], 0)
glTranslatef(0,0,self.transv[2]) glTranslatef(0, 0, self.transv[2])
glMultMatrixd(mat) glMultMatrixd(mat)
glGetDoublev(GL_MODELVIEW_MATRIX,self.mvmat) glGetDoublev(GL_MODELVIEW_MATRIX, self.mvmat)
self.rot=1 self.rot = 1
elif event.ButtonUp(wx.MOUSE_BTN_LEFT): elif event.ButtonUp(wx.MOUSE_BTN_LEFT):
if self.initpos is not None: if self.initpos is not None:
self.initpos=None self.initpos = None
elif event.ButtonUp(wx.MOUSE_BTN_RIGHT): elif event.ButtonUp(wx.MOUSE_BTN_RIGHT):
if self.initpos is not None: if self.initpos is not None:
self.initpos=None self.initpos = None
elif event.Dragging() and event.RightIsDown() and event.ShiftDown(): elif event.Dragging() and event.RightIsDown() and event.ShiftDown():
if self.initpos is None: if self.initpos is None:
self.initpos=event.GetPositionTuple() self.initpos = event.GetPositionTuple()
else: else:
p1=self.initpos p1 = self.initpos
p2=event.GetPositionTuple() p2 = event.GetPositionTuple()
sz=self.GetClientSize() sz = self.GetClientSize()
p1=list(p1) p1 = list(p1)
p2=list(p2) p2 = list(p2)
p1[1]*=-1 p1[1] *= -1
p2[1]*=-1 p2[1] *= -1
self.transv=map(lambda x,y,z,c:c-self.dist*(x-y)/z, list(p1)+[0], list(p2)+[0], list(sz)+[1], self.transv) self.transv = map(lambda x, y, z, c: c - self.dist * (x - y) / z, list(p1) + [0], list(p2) + [0], list(sz) + [1], self.transv)
glLoadIdentity() glLoadIdentity()
glTranslatef(self.transv[0],self.transv[1],0) glTranslatef(self.transv[0], self.transv[1], 0)
glTranslatef(0,0,self.transv[2]) glTranslatef(0, 0, self.transv[2])
if(self.rot): if(self.rot):
glMultMatrixd(build_rotmatrix(self.basequat)) glMultMatrixd(build_rotmatrix(self.basequat))
glGetDoublev(GL_MODELVIEW_MATRIX,self.mvmat) glGetDoublev(GL_MODELVIEW_MATRIX, self.mvmat)
self.rot=1 self.rot = 1
self.initpos=None self.initpos = None
else: else:
#mouse is moving without a button press #mouse is moving without a button press
p=event.GetPositionTuple() p = event.GetPositionTuple()
sz=self.GetClientSize() sz = self.GetClientSize()
v=map(lambda m,w,b:b*m/w,p,sz,self.bedsize) v = map(lambda m, w, b: b * m / w, p, sz, self.bedsize)
v[1]=self.bedsize[1]-v[1] v[1] = self.bedsize[1] - v[1]
self.mousepos=v self.mousepos = v
def rotate_shape(self, angle): def rotate_shape(self, angle):
"""rotates acive shape """rotates acive shape
...@@ -582,17 +594,17 @@ class TestGlPanel(GLPanel): ...@@ -582,17 +594,17 @@ class TestGlPanel(GLPanel):
model = self.parent.models[name] model = self.parent.models[name]
model.rot += angle model.rot += angle
def wheel(self,event): def wheel(self, event):
"""react to mouse wheel actions: """react to mouse wheel actions:
rotate object rotate object
with shift zoom viewport with shift zoom viewport
""" """
z=event.GetWheelRotation() z = event.GetWheelRotation()
angle=10 angle = 10
if not event.ShiftDown(): if not event.ShiftDown():
i=self.parent.l.GetSelection() i = self.parent.l.GetSelection()
if i<0: if i < 0:
try: try:
self.parent.setlayerindex(z) self.parent.setlayerindex(z)
except: except:
...@@ -600,21 +612,21 @@ class TestGlPanel(GLPanel): ...@@ -600,21 +612,21 @@ class TestGlPanel(GLPanel):
return return
if z > 0: if z > 0:
self.rotate_shape(angle/2) self.rotate_shape(angle / 2)
else: else:
self.rotate_shape(-angle/2) self.rotate_shape(-angle / 2)
return return
if z > 0: if z > 0:
self.transv[2]+=angle self.transv[2] += angle
else: else:
self.transv[2]-=angle self.transv[2] -= angle
glLoadIdentity() glLoadIdentity()
glTranslatef(*self.transv) glTranslatef(*self.transv)
if(self.rot): if(self.rot):
glMultMatrixd(build_rotmatrix(self.basequat)) glMultMatrixd(build_rotmatrix(self.basequat))
glGetDoublev(GL_MODELVIEW_MATRIX,self.mvmat) glGetDoublev(GL_MODELVIEW_MATRIX, self.mvmat)
self.rot=1 self.rot = 1
def keypress(self, event): def keypress(self, event):
"""gets keypress events and moves/rotates acive shape""" """gets keypress events and moves/rotates acive shape"""
...@@ -647,50 +659,48 @@ class TestGlPanel(GLPanel): ...@@ -647,50 +659,48 @@ class TestGlPanel(GLPanel):
def update(self): def update(self):
while(1): while(1):
dt=0.05 dt = 0.05
time.sleep(0.05) time.sleep(0.05)
try: try:
wx.CallAfter(self.Refresh) wx.CallAfter(self.Refresh)
except: except:
return return
def anim(self,obj): def anim(self, obj):
g=50*9.8 g = 50 * 9.8
v=20 v = 20
dt=0.05 dt = 0.05
basepos=obj.offsets[2] basepos = obj.offsets[2]
obj.offsets[2]+=obj.animoffset obj.offsets[2] += obj.animoffset
while obj.offsets[2]>-1: while obj.offsets[2] > -1:
time.sleep(dt) time.sleep(dt)
obj.offsets[2]-=v*dt obj.offsets[2] -= v * dt
v+=g*dt v += g * dt
if(obj.offsets[2]<0): if(obj.offsets[2] < 0):
obj.scale[2]*=1-3*dt obj.scale[2] *= 1 - 3 * dt
#return #return
v=v/4 v = v / 4
while obj.offsets[2]<basepos: while obj.offsets[2] < basepos:
time.sleep(dt) time.sleep(dt)
obj.offsets[2]+=v*dt obj.offsets[2] += v * dt
v-=g*dt v -= g * dt
obj.scale[2]*=1+5*dt obj.scale[2] *= 1 + 5 * dt
obj.scale[2]=1.0 obj.scale[2] = 1.0
def create_objects(self): def create_objects(self):
'''create opengl objects when opengl is initialized''' '''create opengl objects when opengl is initialized'''
self.initialized=1 self.initialized = 1
wx.CallAfter(self.Refresh) wx.CallAfter(self.Refresh)
def drawmodel(self,m,n): def drawmodel(self, m, n):
batch = pyglet.graphics.Batch() batch = pyglet.graphics.Batch()
stl = stlview(m.facets, batch=batch) stl = stlview(m.facets, batch=batch)
m.batch=batch m.batch = batch
m.animoffset=300 m.animoffset = 300
#print m #print m
#threading.Thread(target=self.anim,args=(m,)).start() #threading.Thread(target = self.anim, args = (m, )).start()
wx.CallAfter(self.Refresh) wx.CallAfter(self.Refresh)
def update_object_resize(self): def update_object_resize(self):
'''called when the window recieves only if opengl is initialized''' '''called when the window recieves only if opengl is initialized'''
pass pass
...@@ -704,7 +714,7 @@ class TestGlPanel(GLPanel): ...@@ -704,7 +714,7 @@ class TestGlPanel(GLPanel):
#glLoadIdentity() #glLoadIdentity()
#print list(self.pmat) #print list(self.pmat)
if self.rot==1: if self.rot == 1:
glLoadIdentity() glLoadIdentity()
glMultMatrixd(self.mvmat) glMultMatrixd(self.mvmat)
else: else:
...@@ -712,74 +722,74 @@ class TestGlPanel(GLPanel): ...@@ -712,74 +722,74 @@ class TestGlPanel(GLPanel):
glTranslatef(*self.transv) glTranslatef(*self.transv)
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))
glBegin(GL_LINES) glBegin(GL_LINES)
glNormal3f(0,0,1) glNormal3f(0, 0, 1)
rows=10 rows = 10
cols=10 cols = 10
zheight=50 zheight = 50
for i in xrange(-rows,rows+1): for i in xrange(-rows, rows + 1):
if i%5==0: if i % 5 == 0:
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.6, 0.6, 0.6, 1)) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.6, 0.6, 0.6, 1))
else: else:
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))
glVertex3f(10*-cols, 10*i,0) glVertex3f(10 * -cols, 10 * i, 0)
glVertex3f(10*cols, 10*i,0) glVertex3f(10 * cols, 10 * i, 0)
for i in xrange(-cols,cols+1): for i in xrange(-cols, cols + 1):
if i%5==0: if i % 5 == 0:
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.6, 0.6, 0.6, 1)) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.6, 0.6, 0.6, 1))
else: else:
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))
glVertex3f(10*i, 10*-rows,0) glVertex3f(10 * i, 10 * -rows, 0)
glVertex3f(10*i, 10*rows,0) glVertex3f(10 * i, 10 * rows, 0)
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.6, 0.6, 0.6, 1)) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.6, 0.6, 0.6, 1))
glVertex3f(10*-cols, 10*-rows,0) glVertex3f(10 * -cols, 10 * -rows, 0)
glVertex3f(10*-cols, 10*-rows,zheight) glVertex3f(10 * -cols, 10 * -rows, zheight)
glVertex3f(10*cols, 10*rows,0) glVertex3f(10 * cols, 10 * rows, 0)
glVertex3f(10*cols, 10*rows,zheight) glVertex3f(10 * cols, 10 * rows, zheight)
glVertex3f(10*cols, 10*-rows,0) glVertex3f(10 * cols, 10 * -rows, 0)
glVertex3f(10*cols, 10*-rows,zheight) glVertex3f(10 * cols, 10 * -rows, zheight)
glVertex3f(10*-cols, 10*rows,0) glVertex3f(10 * -cols, 10 * rows, 0)
glVertex3f(10*-cols, 10*rows,zheight) glVertex3f(10 * -cols, 10 * rows, zheight)
glVertex3f(10*-cols, 10*rows,zheight) glVertex3f(10 * -cols, 10 * rows, zheight)
glVertex3f(10*cols, 10*rows,zheight) glVertex3f(10 * cols, 10 * rows, zheight)
glVertex3f(10*cols, 10*rows,zheight) glVertex3f(10 * cols, 10 * rows, zheight)
glVertex3f(10*cols, 10*-rows,zheight) glVertex3f(10 * cols, 10 * -rows, zheight)
glVertex3f(10*cols, 10*-rows,zheight) glVertex3f(10 * cols, 10 * -rows, zheight)
glVertex3f(10*-cols, 10*-rows,zheight) glVertex3f(10 * -cols, 10 * -rows, zheight)
glVertex3f(10*-cols, 10*-rows,zheight) glVertex3f(10 * -cols, 10 * -rows, zheight)
glVertex3f(10*-cols, 10*rows,zheight) glVertex3f(10 * -cols, 10 * rows, zheight)
glEnd() glEnd()
glPushMatrix() glPushMatrix()
glTranslatef(self.mousepos[0]-self.bedsize[0]/2,self.mousepos[1]-self.bedsize[1]/2,0) glTranslatef(self.mousepos[0] - self.bedsize[0] / 2, self.mousepos[1] - self.bedsize[1] / 2, 0)
glBegin(GL_TRIANGLES) glBegin(GL_TRIANGLES)
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(1, 0, 0, 1)) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(1, 0, 0, 1))
glNormal3f(0,0,1) glNormal3f(0, 0, 1)
glVertex3f(2,2,0) glVertex3f(2, 2, 0)
glVertex3f(-2,2,0) glVertex3f(-2, 2, 0)
glVertex3f(-2,-2,0) glVertex3f(-2, -2, 0)
glVertex3f(2,-2,0) glVertex3f(2, -2, 0)
glVertex3f(2,2,0) glVertex3f(2, 2, 0)
glVertex3f(-2,-2,0) glVertex3f(-2, -2, 0)
glEnd() glEnd()
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.3, 0.7, 0.5, 1)) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.3, 0.7, 0.5, 1))
#glTranslatef(0,40,0) #glTranslatef(0, 40, 0)
glPopMatrix() glPopMatrix()
glPushMatrix() glPushMatrix()
glTranslatef(-100,-100,0) glTranslatef(-100, -100, 0)
for i in self.parent.models.values(): for i in self.parent.models.values():
glPushMatrix() glPushMatrix()
glTranslatef(*(i.offsets)) glTranslatef(*(i.offsets))
glRotatef(i.rot,0.0,0.0,1.0) glRotatef(i.rot, 0.0, 0.0, 1.0)
glScalef(*i.scale) glScalef(*i.scale)
try: try:
if i.curlayer in i.gc.layers: if i.curlayer in i.gc.layers:
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.13, 0.37, 0.25, 1)) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.13, 0.37, 0.25, 1))
[i.gc.layers[j].draw() for j in i.gc.layers.keys() if j<i.curlayer] [i.gc.layers[j].draw() for j in i.gc.layers.keys() if j < i.curlayer]
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.5, 0.6, 0.9, 1)) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.5, 0.6, 0.9, 1))
b=i.gc.layers[i.curlayer] b = i.gc.layers[i.curlayer]
b.draw() b.draw()
else: else:
i.batch.draw() i.batch.draw()
...@@ -788,69 +798,69 @@ class TestGlPanel(GLPanel): ...@@ -788,69 +798,69 @@ class TestGlPanel(GLPanel):
glPopMatrix() glPopMatrix()
glPopMatrix() glPopMatrix()
#print "drawn batch" #print "drawn batch"
class GCFrame(wx.Frame): class GCFrame(wx.Frame):
'''A simple class for using OpenGL with wxPython.''' '''A simple class for using OpenGL with wxPython.'''
def __init__(self, parent, ID, title, pos=wx.DefaultPosition, def __init__(self, parent, ID, title, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE): size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE):
super(GCFrame, self).__init__(parent, ID, title, pos, (size[0]+150,size[1]), style) super(GCFrame, self).__init__(parent, ID, title, pos, (size[0] + 150, size[1]), style)
class d: class d:
def GetSelection(self): def GetSelection(self):
return -1 return wx.NOT_FOUND
self.p=self self.p = self
m=d() m = d()
m.offsets=[0,0,0] m.offsets = [0, 0, 0]
m.rot=0 m.rot = 0
m.curlayer=0.0 m.curlayer = 0.0
m.scale=[1.,1.,1.] m.scale = [1.0, 1.0, 1.0]
m.batch=pyglet.graphics.Batch() m.batch = pyglet.graphics.Batch()
m.gc=gcview([], batch=m.batch) m.gc = gcview([], batch=m.batch)
self.models={"":m} self.models = {"": m}
self.l=d() self.l = d()
self.modelindex=0 self.modelindex = 0
self.GLPanel1 = TestGlPanel(self,size) self.GLPanel1 = TestGlPanel(self, size)
def addfile(self,gcode=[]): def addfile(self, gcode=[]):
self.models[""].gc.delete() self.models[""].gc.delete()
self.models[""].gc=gcview(gcode, batch=self.models[""].batch) self.models[""].gc = gcview(gcode, batch=self.models[""].batch)
def clear(self): def clear(self):
self.models[""].gc.delete() self.models[""].gc.delete()
self.models[""].gc=gcview([], batch=self.models[""].batch) self.models[""].gc = gcview([], batch=self.models[""].batch)
def Show(self, arg=True):
def Show(self,arg=True): wx.Frame.Show(self, arg)
wx.Frame.Show(self,arg) self.SetClientSize((self.GetClientSize()[0], self.GetClientSize()[1] + 1))
self.SetClientSize((self.GetClientSize()[0],self.GetClientSize()[1]+1)) self.SetClientSize((self.GetClientSize()[0], self.GetClientSize()[1] - 1))
self.SetClientSize((self.GetClientSize()[0],self.GetClientSize()[1]-1))
self.Refresh() self.Refresh()
wx.FutureCall(500,self.GLPanel1.forceresize) wx.FutureCall(500, self.GLPanel1.forceresize)
#threading.Thread(target=self.update).start() #threading.Thread(target = self.update).start()
#self.initialized=0 #self.initialized = 0
def setlayerindex(self,z): def setlayerindex(self, z):
m=self.models[""] m = self.models[""]
mlk=sorted(m.gc.layers.keys()) mlk = sorted(m.gc.layers.keys())
if z>0 and self.modelindex<len(mlk)-1: if z > 0 and self.modelindex < len(mlk) - 1:
self.modelindex+=1 self.modelindex += 1
if z<0 and self.modelindex>0: if z < 0 and self.modelindex > 0:
self.modelindex-=1 self.modelindex -= 1
m.curlayer=mlk[self.modelindex] m.curlayer = mlk[self.modelindex]
wx.CallAfter(self.SetTitle,"Gcode view, shift to move. Layer %d, Z=%f"%(self.modelindex,m.curlayer)) wx.CallAfter(self.SetTitle, "Gcode view, shift to move. Layer %d, Z = %f" % (self.modelindex, m.curlayer))
def main(): def main():
app = wx.App(redirect=False) app = wx.App(redirect=False)
frame = GCFrame(None, wx.ID_ANY, 'Gcode view, shift to move view, mousewheel to set layer', size=(400,400)) frame = GCFrame(None, wx.ID_ANY, 'Gcode view, shift to move view, mousewheel to set layer', size=(400, 400))
frame.addfile(list(open("carriage dump_export.gcode"))) frame.addfile(list(open("carriage dump_export.gcode")))
#frame = wx.Frame(None, -1, "GL Window", size=(400,400)) #frame = wx.Frame(None, -1, "GL Window", size=(400, 400))
#panel = TestGlPanel(frame) #panel = TestGlPanel(frame)
#frame.Show(True) #frame.Show(True)
#app.MainLoop() #app.MainLoop()
app.Destroy() app.Destroy()
if __name__=="__main__": if __name__ == "__main__":
import cProfile import cProfile
print cProfile.run("main()") print cProfile.run("main()")
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