def drawXAxis(self, vlimits): xmin, ymin, zmin = self.limits[0] xmax, ymax, zmax = self.limits[1] difference_vector = self.limits[1] - self.limits[0] deltax, deltay, deltaz = self.delta * (difference_vector) begin = [[xmin, ymin - deltay, zmin - deltaz], [xmin, ymax + deltay, zmin - deltaz], [xmin, ymin - deltay, zmax + deltaz], [xmin, ymax + deltay, zmax + deltaz]] end = [[xmax, ymin - deltay, zmin - deltaz], [xmax, ymax + deltay, zmin - deltaz], [xmax, ymin - deltay, zmax + deltaz], [xmax, ymax + deltay, zmax + deltaz]] X = [] for i in range(4): X.append([GLU.gluProject(*begin[i]), GLU.gluProject(*end[i])]) #print "0->0, 1", vlimits[0][0], vlimits[1][0] #print "1->0, 1", vlimits[0][1], vlimits[1][1] possible = [1, 1, 1, 1] i = 0 for item in X: if (item[0][0] > vlimits[0][0]) and (item[0][0] < vlimits[1][0]) and \ (item[0][1] > vlimits[0][1]) and (item[0][1] < vlimits[1][1]): possible[i] = 0 elif (item[1][0] > vlimits[0][0]) and (item[1][0] < vlimits[1][0]) and \ (item[1][1] > vlimits[0][1]) and (item[1][1] < vlimits[1][1]): possible[i] = 0 i += 1 #print "POSSIBLE = ", possible j = None for i in range(4): if possible[i]: if j is None: j = i else: if X[i][0][0] > X[j][0][0]: j = i if j is not None: i = j GL.glColor3f(0.5, 0.0, 0.0) #RED for X Axis self.parent.renderText(begin[i][0], begin[i][1], begin[i][2], "%.3f" % (begin[i][0]), self.parent.font(), 2000) self.parent.renderText(end[i][0], end[i][1], end[i][2], "%.3f" % (end[i][0]), self.parent.font(), 2000) return
def drawZAxis(self, vlimits): xmin, ymin, zmin = self.limits[0] xmax, ymax, zmax = self.limits[1] difference_vector = self.limits[1] - self.limits[0] deltax, deltay, deltaz = self.delta * (difference_vector) begin = [[xmin - deltax, ymin - deltay, zmin], [xmin - deltax, ymax + deltay, zmin], [xmax + deltax, ymin - deltay, zmin], [xmax + deltax, ymax + deltay, zmin]] end = [[xmin - deltax, ymin - deltay, zmax], [xmin - deltax, ymax + deltay, zmax], [xmax + deltax, ymin - deltay, zmax], [xmax + deltax, ymax + deltay, zmax]] X = [] for i in range(4): X.append([GLU.gluProject(*begin[i]), GLU.gluProject(*end[i])]) possible = [1, 1, 1, 1] i = 0 for item in X: if (item[0][0] > vlimits[0][0]) and (item[0][0] < vlimits[1][0]) and \ (item[0][1] > vlimits[0][1]) and (item[0][1] < vlimits[1][1]): possible[i] = 0 elif (item[1][0] > vlimits[0][0]) and (item[1][0] < vlimits[1][0]) and \ (item[1][1] > vlimits[0][1]) and (item[1][1] < vlimits[1][1]): possible[i] = 0 i += 1 j = None for i in range(4): if possible[i]: #if pow(pow(X[i][1][0] - X[i][0][0], 2) + pow(X[i][1][1] - X[i][0][1], 2),0.5) > 30: if j is None: j = i else: if X[i][0][0] > X[j][0][0]: j = i if j is not None: i = j GL.glColor3f(0.0, 0.0, 0.5) #BLUE for Z Axis self.parent.renderText(begin[i][0], begin[i][1], begin[i][2], "%.3f" % (begin[i][2]), self.parent.font(), 2000) self.parent.renderText(end[i][0], end[i][1], end[i][2], "%.3f" % (end[i][2]), self.parent.font(), 2000) return
def paintGL(self, p0=0, p1=None, drawOpts=DRAWOPT_DEFAULT): ''' :param drawOpts: OR combination of draw flags. default is :data:`UI.DRAWOPT_DEFAULT` ''' is_click = (p1 is not None) if p1 is None: p1 = len(self) assert(p0 >= 0 and p1 >= p0 and p1 <= len(self.vertices)) if p1 <= p0: return # draw nothing GL.glDisable(GL.GL_TEXTURE_2D) GL.glShadeModel(GL.GL_SMOOTH) GL.glColor3f(*self.color) GL.glLineWidth(1) GL.glEnableClientState(GL.GL_VERTEX_ARRAY) GL.glVertexPointerf(self.vertices) GL.glDrawElementsui(GL.GL_LINES, self.idx) if self.graph is not None: GL.glColor3f(0,1,0) GL.glLineWidth(5) GL.glVertexPointerf(self.vertices) GL.glDrawElementsui(GL.GL_LINES, self.graph) GL.glColor3f(1,0,0) GL.glPointSize(10) GL.glVertexPointerf(self.vertices) GL.glDrawArrays(GL.GL_POINTS, 0, len(self.vertices)) if self.name and DRAWOPT_LABELS & drawOpts: GL.glColor3f(*self.color) phi = np.max(self.vertices,axis=0) plo = np.min(self.vertices,axis=0) if bool(GL.glWindowPos2f): Mmat = GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX) Pmat = GL.glGetDoublev(GL.GL_PROJECTION_MATRIX) viewport = GL.glGetIntegerv(GL.GL_VIEWPORT) p = GLU.gluProject((phi[0]+plo[0])*0.5,phi[1] + 300.0,(phi[2]+plo[2])*0.5, Mmat, Pmat, viewport) if self.nameWidth is None: self.nameWidth = sum([GLUT.glutBitmapWidth(self.font, ord(x)) for x in self.name]) GL.glWindowPos2f(p[0] - 0.5*self.nameWidth,p[1]) else: GL.glRasterPos3f((phi[0]+plo[0])*0.5,phi[1] + 300.0,(phi[2]+plo[2])*0.5) GLUT.glutBitmapString(self.font, self.name) if self.names and DRAWOPT_LABELS & drawOpts: if self.nameWidths is None: self.nameWidths = [sum([GLUT.glutBitmapWidth(self.font, ord(x)) for x in name]) for name in self.names] GL.glColor3f(*self.color) Mmat = GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX) Pmat = GL.glGetDoublev(GL.GL_PROJECTION_MATRIX) viewport = GL.glGetIntegerv(GL.GL_VIEWPORT) for ni,(name,v,w) in enumerate(zip(self.names, self.vertices, self.nameWidths)): if bool(GL.glWindowPos2f): p = GLU.gluProject(v[0],v[1]+10+ni*0.1,v[2], Mmat, Pmat, viewport) GL.glWindowPos2f(p[0] - 0.5*w,p[1]) else: GL.glRasterPos3f(v,(phi[2]+plo[2])*0.5) GLUT.glutBitmapString(self.font, name) GL.glDisableClientState(GL.GL_VERTEX_ARRAY)
def OnDraw(self): vv.OrientableMesh.OnDraw(self) if self._screenVec is None: pos1 = [int(s/2) for s in reversed(self.translation.data.flatten())] pos2 = [s for s in pos1] pos2[0] += 1 # screen1 = glu.gluProject(pos1[2], pos1[1], pos1[0]) screen2 = glu.gluProject(pos2[2], pos2[1], pos2[0]) # self._screenVec = screen2[0]-screen1[0], screen1[1]-screen2[1]
def convertToViewportLimits(self, limits): xmin, ymin, zmin = limits[0] xmax, ymax, zmax = limits[1] limits = [] limits.append(GLU.gluProject(xmin, ymin, zmin)) limits.append(GLU.gluProject(xmin, ymin, zmax)) limits.append(GLU.gluProject(xmin, ymax, zmin)) limits.append(GLU.gluProject(xmin, ymax, zmax)) limits.append(GLU.gluProject(xmax, ymin, zmin)) limits.append(GLU.gluProject(xmax, ymin, zmax)) limits.append(GLU.gluProject(xmax, ymax, zmin)) limits.append(GLU.gluProject(xmax, ymax, zmax)) lminx, lminy, lminz = limits[0] lmaxx, lmaxy, lmaxz = limits[0] for i in range(len(limits)): x, y, z = limits[i] if x < lminx: lminx = x elif x > lmaxx: lmaxx = x if y < lminy: lminy = y elif y > lmaxy: lmaxy = y if z < lminz: lminz = z elif z > lmaxz: lmaxz = z return [[lminx, lminy, lminz], [lmaxx, lmaxy, lmaxz]]
def OnDraw(self): # get screen position and store tmp = glu.gluProject(self._x, self._y, self._z) self._screenx, self._screeny, self._screenz = tuple(tmp) # make integer (to prevent glitchy behaviour), but not z! self._screenx = int(self._screenx + 0.5) self._screeny = int(self._screeny + 0.5)
def OnDraw(self): # get screen position and store tmp = glu.gluProject(self._x, self._y, self._z) self._screenx, self._screeny, self._screenz = tuple(tmp) # make integer (to prevent glitchy behaviour), but not z! self._screenx = int(self._screenx+0.5) self._screeny = int(self._screeny+0.5)
def OnDraw(self, fast=False): # Draw the texture. # set color to white, otherwise with no shading, there is odd scaling gl.glColor3f(1.0,1.0,1.0) # Enable texture, so that it has a corresponding OpenGl texture. # Binding is done by the shader self._texture1.Enable(-1) self.shader.SetUniform('texture', self._texture1) # _texture._shape is a good indicator of a valid texture if not self._texture1._shape: return if self.shader.isUsable and self.shader.hasCode: # fragment shader on -> anti-aliasing self.shader.Enable() else: # Fixed funcrion pipeline self.shader.EnableTextureOnly('texture') # do the drawing! self._DrawQuads() gl.glFlush() # clean up self.shader.Disable() # Draw outline? clr = self._edgeColor if self._interact_down or self._interact_over: clr = self._edgeColor2 if clr: self._DrawQuads(clr) # Get screen vector? if self._screenVec is None: pos1 = [int(s/2) for s in self._dataRef3D.shape] pos2 = [s for s in pos1] pos2[self._axis] += 1 # screen1 = glu.gluProject(pos1[2], pos1[1], pos1[0]) screen2 = glu.gluProject(pos2[2], pos2[1], pos2[0]) # self._screenVec = screen2[0]-screen1[0], screen1[1]-screen2[1]
def paintGL(self, ci, cameraInterest, p0=0, p1=None, drawOpts=DRAWOPT_DETECTIONS): ''' :param drawOpts: OR combination of draw flags. default is :data:`UI.DRAWOPT_DETECTIONS` ''' if ci < 0 or ci + 1 >= len(self.bounds): return if not DRAWOPT_DETECTIONS & drawOpts or not self.visible: return if p1 is None or p1 > self.len(ci): p1 = self.len(ci) x, s = self.vertices, self.bounds x2ds = x[s[ci]:s[ci + 1]][p0:p1] plot = np.zeros((len(x2ds), 3), dtype=np.float32) plot[:, :2] = x2ds plot[:, 2] = -1.0 plot *= cameraInterest GL.glDisable(GL.GL_DEPTH_TEST) GL.glPointSize(self.pointSize) GL.glEnable(GL.GL_BLEND) if self.colours.any(): GL.glEnableClientState(GL.GL_COLOR_ARRAY) GL.glColorPointerf(self.colours[s[ci]:s[ci + 1]][p0:p1]) else: GL.glColor4f(*self.colour) GL.glEnableClientState(GL.GL_VERTEX_ARRAY) GL.glVertexPointerf(plot) GL.glDrawArrays(GL.GL_POINTS, 0, len(plot)) GL.glDisableClientState(GL.GL_VERTEX_ARRAY) GL.glEnable(GL.GL_DEPTH_TEST) GL.glDisable(GL.GL_BLEND) GL.glDisableClientState(GL.GL_COLOR_ARRAY) drawLabels = DRAWOPT_LABELS & drawOpts if self.names is not None and drawLabels: nameWidth = [ sum([GLUT.glutBitmapWidth(self.font, ord(x)) for x in name]) for name in self.names ] GL.glColor4f(*self.fontColour) Mmat = GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX) Pmat = GL.glGetDoublev(GL.GL_PROJECTION_MATRIX) viewport = GL.glGetIntegerv(GL.GL_VIEWPORT) for name, v, w in zip(self.names, self.vertices, nameWidth)[s[ci]:s[ci + 1]][p0:p1]: if bool(GL.glWindowPos2f): p = GLU.gluProject(v[0], v[1], -1.0, Mmat, Pmat, viewport) GL.glWindowPos2f(p[0] - 0.5 * w, p[1]) else: GL.glRasterPos3f(v[0], v[1] + 10, v[2]) GLUT.glutBitmapString(self.font, name)
def project(self, x, y, z, auto_flip_vertical=True): modelview_mat = GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX) projection_mat = GL.glGetDoublev(GL.GL_PROJECTION_MATRIX) viewport = GL.glGetIntegerv(GL.GL_VIEWPORT) ret = GLU.gluProject(x, y, z, modelview_mat, projection_mat, viewport) ret = list(ret) if auto_flip_vertical: ret[1] = viewport[-1] - ret[1] return ret
def canvas2pix(self, pos): """Takes a 3-tuple of (cx, cy, cz) in canvas coordinates and gives the (x, y, z) pixel coordinates in the window. """ x, y, z = pos mm = gl.glGetDoublev(gl.GL_MODELVIEW_MATRIX) pm = gl.glGetDoublev(gl.GL_PROJECTION_MATRIX) vp = gl.glGetIntegerv(gl.GL_VIEWPORT) pt = glu.gluProject(x, y, z, mm, pm, vp) return pt
def worldToScreen(self, x, y, flip): # project the point to screen point = glu.gluProject(x, y, 1.0, self.model_view, self.proj, self.view) # -0.75 -> pos_y0 if flip: sx = round(point[0]) sy = round(self.view[3] - point[1]) return ([sx, sy]) else: return ([point[0], point[1]])
def fkt_3DPosToWinPos(self, x, y, z): point = [None, None, None] # result point modelview = GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX) # get the modelview info projection = GL.glGetDoublev(GL.GL_PROJECTION_MATRIX) # get the projection matrix info viewport = GL.glGetIntegerv(GL.GL_VIEWPORT) # get the viewport info # in OpenGL y soars (steigt) from bottom (0) to top y_new = y point[0], point[1], point[2] = GLU.gluProject(x, y_new, z, modelview, projection, viewport) point[1] = self.height -point[1] return point
def project(self,x,y,z,locked=False): "Map the object coordinates (x,y,z) to window coordinates.""" locked=False if locked: model,proj,view = self.projection_matrices else: self.makeCurrent() self.camera.loadProjection() model = GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX) proj = GL.glGetDoublev(GL.GL_PROJECTION_MATRIX) view = GL.glGetIntegerv(GL.GL_VIEWPORT) winx,winy,winz = GLU.gluProject(x,y,z,model,proj,view) return winx,winy,winz return self.camera.project(x,y,z)
def project(self, x, y, z, locked=False): "Map the object coordinates (x,y,z) to window coordinates." "" locked = False if locked: model, proj, view = self.projection_matrices else: self.makeCurrent() self.camera.loadProjection() model = GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX) proj = GL.glGetDoublev(GL.GL_PROJECTION_MATRIX) view = GL.glGetIntegerv(GL.GL_VIEWPORT) winx, winy, winz = GLU.gluProject(x, y, z, model, proj, view) return winx, winy, winz return self.camera.project(x, y, z)
def display(self): """Display texture. """ if self._dirty: depth = oglu.gluProject(*self._point)[2] if depth != self._depth: bottomleft = oglu.gluUnProject(0, 0, depth) bottomright = oglu.gluUnProject(self._winSize[0], 0, depth) topleft = oglu.gluUnProject(0, self._winSize[1], depth) topright = oglu.gluUnProject(self._winSize[0], self._winSize[1], depth) self.dims = topleft, topright, bottomright, bottomleft width = topright[0] - topleft[0] height = topright[1] - bottomright[1] self._qdims = topleft[0], topleft[1], width, height self._depth = depth LaminaScreenSurface.display(self)
def display(self): """Display texture. """ if self._dirty: depth = oglu.gluProject(*self._point)[2] if depth != self._depth: bottomleft = oglu.gluUnProject(0,0,depth) bottomright = oglu.gluUnProject(self._winSize[0],0,depth) topleft = oglu.gluUnProject(0,self._winSize[1],depth) topright = oglu.gluUnProject(self._winSize[0],self._winSize[1],depth) self.dims = topleft, topright, bottomright, bottomleft width = topright[0] - topleft[0] height = topright[1] - bottomright[1] self._qdims = topleft[0], topleft[1], width, height self._depth = depth LaminaScreenSurface.display(self)
def world_to_screen(app, world_x, world_y, world_z): """ Return 2D screen pixel space coordinates for given 3D (float) world space coordinates. """ pjm = np.matrix(app.camera.projection_matrix, dtype=np.float64) vm = np.matrix(app.camera.view_matrix, dtype=np.float64) # viewport tuple order should be same as glGetFloatv(GL_VIEWPORT) viewport = (0, 0, app.window_width, app.window_height) try: x, y, z = GLU.gluProject(world_x, world_y, world_z, vm, pjm, viewport) except: x, y, z = 0, 0, 0 app.log('GLU.gluProject failed!') # does Z mean anything here? return x, y
def tkTranslate(self, event): """Perform translation of scene.""" self.activate() # Scale mouse translations to object viewplane so object tracks with mouse win_height = max(1, self.winfo_height()) obj_c = (self.xcenter, self.ycenter, self.zcenter) win = GLU.gluProject(obj_c[0], obj_c[1], obj_c[2]) obj = GLU.gluUnProject(win[0], win[1] + 0.5 * win_height, win[2]) dist = math.sqrt(v3distsq(obj, obj_c)) scale = abs(dist / (0.5 * win_height)) glTranslateScene(scale, event.x, event.y, self.xmouse, self.ymouse) self.tkRedraw() self.tkRecordMouse(event)
def ClickUnitCheck(self, screenPos, worldPos, proj, screenSize): #print "clickScreenPos", screenPos #print "at worldPos", worldPos #Get unit nearest click position getNearby = events.Event("getNearbyUnits") getNearby.pos = worldPos getNearby.notFaction = None nearbyRet = self.mediator.Send(getNearby) bestUuid, bestDist = None, None for ret in nearbyRet: if ret is None: continue assert len(ret) == 2 bestUuid, bestDist = ret #print "best unit", bestUuid, bestDist #Get position of unit screenDist = None if bestUuid: getPos = events.Event("getpos") getPos.objId = bestUuid getPosRet = self.mediator.Send(getPos) assert len(getPosRet) == 1 nearestUnitWorldPos = getPosRet[0] #print "at worldPos", nearestUnitWorldPos #Get cartesian position cartPos = proj.ProjDeg(*nearestUnitWorldPos) #print "cartPos", cartPos #Get screen coordinates of nearest unit unitScreenPos = GLU.gluProject(*cartPos) #print "at screenPos", unitScreenPos unitScreenPos2D = np.array((unitScreenPos[0], unitScreenPos[1])) glScreenPos = (screenPos[0], screenSize[1] - screenPos[1]) screenDist = np.linalg.norm(unitScreenPos2D - glScreenPos, ord=2) return bestUuid, bestDist, screenDist
def _GetCords(self): """ _GetCords() Get a pointset of the coordinates of the wobject. This is used for drawing the quads and lines using a vertex array. """ # Can we reuse buffered coordinates? if self._cordsBuffer is not None: return self._cordsBuffer # Get ranges in world coords rangex, rangey = self._GetRangesInWorldCords() # Project two points to use in OnDrawScreen screen1 = glu.gluProject(rangex.min, rangey.min, 0) screen2 = glu.gluProject(rangex.max, rangey.max, 0) # Calculate world-distance of a screendistance of self._barwidth # and then do drawing here (not in OnDrawScreen), otherwise I won't # be able to detect picking!! onePixelx = rangex.range / (screen2[0] - screen1[0]) onePixely = rangey.range / (screen2[1] - screen1[1]) # Get coords tmp = self._barWidth x1, x2, xd = rangex.min, rangex.max, onePixelx * tmp y1, y2, yd = rangey.min, rangey.max, onePixely * tmp if yd < 0: y1, y2 = y2, y1 # axis flipped # Definition of the coordinate indices: # # 12 11 10 15 # 4 0 ----- 3 9 # | | # | | # 5 1------ 2 8 # 13 6 7 14 # # Make coords pp = Pointset(2) # pp.append(x1, y1) pp.append(x1, y2) pp.append(x2, y2) pp.append(x2, y1) # pp.append(x1 - xd, y1) pp.append(x1 - xd, y2) pp.append(x1, y2 + yd) pp.append(x2, y2 + yd) # pp.append(x2 + xd, y2) pp.append(x2 + xd, y1) pp.append(x2, y1 - yd) pp.append(x1, y1 - yd) # pp.append(x1 - xd, y1 - yd) pp.append(x1 - xd, y2 + yd) pp.append(x2 + xd, y2 + yd) pp.append(x2 + xd, y1 - yd) # Done self._cordsBuffer = pp return pp
def getPoint(self, pt): """Get x,y coords of pt in 3d space.""" pt2 = oglu.gluProject(*pt) return pt2[0], pt2[1]
def mouseReleaseEvent(self, event): global winx_inside, winy_inside, winz_inside, indices_selected, indices_all self.dragging = False if len(self.lasso_list) >= 3: points = np.array(self.lasso_list) hull = scipy.spatial.ConvexHull(points) hullx = points[hull.vertices,0].astype(np.float32) hully = points[hull.vertices,1].astype(np.float32) meanx = hullx.mean() meany = hully.mean() radius = np.sqrt((points[hull.vertices,0] - meanx)**2 + (points[hull.vertices,1] - meany)**2).max() project(data_x, data_y, data_z, self.model.reshape(-1), self.proj.reshape(-1), self.view.reshape(-1), winx, winy, winz) pnpoly(hullx, hully, winx, self.height() - winy - 1, inside, meanx, meany, radius) winx_inside = winx[inside==1] winy_inside = winy[inside==1] winz_inside = winz[inside==1] #zmin, zmax = winz_inside.min(), winz_inside.max() #counts = #vaex.histogram.hist1d( fraction = 0.005 N = len(winz_inside) indices = np.argsort(winz_inside) i1, i2 = indices[int(N*fraction)], indices[int(N*(1-fraction))] print i1, i2 zmin = winz_inside[i1] zmax = winz_inside[i2] xmin, xmax = winx_inside.min(), winx_inside.max() ymin, ymax = winy_inside.min(), winy_inside.max() #zmin, zmax = winz_inside.min(), winz_inside.max() print print "x:", xmin, xmax print "y:", ymin, ymax print "z:", zmin, zmax M = np.matrix(self.model) P = np.matrix(self.proj) T = (P * M) print "M", self.model print "P", self.proj print "v", self.view #xmin, xmax = 0, 1 #ymin, ymax = 0, 1 #zmin, zmax = 0, 1 self.bbox = [] for z in [zmin, zmax]: for y in [ymin, ymax]: for x in [xmin, xmax]: xc = ((x - self.view[0])/self.view[2] * 2 - 1) yc = ((y - self.view[1])/self.view[3] * 2 - 1 ) zc = z*2.-1. clip = np.array([[xc, yc, zc, 1]]).T #view = P.I * clip eye = (P.T*M.T).I * clip print eye eye[0:3] /= eye[3] print x, y, z print "->", eye #print clip #print (P*M) * (P*M).I #print GLU.gluUnProject self.bbox.append((eye[0], eye[1], eye[2])) xu,yu,zu = GLU.gluUnProject(x, y, z, self.model.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), self.proj.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), self.view.ctypes.data_as(ctypes.POINTER(ctypes.c_float))) print "glu:", xu, yu, zu indices_selected = np.arange(len(winx), dtype=np.uint32)[inside==1] indices_all = np.arange(len(winx), dtype=np.uint32)[inside==0] print data_x[indices_selected].min(), data_x[indices_selected].max() print data_y[indices_selected].min(), data_y[indices_selected].max() print data_z[indices_selected].min(), data_z[indices_selected].max() #import pdb #pdb.set_trace() x, y, z = 1,1,1 xu,yu,zu = GLU.gluUnProject(x, y, z, self.model.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), self.proj.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), self.view.ctypes.data_as(ctypes.POINTER(ctypes.c_float))) print print xu, yu, zu print GLU.gluProject(xu, yu, zu, self.model.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), self.proj.ctypes.data_as(ctypes.POINTER(ctypes.c_float)), self.view.ctypes.data_as(ctypes.POINTER(ctypes.c_float))) self.lasso_list = [] self.updateGL()
def paintGL(self, p0=0, p1=None, drawOpts=DRAWOPT_DEFAULT): ''' :param drawOpts: OR combination of draw flags. default is :data:`UI.DRAWOPT_DEFAULT` ''' if not self.visible: return if self.vertices is None or len(self.vertices) == 0: return #print self.vertices.shape is_click = (p1 is not None) if p1 is None: p1 = len(self) assert (p0 >= 0 and p1 >= p0 and p1 <= len(self.vertices)) if p1 <= p0: return # draw nothing GL.glDisable(GL.GL_LIGHTING) GL.glDisable(GL.GL_TEXTURE_2D) GL.glEnable(GL.GL_BLEND) GL.glShadeModel(GL.GL_FLAT) if self.normals is not None and len( self.normals) and self.normalTransparency: nColours = [] Mmat = GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX) Pmat = GL.glGetDoublev(GL.GL_PROJECTION_MATRIX) viewport = GL.glGetIntegerv(GL.GL_VIEWPORT) cam = GLU.gluUnProject((viewport[2] - viewport[0]) / 2, (viewport[3] - viewport[1]) / 2, 0.0, Mmat, Pmat, viewport) cam = np.array(cam, dtype=np.float32) diffs = self.vertices - cam # diffs *= -1 for di, diff in enumerate(diffs): nd = diff / np.linalg.norm(diff) dp = np.dot(nd, self.normals[di]) alpha = (dp - (-1)) / 2 * (1 - 0.15) + 0.15 if self.colours: nColours.append([ self.colours[di][0], self.colours[di][1], self.colours[di][2], alpha ]) else: nColours.append([ self.colour[0], self.colour[1], self.colour[2], alpha ]) self.colours = np.array(nColours, dtype=np.float32).reshape(-1, 4) GL.glPushMatrix() try: GL.glMultMatrixf(self.transform) drawPoints = DRAWOPT_POINTS & drawOpts if drawPoints: # actually draw the points if self.drawStyles is None: GL.glColor4f(*self.colour) self.drawPoints(np.arange(p0, p1, dtype=np.int32)) else: ds = self.drawStyles[p0:p1] which_empty = np.where(ds == 0)[0] which_pts = np.where(ds == 1)[0] which_crosses = np.where(ds == 2)[0] GL.glColor4f(1, 1, 0, 1) self.drawPoints(which_empty, p0) GL.glColor4f(*self.colour) self.drawPoints(which_pts, p0) self.drawCrosses(which_crosses, p0) GL.glDisableClientState(GL.GL_COLOR_ARRAY) #print self.selectedIndex if self.selectedIndex >= p0 and self.selectedIndex < p1: GL.glDisable(GL.GL_DEPTH_TEST) GL.glColor4f(1, 0, 0, 1) if self.drawStyles is None or self.drawStyles[ self.selectedIndex] != 2: self.drawPoints( np.arange(self.selectedIndex, self.selectedIndex + 1, dtype=np.int32)) else: self.drawCrosses( np.arange(self.selectedIndex, self.selectedIndex + 1, dtype=np.int32)) GL.glEnable(GL.GL_DEPTH_TEST) drawEdges = DRAWOPT_EDGES & drawOpts if self.edges is not None and drawEdges and not is_click: GL.glEnableClientState(GL.GL_VERTEX_ARRAY) GL.glVertexPointerf(self.vertices) GL.glColor4f(self.edgeColour[0], self.edgeColour[1], self.edgeColour[2], self.edgeColour[3]) GL.glLineWidth(1.0) GL.glDrawElementsui(GL.GL_LINES, self.edges) GL.glDisableClientState(GL.GL_VERTEX_ARRAY) GL.glDisable(GL.GL_BLEND) GL.glEnable(GL.GL_DEPTH_TEST) drawLabels = DRAWOPT_POINT_LABELS & drawOpts if self.names is not None and not is_click and drawLabels: self.nameWidth = [ sum([ GLUT.glutBitmapWidth(self.font, ord(x)) for x in name ]) for name in self.names ] GL.glColor4f(*self.colour) Mmat = GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX) Pmat = GL.glGetDoublev(GL.GL_PROJECTION_MATRIX) viewport = GL.glGetIntegerv(GL.GL_VIEWPORT) for name, v, w in zip(self.names, self.vertices, self.nameWidth)[p0:p1]: if bool(GL.glWindowPos2f): p = GLU.gluProject(v[0], v[1] + 5, v[2], Mmat, Pmat, viewport) GL.glWindowPos2f(p[0] - 0.5 * w, p[1]) else: GL.glRasterPos3f(v[0], v[1] + 5, v[2]) GLUT.glutBitmapString(self.font, name) except Exception, e: print 'ERROR', e, 'at line', sys.exc_info()[2].tb_lineno
def project(self,x,y,z): "Map the object coordinates (x,y,z) to window coordinates.""" self.set3DMatrices() return GLU.gluProject(x,y,z,self.m,self.p,self.v)
def OnDraw(self): # get screen position and store tmp = glu.gluProject(self._x, self._y, self._z) self._screenx, self._screeny, self._screenz = tuple(tmp)
def paintGL(self, p0=0, p1=None, drawOpts=DRAWOPT_DEFAULT): ''' :param drawOpts: OR combination of draw flags. default is :data:`UI.DRAWOPT_DEFAULT` ''' if not DRAWOPT_CAMERAS & drawOpts: return if p1 is None: p1 = len(self) if self.colour[3] != 1: GL.glDisable(GL.GL_DEPTH_TEST) # looks much better GL.glEnable(GL.GL_BLEND) GL.glColor4f(*self.colour) if p1 > p0: GL.glPointSize(5) if self.transform is not None: GL.glPushMatrix() GL.glMultMatrixf(self.transform.T) for pi in xrange(p0, p1): GL.glPushMatrix() GL.glMultMatrixf(self.transforms[pi].T) if self.colours is not None and pi < len(self.colours): GL.glColor4f(*self.colours[pi]) self.drawCamera(drawOpts) ''' GL.glMultMatrixd(np.linalg.inv(self.cameras[pi].K().T)) x = y = z = self.cameras[pi].cameraInterest xn = yn = zn = self.cameras[pi].cameraInterest * 0.200002 cpts = np.array([[-x, -y, -z], [x, -y, -z], [x, y, -z], [-x, y, -z], [-xn, -yn, -zn], [xn, -yn, -zn], [xn, yn, -zn], [-xn, yn, -zn]], dtype=np.float32) self.cameraFrustrumArray = np.array([cpts[0], cpts[1], cpts[1], cpts[2], cpts[2], cpts[3], cpts[3], cpts[0], cpts[4], cpts[5], cpts[5], cpts[6], cpts[6], cpts[7], cpts[7], cpts[4], cpts[0], cpts[4], cpts[1], cpts[5], cpts[2], cpts[6], cpts[3], cpts[7] ], dtype=np.float32) * .2 self.cameraFrustrumIdxArray = np.arange(0, len(self.cameraFrustrumArray)) self.drawFrustrum() ''' GL.glPopMatrix() if self.transform is not None: GL.glPopMatrix() # camera labels if self.names is None or not (DRAWOPT_LABELS & drawOpts): return if self.nameWidth is None: self.nameWidth = [ sum([GLUT.glutBitmapWidth(self.font, ord(x)) for x in name]) for name in self.names ] Mmat = GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX) Pmat = GL.glGetDoublev(GL.GL_PROJECTION_MATRIX) viewport = GL.glGetIntegerv(GL.GL_VIEWPORT) for name, mat, w in zip(self.names, self.mats, self.nameWidth)[p0:p1]: try: v = mat[4] if bool(GL.glWindowPos2f): p = GLU.gluProject(v[0], v[1] + 10, v[2], Mmat, Pmat, viewport) if p[2] > 1 or p[2] < 0: continue # near/far clipping of text GL.glWindowPos2f(p[0] - 0.5 * w, p[1]) else: GL.glRasterPos3f(v[0], v[1] + 10, v[2]) GLUT.glutBitmapString(self.font, name) except ValueError: pass # projection failed
def paintGL(self, p0=0, p1=None, drawOpts=DRAWOPT_DEFAULT): ''' :param drawOpts: OR combination of draw flags. default is :data:`UI.DRAWOPT_DEFAULT` ''' doingSelection = (p1 is not None) if doingSelection: return # TODO, selection not working because of using shaders if not self.d['draw'] or not self.d['visible']: return if p1 is None: p1 = len(self) if not self.GL_is_initialised: self.initializeGL() # could store a selected/non-selected colour, switch on selection change and avoid this if.. boneColour = COLOURS['Selected'] if self.d[K_SELECTED] else self.d[ K_BONE_COLOUR] # TODO: draw offset should be an option of THIS primitive, not a view based draw option? drawingOffset = DRAWOPT_OFFSET & drawOpts if drawingOffset: GL.glTranslate(self.offset[0], self.offset[1], self.offset[2]) GL.glEnable(GL.GL_BLEND) first_sel = self.numBones if self.transforms is not None and p0 < first_sel: GL.glUseProgram(self.colour_shader) b0, b1 = min(max(0, p0), first_sel), min(max(0, p1), first_sel) #GL.glUniform4fv(self.colour_shader_colours, 3, self.colours) # NOT WORKING GL.glUniform1iv( self.colour_shader_states, len(self.bone_colour_states), self.bone_colour_states ) # set the states so the shader can pick the correct colour per joint GL.glVertexAttrib4f(self.colour_shader_colour, *boneColour) GL.glVertexAttrib4f(self.colour_shader_alt_colour, *COLOURS['Hilighted']) GL.glEnableClientState(GL.GL_VERTEX_ARRAY) self.bvs.bind() GL.glVertexPointerf(self.bvs) GL.glEnableVertexAttribArray(self.colour_shader_bi) self.bvis.bind() GL.glVertexAttribIPointer(self.colour_shader_bi, 1, GL.GL_UNSIGNED_INT, 0, self.bvis) # write the bvis to bi if (DRAWOPT_BONES | DRAWOPT_JOINTS) & drawOpts: GL.glLineWidth(1) GL.glPointSize(5) for t0 in xrange(b0, b1, 128): # draw the bones in batches of 128 t1 = min(t0 + 128, b1) GL.glUniformMatrix4fv( self.colour_shader_myMat, t1 - t0, GL.GL_FALSE, self.transforms[t0:t1]) # put the transforms in myMat if DRAWOPT_BONES & drawOpts: GL.glDrawArrays(GL.GL_LINES, 2 * t0, 2 * (t1 - t0)) if DRAWOPT_JOINTS & drawOpts: GL.glDrawArrays(GL.GL_POINTS, 2 * t0, 2 * (t1 - t0)) self.bvis.unbind() GL.glDisableVertexAttribArray(self.colour_shader_bi) self.bvs.unbind() GL.glDisableClientState(GL.GL_VERTEX_ARRAY) if self.mvs and p1 > first_sel and DRAWOPT_MARKERS & drawOpts: assert self.numBones < 128, 'Only up to 128 bones are supported for now' GL.glUseProgram(self.colour_shader) m0, m1 = min(max(0, p0 - first_sel), self.numMarkers), min(max(0, p1 - first_sel), self.numMarkers) GL.glUniformMatrix4fv( self.colour_shader_myMat, len(self.transforms), GL.GL_FALSE, self.transforms) # put the transforms in myMat GL.glEnableClientState(GL.GL_VERTEX_ARRAY) self.mvs.bind() GL.glVertexPointerf(self.mvs) GL.glEnableVertexAttribArray(self.colour_shader_bi) self.mvis.bind() GL.glVertexAttribIPointer(self.colour_shader_bi, 1, GL.GL_UNSIGNED_INT, 0, self.mvis) # write the mvis to bi GL.glPointSize(5) GL.glVertexAttrib4f(self.colour_shader_colour, *self.d[K_MARKER_COLOUR]) # write the colour GL.glDrawArrays(GL.GL_POINTS, m0, m1 - m0) self.mvis.unbind() GL.glDisableVertexAttribArray(self.colour_shader_bi) self.mvs.unbind() GL.glDisableClientState(GL.GL_VERTEX_ARRAY) if p1 == len(self): if DRAWOPT_AXES & drawOpts: GL.glUseProgram(self.colour_shader) GL.glUniformMatrix4fv( self.shader_myMat, len(self.transforms), GL.GL_FALSE, self.transforms) # put the transforms in myMat GL.glEnableClientState(GL.GL_VERTEX_ARRAY) self.avs.bind() GL.glVertexPointerf(self.avs) GL.glEnableVertexAttribArray(self.colour_shader_bi) self.avis.bind() GL.glVertexAttribIPointer(self.colour_shader_bi, 1, GL.GL_UNSIGNED_INT, 0, self.avis) # write the avis to bi GL.glLineWidth(2) GL.glVertexAttrib4f(self.colour_shader_colour, 1, 0, 0, 1) # red GL.glVertexAttrib4f( self.colour_shader_alt_colour, 1, 0, 0, 1 ) # this doesn't seem clever. need to make the glUniform4fv work then make one call to set the 2 colours self.aris.bind() GL.glDrawElementsui(GL.GL_LINES, self.aris) # draw the lines self.aris.unbind() GL.glVertexAttrib4f(self.colour_shader_colour, 0, 1, 0, 1) # green GL.glVertexAttrib4f(self.colour_shader_alt_colour, 0, 1, 0, 1) self.agis.bind() GL.glDrawElementsui(GL.GL_LINES, self.agis) # draw the lines self.agis.unbind() GL.glVertexAttrib4f(self.colour_shader_colour, 0, 0, 1, 1) # blue GL.glVertexAttrib4f(self.colour_shader_alt_colour, 0, 0, 1, 1) self.abis.bind() GL.glDrawElementsui(GL.GL_LINES, self.abis) # draw the lines self.abis.unbind() self.avis.unbind() GL.glDisableVertexAttribArray(self.colour_shader_bi) self.avs.unbind() GL.glDisableClientState(GL.GL_VERTEX_ARRAY) GL.glUseProgram(self.shader) if self.image != self.bindImage: if self.bindImage is not None: self.deleteTexture(self.bindId) self.bindId, self.bindImage = long(0), None if self.image is not None: global win self.bindId = self.view.bindTexture(self.image) self.bindImage = self.image if self.bindImage is not None: GL.glEnable(GL.GL_TEXTURE_2D) GL.glBindTexture(GL.GL_TEXTURE_2D, self.bindId) GL.glEnable(GL.GL_CULL_FACE) GL.glCullFace(GL.GL_BACK) GL.glFrontFace(GL.GL_CCW) GL.glEnable(GL.GL_LIGHTING) GL.glEnable(GL.GL_LIGHT0) Pmat = GL.glGetDoublev(GL.GL_PROJECTION_MATRIX) lightDir = -Pmat[:3, 2] # the direction the camera is looking GL.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, lightDir) if self.d[K_COLOUR]: GL.glMaterialfv(GL.GL_FRONT, GL.GL_AMBIENT_AND_DIFFUSE, self.d[K_COLOUR]) if self.vs is not None: GL.glEnableClientState(GL.GL_VERTEX_ARRAY) self.vs.bind() GL.glVertexPointerf(self.vs) if self.vts is not None: GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY) self.vts.bind() GL.glTexCoordPointerf(self.vts) if self.vns is not None: GL.glEnableClientState(GL.GL_NORMAL_ARRAY) self.vns.bind() GL.glNormalPointerf(self.vns) if self.tris is not None: GL.glDrawElementsui(GL.GL_TRIANGLES, self.tris) # static geom if self.transformData is not None and self.transforms is not None: GL.glUniformMatrix4fv( self.shader_myMat, len(self.transforms), GL.GL_FALSE, self.transforms) # put the transforms in myMat GL.glEnableVertexAttribArray(self.shader_bi) self.vtis.bind() GL.glVertexAttribIPointer(self.shader_bi, 1, GL.GL_UNSIGNED_INT, 0, self.vtis) # write the vtis to bi if DRAWOPT_GEOMS & drawOpts: self.tis.bind() GL.glDrawElementsui(GL.GL_TRIANGLES, self.tis) # draw the triangles self.tis.unbind() self.vtis.unbind() GL.glDisableVertexAttribArray(self.shader_bi) if self.vs is not None: self.vs.unbind() GL.glDisableClientState(GL.GL_VERTEX_ARRAY) if self.vts is not None: self.vts.unbind() GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY) if self.vns is not None: self.vns.unbind() GL.glDisableClientState(GL.GL_NORMAL_ARRAY) GL.glDisable(GL.GL_LIGHTING) GL.glDisable(GL.GL_TEXTURE_2D) GL.glDisable(GL.GL_BLEND) GL.glUseProgram(0) if self.d[ K_NAME] is not None and self.transforms is not None and DRAWOPT_LABELS & drawOpts: try: GL.glColor4f(*boneColour) phi = np.max(self.transforms[:, 3, :3], axis=0) plo = np.min(self.transforms[:, 3, :3], axis=0) if bool(GL.glWindowPos2f): Mmat = GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX) Pmat = GL.glGetDoublev(GL.GL_PROJECTION_MATRIX) viewport = GL.glGetIntegerv(GL.GL_VIEWPORT) p = GLU.gluProject((phi[0] + plo[0]) * 0.5, phi[1] + 300.0, (phi[2] + plo[2]) * 0.5, Mmat, Pmat, viewport) if p[2] > 0 and p[2] < 1: # near/far clipping of text # TODO, now this won't change if name changes... if self.nameWidth is None: self.nameWidth = sum([ GLUT.glutBitmapWidth(self.font, ord(x)) for x in self.d[K_NAME] ]) GL.glWindowPos2f(p[0] - 0.5 * self.nameWidth, p[1]) GLUT.glutBitmapString(self.font, self.d[K_NAME]) else: GL.glRasterPos3f((phi[0] + plo[0]) * 0.5, phi[1] + 300.0, (phi[2] + plo[2]) * 0.5) GLUT.glutBitmapString(self.font, self.d[K_NAME]) except ValueError: pass # projection failed if DRAWOPT_OFFSET & drawOpts: GL.glTranslate(-self.offset[0], -self.offset[1], -self.offset[2])
def _GetCords(self): """ _GetCords() Get a pointset of the coordinates of the wobject. This is used for drawing the quads and lines using a vertex array. """ # Can we reuse buffered coordinates? if self._cordsBuffer is not None: return self._cordsBuffer # Get ranges in world coords rangex, rangey = self._GetRangesInWorldCords() # Project two points to use in OnDrawScreen screen1 = glu.gluProject(rangex.min, rangey.min, 0) screen2 = glu.gluProject(rangex.max, rangey.max, 0) # Calculate world-distance of a screendistance of self._barwidth # and then do drawing here (not in OnDrawScreen), otherwise I won't # be able to detect picking!! onePixelx = rangex.range / ( screen2[0] - screen1[0] ) onePixely = rangey.range / ( screen2[1] - screen1[1] ) # Get coords tmp = self._barWidth x1, x2, xd = rangex.min, rangex.max, onePixelx*tmp y1, y2, yd = rangey.min, rangey.max, onePixely*tmp if yd<0: y1, y2 = y2, y1 # axis flipped # Definition of the coordinate indices: # # 12 11 10 15 # 4 0 ----- 3 9 # | | # | | # 5 1------ 2 8 # 13 6 7 14 # # Make coords pp = Pointset(2) # pp.append(x1, y1) pp.append(x1, y2) pp.append(x2, y2) pp.append(x2, y1) # pp.append(x1-xd, y1) pp.append(x1-xd, y2) pp.append(x1, y2+yd) pp.append(x2, y2+yd) # pp.append(x2+xd, y2) pp.append(x2+xd, y1) pp.append(x2, y1-yd) pp.append(x1, y1-yd) # pp.append(x1-xd, y1-yd) pp.append(x1-xd, y2+yd) pp.append(x2+xd, y2+yd) pp.append(x2+xd, y1-yd) # Done self._cordsBuffer = pp return pp
def project(self,x,y,z): "Map the object coordinates (x,y,z) to window coordinates.""" self.set3DMatrices() return GLU.gluProject(x,y,z,self.m.astype(double),self.p,self.v)