def apply(self): """Applies the transform this camera represents to the active OpenGL context.""" self._update_pos() gluLookAt(*self._pos.x_y_z, *self._look_at.x_y_z, *self._up.x_y_z)
def SetView(self, viewport, camx, camy, zoom, NoDepth = False): """ Sets viewport. Parameters: viewport: the viewport (duh) camx,camy: camera position zoom: the zoom. NoDepth: if this is set to True, there will be no depth """ self.camx = camx self.camy = camy self.zoom = zoom self.ratio_x = viewport.resx self.ratio_y = viewport.resy if NoDepth: glDisable(GL_DEPTH_TEST) glDisable(GL_ALPHA_TEST) else: glEnable(GL_DEPTH_TEST) glEnable(GL_ALPHA_TEST) glViewport( int(viewport.x*self.screen_w), int( (((1.0)-viewport.y)-viewport.h) * self.screen_h), int(viewport.w*self.screen_w), int(viewport.h*self.screen_h)); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); glOrtho( (-viewport.resx/2)*zoom, (viewport.resx/2)*zoom, (viewport.resy/2)*zoom, (-viewport.resy/2)*zoom, -100, 100 ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); gluLookAt(camx,camy,20, camx,camy,0, 0,1,0);
def main(): moons = [Moon(pos) for pos in d12_input] glutInit(sys.argv) glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH) glutInitWindowSize(800, 800) glutInitWindowPosition(350, 200) glutCreateWindow('name') glClearColor(0., 0., 0., 1.) glShadeModel(GL_SMOOTH) glEnable(GL_CULL_FACE) glEnable(GL_DEPTH_TEST) glEnable(GL_LIGHTING) lightZeroPosition = [10., 4., 10., 1.] lightZeroColor = [0.8, 1.0, 0.8, 1.0] glLightfv(GL_LIGHT0, GL_POSITION, lightZeroPosition) glLightfv(GL_LIGHT0, GL_DIFFUSE, lightZeroColor) glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.1) glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.05) glEnable(GL_LIGHT0) glutDisplayFunc(lambda: display_scene(moons)) glutTimerFunc(0, timer, 0) glMatrixMode(GL_PROJECTION) gluPerspective(40., 1., 1., 40.) glMatrixMode(GL_MODELVIEW) gluLookAt(0, -10, 10, 0, 0, 0, 0, 1, 0) glPushMatrix() glutMainLoop()
def reshape_function(self, w, h): # prevent dividing by zero if window height is 0 if h == 0: h = 1 self.window_width = w self.window_height = h proportional_rate = float(w) / h glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(60.0, proportional_rate, 0.1, 100) camera_settings_matrix = [0 for i in range(9)] # calculate camera's point of view camera_settings_matrix = self.recalculate_camera_settings( camera_settings_matrix) # set camera's point of view gluLookAt(camera_settings_matrix[0], camera_settings_matrix[1], camera_settings_matrix[2], camera_settings_matrix[3], camera_settings_matrix[4], camera_settings_matrix[5], camera_settings_matrix[6], camera_settings_matrix[7], camera_settings_matrix[8]) glScalef(self.scale_factor, self.scale_factor, self.scale_factor) glMatrixMode(GL_MODELVIEW)
def drawScene(): "" glClear(GL_COLOR_BUFFER_BIT) glLoadIdentity() # Write text in isolated (i.e., before gluLookAt) translate block. glPushMatrix() glTranslatef(0.0, 0.0, -30.0) glColor3fv(highlightColor) glRasterPos3f(-28.0, 25.0, 0.0) if not animateMode: writeBitmapString(font, "DEVELOP MODE") manVector[manVectorIterator].writeData() else: writeBitmapString(font, "ANIMATE MODE") glPopMatrix() # Place camera. gluLookAt(camera.zoomDistance * sin(camera.viewDirection * PI / 180.0), 0.0, camera.zoomDistance * cos(camera.viewDirection * PI / 180.0), 0.0, 0.0, 0.0, 0.0, 1.0, 0.0) # Move man right 10 units because of data text on left of screen. glTranslatef(10.0, 0.0, 0.0) if not animateMode: # Develop mode. # Draw all the configurations in manVector. for man in manVector: man.draw() else: # Animated mode - # use separate iterator so as to leave develop mode iterator unchanged. manVector[manVectorAnimationIterator].draw() # Other (fixed) objects in scene are drawn below starting here. # Black floor. glColor3f(0.0, 0.0, 0.0) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) for zi in range(-5, 20): ### for (float z = -25.0; z<100.0; z += 5.0) z = zi * 5.0 glBegin(GL_TRIANGLE_STRIP) for xi in range(-10, 10): ### for (float x = -50.0; x<50.0; x += 5.0) x = xi * 5.0 glVertex3f(x, -25.0, z) glVertex3f(x, -25.0, z + 5.0) glEnd() # Green sphere. glColor3f(0.0, 1.0, 0.0) glTranslatef(0.0, -20.0, 10.0) glPushMatrix() glScalef(5.0, 5.0, 5.0) glutWireSphere(1.0, 10, 8) glPopMatrix() glutSwapBuffers()
def __get_rotation_matrix(coordinates, side_length): """Get rotation matrix from specific point of view and scale.""" assert len(coordinates) == 3 glLoadIdentity() glOrtho(-side_length, side_length, -side_length, side_length, -4 * side_length, 4 * side_length) x, y, z = coordinates gluLookAt(x, y, z, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0) return array(glGetFloatv(GL_MODELVIEW_MATRIX), dtype='f')
def update(self): # Set matrix via gluLookAt # Build reference point vector (absolute coords) rx = self.pos[0] + self.ref[0] ry = self.pos[1] + self.ref[1] rz = self.pos[2] + self.ref[2] # cam_pos, ref_pt, up_vec gluLookAt(self.pos[0], self.pos[1], self.pos[2], rx, ry, rz, 0.0, 1.0, 0.0)
def resize(self, w, h): if h == 0: h = 1 glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(45.0, float(w) / float(h), 0.1, 1000.0) #glEnable(GL_DEPTH_TEST) glMatrixMode(GL_MODELVIEW) glLoadIdentity() gluLookAt(0, 0, 10, 0, 0, 0, 0, 1, 0) glEnable(GL_DEPTH_TEST)
def display(self): glMatrixMode(GL_MODELVIEW) glLoadIdentity() gluLookAt(0.0, 240.0, 1000.0, 0.0, 240.0, 0.0, 0.0, 1.0, 0.0) glClear(GL_COLOR_BUFFER_BIT) for i in self.fountains: i.life -= 1 i.init() i.update() glutPostRedisplay() glutSwapBuffers()
def draw(self): self.handle_reshape(self.width, self.height) size = self._size / 2 glPushMatrix() glTranslatef(0, 0, -5.64 * size) gluLookAt(self._eye_x, self._eye_y, self._eye_z, 0, 0, -5.64 * size, 0, 1, 0) glRotatef(self._rotate_x, 1.0, 0.0, 0.0) glRotatef(self._rotate_y, 0.0, 1.0, 0.0) glPushMatrix() glTranslatef(0, 0, size) self._draw_zero_plane_xy(Color.Blue) glPopMatrix() glPushMatrix() glTranslatef(0, 0, -size) self._draw_zero_plane_xy(Color.Orange) glPopMatrix() glPushMatrix() glTranslatef(0, size, 0) glRotatef(90, 1, 0, 0) self._draw_zero_plane_xy(Color.Green) glPopMatrix() glPushMatrix() glTranslatef(0, -size, 0) glRotatef(90, 1, 0, 0) self._draw_zero_plane_xy(Color.Pink) glPopMatrix() glPushMatrix() glTranslatef(size, 0, 0) glRotatef(90, 0, 1, 0) self._draw_zero_plane_xy(Color.Purple) glPopMatrix() glPushMatrix() glTranslatef(-size, 0, 0) glRotatef(90, 0, 1, 0) self._draw_zero_plane_xy(Color.Red) glPopMatrix() glPopMatrix()
def draw(self): #set listener position at camera sounds.setListenerPosition((self.x, self.y, self.z)) #target coord tx, ty, tz = self.target.body.getPosition() if self.oldTargetPos==None: self.oldTargetPos = tx, ty, tz gluLookAt(self.x, self.y, self.z, (tx+self.oldTargetPos[0])/2, (self.y+self.oldTargetPos[1])/2/3, (tz+self.oldTargetPos[2])/2, 0, 1, 0) self.oldTargetPos = tx, ty, tz v = vectormath.getVector((self.x, 0.0, self.z), (tx, 0.0, tz)) self.angleY = -(atan2(v[2], v[0]) + pi/2)*180.0/pi
def updateMatrix(self): """ needs updating if light changes position or direction. """ # for some reason this is faster then calling the cython code glMatrixMode(GL_MODELVIEW) glLoadIdentity() gluLookAt(self.light.lightPosition[0], self.light.lightPosition[1], self.light.lightPosition[2], self.light.lightDirection[0], self.light.lightDirection[1], self.light.lightDirection[2], 0.0, 1.0, 0.0 ) self.modelViewMatrix = glGetFloatv( gl.GL_MODELVIEW_MATRIX )
def reshape(Width, Height): far = 30.0 if (Width == Height): glViewport(0, 0, Width, Height) elif (Width > Height): glViewport(0, 0, Height, Height) else: glViewport(0, 0, Width, Width) glMatrixMode(GL_PROJECTION) glLoadIdentity() #glFrustum(-10.0,10.0,-10.0,10.0,3.0,60.0) gluPerspective(80.0, 1.0, 1.0, 80.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() gluLookAt(0.0, 0.0, far, 0.0, 0.0, 0.0, 0.0, 1.0, far)
def init(self): # Enable a single OpenGL light. glLightfv(GL_LIGHT0, GL_AMBIENT, self.light_ambient) glLightfv(GL_LIGHT0, GL_DIFFUSE, self.light_diffuse) glLightfv(GL_LIGHT0, GL_POSITION, self.light_position) glEnable(GL_LIGHT0) glEnable(GL_LIGHTING) # Use depth buffering for hidden surface elimination. glEnable(GL_DEPTH_TEST) # Setup the view of the cube. glMatrixMode(GL_PROJECTION) gluPerspective(40.0, 640. / 480., 1.0, 10.0) glMatrixMode(GL_MODELVIEW) gluLookAt(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.)
def reshape(Width,Height): far=30.0 if (Width==Height): glViewport(0,0,Width,Height) elif (Width>Height): glViewport(0,0,Height,Height) else: glViewport(0,0,Width,Width) glMatrixMode(GL_PROJECTION) glLoadIdentity() #glFrustum(-10.0,10.0,-10.0,10.0,3.0,60.0) gluPerspective(80.0,1.0,1.0,80.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() gluLookAt(0.0,0.0,far, 0.0,0.0,0.0, 0.0,1.0,far)
def updateMatrix(self): # create float32 look at matrix pos = self.position view = self.direction # for some reason this is faster then calling the cython code glMatrixMode( GL_PROJECTION ) glLoadIdentity() gluLookAt(pos[0], pos[1], pos[2], pos[0] + view[0], pos[1] + view[1], pos[2] + view[2], 0.0, 1.0, 0.0) self.modelViewMatrix = glGetFloatv( GL_PROJECTION_MATRIX ) # emit signal that the modelview matrix changed self.signalQueueEmit( Camera.CAMERA_MODELVIEW_SIGNAL )
def draw(self): #set listener position at camera sounds.setListenerPosition((self.x, self.y, self.z)) #target coord tx, ty, tz = self.target.body.getPosition() if self.oldTargetPos == None: self.oldTargetPos = tx, ty, tz gluLookAt(self.x, self.y, self.z, (tx + self.oldTargetPos[0]) / 2, (self.y + self.oldTargetPos[1]) / 2 / 3, (tz + self.oldTargetPos[2]) / 2, 0, 1, 0) self.oldTargetPos = tx, ty, tz v = vectormath.getVector((self.x, 0.0, self.z), (tx, 0.0, tz)) self.angleY = -(atan2(v[2], v[0]) + pi / 2) * 180.0 / pi
def gluLookAtMatrix(eye, center, up): ''' get the lookat matrix using opengl. Note that opengl context needs to be initialized at the point of making this call. ''' from OpenGL.GL import GL_MODELVIEW, GL_MODELVIEW_MATRIX, glMatrixMode, \ glLoadIdentity, glGetDoublev, glPushMatrix, \ glPopMatrix from OpenGL.GLU import gluLookAt glMatrixMode(GL_MODELVIEW) glPushMatrix() glLoadIdentity() gluLookAt(eye[0], eye[1], eye[2], center[0], center[1], center[2], up[0], up[1], up[2]) M = np.transpose(glGetDoublev(GL_MODELVIEW_MATRIX)) glPopMatrix() return np.matrix(M)
def updateMatrix(self): """ update the light rotation matrix. needs only updating if the light position changes. """ # for some reason this is faster then calling the cython code glMatrixMode(GL_MODELVIEW) glLoadIdentity() gluLookAt(0.0, 0.0, 0.0, - self.light.lightPosition[0], - self.light.lightPosition[1], - self.light.lightPosition[2], -1.0, 0.0, 0.0 ) self.modelViewMatrix = glGetFloatv( gl.GL_MODELVIEW_MATRIX ) # projection depends on modelview matrix self.updateProjectionMatrix()
def __draw(self, widget, event): x = self.__distance * sin(self.__angle) z = self.__distance * cos(self.__angle) gldrawable = widget.get_gl_drawable() glcontext = widget.get_gl_context() # OpenGL begin. if not gldrawable.gl_begin(glcontext): return glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity () gluLookAt(x, 0.0, z, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0) #========================== glPushMatrix() glLineWidth(3) glRotatef(self.__arm_angles[0], 1., 0., 0.) glRotatef(self.__arm_angles[1], 0., 1., 0.) glRotatef(self.__arm_angles[2], 0., 0., 1.) glTranslatef(self.__upper_arm, 0., 0.) #========================== glPushMatrix() glColor3f(30./255., 126./255., 30./255.) glScalef(self.__upper_arm, 0.4, 1.0) self.__draw_cube() # shoulder glPopMatrix() #========================== glTranslatef(self.__upper_arm, 0., 0.) glRotatef(self.__arm_angles[3] , 0., 0., 1.) glTranslatef(self.__forearm, 0., 0.) glPushMatrix() #========================== glScalef(self.__forearm, 0.3, 0.75) glColor3f(126./255., 30./255., 30./255.) self.__draw_cube() # elbow glPopMatrix() glPopMatrix() #========================== if gldrawable.is_double_buffered(): gldrawable.swap_buffers() else: glFlush() gldrawable.gl_end() # OpenGL end return
def setGluViewMatrix(self): """ Sets the LookAt Matrix using GLU. """ tmpVec = self.Position + self.Front self.Focus = tmpVec if (self.debug1): print("\n\t getGluViewMatrix() Vectors : Yaw: ", self.Yaw, " Pitch: ", self.Pitch, " Position: ", self.Position.x, ", ", self.Position.y, ", ", self.Position.z, " Focus: ", self.Focus.x, ", ", self.Focus.y, ", ", self.Focus.z, " Front: ", self.Front.x, ", ", self.Front.y, ", ", self.Front.z) gluLookAt( self.Position.x, self.Position.y, self.Position.z, tmpVec.x, tmpVec.y, tmpVec.z, self.Up.x, self.Up.y, self.Up.z )
def paintGL(self): glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(self.zoom, -self.zoom, -self.zoom, self.zoom, -5000, 5000) arriba = 1 if self.theta == 360: arriba = -1 gluLookAt(self.x, self.y, self.z, self.desviacion_x, self.desviacion_y, self.desviacion_z, 0, arriba, 0) glMatrixMode(GL_MODELVIEW) if self.programa.modo_oscuro: glClearColor(0.3, 0.3, 0.3, 0) else: glClearColor(1, 1, 1, 0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadMatrixf(self.m) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) self.ordenar_elementos() self.update()
def draw(self): glMatrixMode(GL_MODELVIEW) glPushMatrix() gluLookAt(-2, 2, -6, 0, 0, 0, 0, 1, 0) glMultMatrixf(self._identity_mat) color = 0 colors = [(1, 0, 0), (1, 1, 0), (0, 1, 1), (1, 0, 0), (1, 1, 0), (0, 1, 1)] for edge in self._edges: glColor3f(colors[color][0], colors[color][1], colors[color][2]) if color > 2: Edge.draw_dotted_edge( Edge(self._vertices[edge[0]], self._vertices[edge[1]])) else: Edge.draw_edge( Edge(self._vertices[edge[0]], self._vertices[edge[1]])) color += 1 glPopMatrix()
def look_at(self, eye=None, center=None, up=None): ''' Set the camera view with gluLookAt, use default settings if values are not provided ''' # If the arguments passed to this module have value, set the # corresponding class variable to the value passed if eye: self.eye = eye if center: self.center = center if up: self.up = up # Switch to modelview self.reset() # Set camera lookat gluLookAt(self.eye[0], self.eye[1], self.eye[2], self.center[0], self.center[1], self.center[2], self.up[0], self.up[1], self.up[2])
def recalcular_posicion(self): if self.theta < 360: self.theta = 360 if self.theta > 540: self.theta = 540 if self.phi >= 360: self.phi -= 360 if self.phi < 0: self.phi += 360 if self.zoom < 10: self.zoom = 10 self.x = sin(radians(self.theta)) * cos(radians( self.phi)) + self.desviacion_x self.z = sin(radians(self.theta)) * sin(radians( self.phi)) + self.desviacion_z self.y = cos(radians(self.theta)) + self.desviacion_y gluLookAt(self.x, self.y, self.z, self.desviacion_x, self.desviacion_y, self.desviacion_z, 0, 1, 0) self.programa.actualizar_texto() self.update()
def reshape(Width, Height): """ 调整窗口大小回调函数 :param Width: :param Height: :return: """ far = 30.0 if (Width == Height): glViewport(0, 0, Width, Height) elif (Width > Height): glViewport(0, 0, Height, Height) else: glViewport(0, 0, Width, Width) # 如果参数是GL_PROJECTION,这个是投影的意思,就是要对投影相关进行操作, # 也就是把物体投影到一个平面上,就像我们照相一样,把3维物体投到2维的平面上。 # 这样,接下来的语句可以是跟透视相关的函数,比如glFrustum()或gluPerspective(); glMatrixMode(GL_PROJECTION) # 恢复初始坐标系,对当前矩阵进行初始化 glLoadIdentity() # glFrustum(-10.0,10.0,-10.0,10.0,3.0,60.0) # 指定了观察的视景体(frustum为锥台的意思,通常译为视景体)在世界坐标系中的具体大小, # 一般而言,其中的参数aspect应该与窗口的宽高比大小相同。 gluPerspective(80.0, 1.0, 1.0, 80.0) # 如果参数是GL_MODELVIEW,这个是对模型视景的操作, # 接下来的语句描绘一个以模型为基础的适应,这样来设置参数, # 接下来用到的就是像gluLookAt()这样的函数 glMatrixMode(GL_MODELVIEW) # 恢复初始坐标系,对当前矩阵进行初始化 glLoadIdentity() # gluLookAt()函数是通过移动照相机(使用视图变换)来观察 gluLookAt(0.0, 0.0, far, 0.0, 0.0, 0.0, 0.0, 1.0, far)
def look_at(self, eye=None, center=None, up=None): ''' Set the camera view with gluLookAt, use default settings if values are not provided ''' # If the arguments passed to this module have value, set the # corresponding class variable to the value passed if eye: self.eye = eye if center: self.center = center if up: self.up = up # Switch to modelview self.reset() # Set camera lookat gluLookAt( self.eye[0], self.eye[1], self.eye[2], self.center[0], self.center[1], self.center[2], self.up[0], self.up[1], self.up[2] )
def render(self, local_rot): glMatrixMode(GL_MODELVIEW) glPushMatrix() gluLookAt(-2, 2, -6, 0, 0, 0, 0, 1, 0) glMultMatrixf(self._trans_mat) glMultMatrixf(self._rotation_mat) glPushMatrix() self.move_x() self.move_y() self.move_z() glPopMatrix() glPushMatrix() glLoadIdentity() if local_rot: self.rotate_local() else: self.rotate_global() self._rotation_mat = glGetFloatv(GL_MODELVIEW_MATRIX) glPopMatrix() self.draw() glPopMatrix()
def set_camera(self): gluLookAt(self.pos[0], self.pos[1], self.pos[2], self.center[0], self.center[1], self.center[2], self.upvec[0], self.upvec[1], self.upvec[2])
def apply(self): """Load the camera matrix.""" gluLookAt(self.origin[0], self.origin[1], self.origin[2], self.target[0], self.target[1], self.target[2], self.up[0], self.up[1], self.up[2])
def set_camera(self): gluLookAt(self.pos[0],self.pos[1],self.pos[2], self.center[0],self.center[1],self.center[2], self.upvec[0],self.upvec[1],self.upvec[2])
def draw(): global curIndex, curData, data glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) if curData>2 or curData==0: pz = 400 else: pz = 0 glPushMatrix() gluLookAt(0, view_dist, 0, 0, 0, 0, 0, 0, 1); glRotatef(view_rotx, 1, 0, 0) glRotatef(view_roty, 0, 0, 1) glTranslatef(0,0,-pz) # then the DNA glColor(1,1,1,1) glBegin(GL_LINE_STRIP) if curIndex >= data[curData].shape[0]: curIndex = 0 for vert in data[curData][curIndex,:,:]: glVertex3f(vert[0],vert[1],vert[2]) glEnd() # and a pore, if needed if curData > 4: glColor(1,0,0,1) r = 5 z = 400 glBegin(GL_LINE_STRIP) for th in np.linspace(0,2*np.pi,20): glVertex3f(r*np.cos(th),r*np.sin(th),z) glEnd() glPopMatrix() # now draw things in screen coords # GL projects rasterpos, so need to set appropriate proj mat glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0,1,0,1,-1, 1); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glColor(1,1,1,1) glRasterPos2f(0.02, 0.02); # loop through string and spit out per char debugstr = "Index: " + str(curIndex) for c in debugstr: glutBitmapCharacter(GLUT_BITMAP_9_BY_15, ord(c)); glMatrixMode(GL_PROJECTION); glPopMatrix() glMatrixMode(GL_MODELVIEW); glPopMatrix() glutSwapBuffers() glutPostRedisplay()
def keyboard(*key): print key if key[0] == '\x1b': sys.exit() if key[0] == '\r': gluLookAt(0,0,1,0,0,0,1,1,1)
def look(self): glMatrixMode(GL_MODELVIEW) glLoadIdentity() gluLookAt(self.pos[0], self.pos[1], self.pos[2], self.target[0], self.target[1], self.target[2], self.up[0], self.up[1], self.up[2])
def OnDraw(self): glMatrixMode(GL_PROJECTION) glLoadIdentity() glFrustum(-50.0 * self.zoom, 50.0 * self.zoom, -50.0 * self.zoom, 50.0 * self.zoom, 200, 800.0) #glTranslatef(0.0, 0.0, -400.0) gluLookAt(200.0, -200.0, 400.0, 0.0, 0.0, 0.0, -1.0, 1.0, 0.0) glMatrixMode(GL_MODELVIEW) if self.resetView: glLoadIdentity() self.lastx = self.x = 0 self.lasty = self.y = 0 self.anglex = self.angley = self.anglez = 0 self.transx = self.transy = 0 self.resetView = False if self.size is None: self.size = self.GetClientSize() w, h = self.size w = max(w, 1.0) h = max(h, 1.0) xScale = 180.0 / w yScale = 180.0 / h glRotatef(self.angley * yScale, 1.0, 0.0, 0.0) glRotatef(self.anglex * xScale, 0.0, 1.0, 0.0) glRotatef(self.anglez, 0.0, 0.0, 1.0) glTranslatef(self.transx, self.transy, 0.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE) glEnable(GL_COLOR_MATERIAL) glEnable(GL_LIGHTING) glEnable(GL_LIGHT0) glEnable(GL_LIGHT1) if self.drawGrid: glBegin(GL_LINES) for i in range(len(self.gridVertices)): glColor(self.gridColors[i]) p = self.gridVertices[i] glVertex3f(p[0], p[1], p[2]) glVertex3f(p[3], p[4], p[5]) glEnd() colors = {MT_RAPID: [0.0, 1.0, 1.0, 1], MT_NORMAL: [1.0, 1.0, 1.0, 1]} currentLineType = MT_RAPID glColor(colors[MT_RAPID]) glBegin(GL_LINE_STRIP) for p in self.dataPoints: if p[3] != currentLineType: currentLineType = p[3] glColor(colors[currentLineType]) glVertex3f(p[0], p[1], p[2]) glEnd() self.SwapBuffers() glDisable(GL_LIGHT0) glDisable(GL_LIGHT1) glDisable(GL_LIGHTING) self.anglex = self.angley = self.anglez = 0 self.transx = self.transy = 0
def point(self): # postcondition: matrix mode is modelview # set up the modelview matrix glMatrixMode(GL_MODELVIEW) glLoadIdentity() gluLookAt(*self.position + self.target + self.up)
def setGLView(self): glLoadIdentity() tgt = self.pos + self.facing gluLookAt(self.pos.x, self.pos.y, self.pos.z, tgt.x, tgt.y, tgt.z, self.up.x, self.up.y, self.up.z)
def OnDraw(self): glMatrixMode(GL_PROJECTION) glLoadIdentity() glFrustum(-50.0*self.zoom, 50.0*self.zoom, -50.0*self.zoom, 50.0*self.zoom, 200, 800.0) #glTranslatef(0.0, 0.0, -400.0) gluLookAt (200.0, -200.0, 400.0, 0.0, 0.0, 0.0, -1.0, 1.0, 0.0); glMatrixMode(GL_MODELVIEW) if self.resetView: glLoadIdentity() self.lastx = self.x = 0 self.lasty = self.y = 0 self.anglex = self.angley = self.anglez = 0 self.transx = self.transy = 0 self.resetView = False if self.size is None: self.size = self.GetClientSize() w, h = self.size w = max(w, 1.0) h = max(h, 1.0) xScale = 180.0 / w yScale = 180.0 / h glRotatef(self.angley * yScale, 1.0, 0.0, 0.0); glRotatef(self.anglex * xScale, 0.0, 1.0, 0.0); glRotatef(self.anglez, 0.0, 0.0, 1.0); glTranslatef(self.transx, self.transy, 0.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); glEnable(GL_COLOR_MATERIAL); glEnable(GL_LIGHTING) glEnable(GL_LIGHT0) glEnable(GL_LIGHT1) self.drawGrid = True if self.drawGrid: glBegin(GL_LINES) for i in range(len(self.gridVertices)): glColor(self.gridColors[i]) p = self.gridVertices[i] glVertex3f(p[0], p[1], p[2]) glVertex3f(p[3], p[4], p[5]) glEnd() glColor([0.0, 0.5, 0.25, 1]) if self.vertexPositions is not None: self.vertexPositions.bind() glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, self.vertexPositions); self.normalPositions.bind() glEnableClientState(GL_NORMAL_ARRAY) glNormalPointer(GL_FLOAT, 0, self.normalPositions); glDrawArrays(GL_TRIANGLES, 0, len(self.vertices)); self.SwapBuffers() glDisable(GL_LIGHT0) glDisable(GL_LIGHT1) glDisable(GL_LIGHTING) self.anglex = self.angley = self.anglez = 0 self.transx = self.transy = 0
def display(self): glLoadIdentity() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) gluLookAt(self.cam_pos.x, self.cam_pos.y, self.cam_pos.z, self.cam_focus.x, self.cam_focus.y, self.cam_focus.z, 0, 1, 0) self.level.draw() glLoadIdentity() gluLookAt(0, -0.5, 2.5, 0, 0, 0, 0, 1, 0) wdth = 0.3 glTranslate( 0.0 - (len(self.level.solomon.current_state.keys()) - 1) * wdth / 2.0, -1.3, 0) if debug == True: for k in self.level.solomon.current_state.keys(): col = "red" if self.level.solomon.current_state[k]: col = "green" glMaterialfv(GL_FRONT, GL_DIFFUSE, colours[col]) glutSolidCube(wdth - 0.02) glTranslate(wdth, 0, 0) glPushMatrix() #glLoadIdentity() glScale(0.005, 0.01, -0.01) glTranslate(-90, 4, -20) #glTranslate(-180,-70,0) glTranslate(-wdth, 0, 0) self.letters.drawString(k[:4]) glPopMatrix() glLoadIdentity() gluLookAt(0, -0.5, 2.5, 0, 0, 0, 0, 1, 0) wdth = 0.2 joystick_actions = [x for x in dir(self.joystick) if x[0:2] == "is"] glTranslate(0.0 - (len(joystick_actions) - 1) * wdth / 2.0, -1.0, 0) if debug == True: for k in joystick_actions: #print(k) col = "red" if getattr(self.joystick, k)(self.keys): col = "green" glMaterialfv(GL_FRONT, GL_DIFFUSE, colours[col]) glutSolidCube(wdth - 0.02) glTranslate(wdth, 0, 0) glPushMatrix() #glLoadIdentity() glScale(0.005, 0.01, -0.01) glTranslate(-45, 0, -20) #glTranslate(-180,-70,0) glTranslate(-wdth, 0, 0) self.letters.drawString(k[2:4]) glPopMatrix() glLoadIdentity() gluLookAt(0, 0, 2.5, 0, 0, 0, 0, 1, 0) glScale(0.01, 0.01, -0.01) glTranslate(-180, -70, 0) if debug == True: self.letters.drawString('X:' + str(self.level.solomon.x) + ' Y:' + str(self.level.solomon.y)) glTranslate(0, 0 - 15, 0) gx, gy = int(self.level.solomon.x), int(self.level.solomon.y) self.letters.drawString('G {0} on: {1} below: {2}'.format( str((gx, gy)), self.level.grid[gy][gx], self.level.grid[gy - 1][gx])) glTranslate(0, 0 - 15, 0) self.letters.drawString('') glutSwapBuffers()
def set_look_at(self): gluLookAt(self.eye[0], self.eye[1], self.eye[2], self.target[0], self.target[1], self.target[2], self.up[0], self.up[1], self.up[2])
def OnPaint(self, event): # startTime = time.time() if not self.init: self.context = GLContext(self) self.SetCurrent(self.context) glEnable(GL_DEPTH_TEST); self.init = True if self._refreshAll: glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() # prepareTime = time.time() - startTime if self.dataNum == 0: self.SwapBuffers() return eyePos = self.eyeDistance ex = 0.0 ey = 0.0 ez = 0.0 dx = 0.0 dy = 0.0 dz = 0.0 ux = 0.0 uy = 0.0 uz = 0.0 xLen = max(abs(self.xMax), abs(self.xMin)) * 2 yLen = max(abs(self.yMax), abs(self.yMin)) * 2 zLen = max(abs(self.zMax), abs(self.zMin)) * 2 # print 'transX, transY:', self.transX, self.transY if self.is3D: r2s = max(xLen, yLen, zLen) / self.size.width tX = self.transX * r2s tY = self.transY * r2s if not zLen == 0: z = zLen / 2 if yLen / zLen > self.size.width / self.size.height: z = yLen * self.size.height / self.size.width / 2 z *= 1.5 usedAngle = pi / 2 - viewPosAngle cfovy1 = (eyePos - z * cos(usedAngle)) / sqrt(eyePos * eyePos + z * z - 2 * eyePos * z * cos(usedAngle)) cfovy2 = (eyePos - z * cos(pi - usedAngle)) / sqrt(eyePos * eyePos + z * z - 2 * eyePos * z * cos(pi - usedAngle)) fovy1 = degrees(acos(cfovy1)) fovy2 = degrees(acos(cfovy2)) self.fovy = 3 * max(fovy1, fovy2) angleX = viewPosAngle + radians(self.angleHorizontal) angleZ = viewPosAngle + radians(self.angleVertical) ex = eyePos * cos(angleZ) * cos(angleX) ey = eyePos * cos(angleZ) * sin(angleX) ez = eyePos * sin(angleZ) ux = 0.0 uy = cos(pi / 2 - radians(self.angleFlat)) uz = sin(pi / 2 - radians(self.angleFlat)) flatAngle = radians(self.angleFlat) dx = -tX * cos(flatAngle) * sin(angleX) - tX * sin(flatAngle) * sin(angleZ) * sin(angleX) dx += tY * sin(flatAngle) * sin(angleX) - tY * cos(flatAngle) * sin(angleZ) * cos(angleX) dy = tX * cos(flatAngle) * cos(angleX) - tX * sin(flatAngle) * sin(angleZ) * cos(angleX) dy += -tY * sin(flatAngle) * cos(angleX) - tY * cos(flatAngle) * sin(angleZ) * sin(angleX) dz = tX * sin(flatAngle) * cos(angleZ) dz += tY * cos(flatAngle) * cos(angleZ) else: r2s = xLen / self.size.width dx = self.transX * r2s dy = self.transY * r2s dz = 0.0 y = yLen / 2 if xLen / yLen > self.size.width / self.size.height: y = xLen * self.size.height / self.size.width / 2 y += yLen / 10 self.fovy = 2 * degrees(atan(y / eyePos)) ez = eyePos ux = sin(radians(self.angleFlat)) uy = cos(radians(self.angleFlat)) uz = 0.0 scale = 1 if self.size != None: scale = float(self.size.width) / self.size.height # userCalculationTime = time.time() - startTime - prepareTime glMatrixMode(GL_PROJECTION) glLoadIdentity() if self.is3D: gluPerspective(self.fovy * self.scaleFactor, scale, 0.1, self.eyeDistance * 2) else: gluPerspective(self.fovy * self.scaleFactor, scale, self.eyeDistance - self.zMax - 10, self.eyeDistance - self.zMin + 10) glMatrixMode(GL_MODELVIEW) glLoadIdentity() gluLookAt(ex, ey, ez, -dx, -dy, -dz, ux, uy, uz) self._startPointIdx = 0 if self.isDragging: # draw the frame instead of all data glLineWidth(1.0) glColor3f(0.0, 0.5, 0.0) glBegin(GL_LINES) glVertex3f(self.xMin, self.yMin, self.zMin) # 1 glVertex3f(self.xMax, self.yMin, self.zMin) # 2 glVertex3f(self.xMax, self.yMin, self.zMin) # 2 glVertex3f(self.xMax, self.yMax, self.zMin) # 3 glVertex3f(self.xMax, self.yMax, self.zMin) # 3 glVertex3f(self.xMin, self.yMax, self.zMin) # 4 glVertex3f(self.xMin, self.yMax, self.zMin) # 4 glVertex3f(self.xMin, self.yMin, self.zMin) # 1 glVertex3f(self.xMin, self.yMin, self.zMin) # 1 glVertex3f(self.xMin, self.yMin, self.zMax) # 5 glVertex3f(self.xMin, self.yMin, self.zMax) # 5 glVertex3f(self.xMax, self.yMin, self.zMax) # 6 glVertex3f(self.xMax, self.yMin, self.zMax) # 6 glVertex3f(self.xMax, self.yMax, self.zMax) # 7 glVertex3f(self.xMax, self.yMax, self.zMax) # 7 glVertex3f(self.xMin, self.yMax, self.zMax) # 8 glVertex3f(self.xMin, self.yMax, self.zMax) # 8 glVertex3f(self.xMin, self.yMin, self.zMax) # 5 glVertex3f(self.xMax, self.yMin, self.zMin) # 2 glVertex3f(self.xMax, self.yMin, self.zMax) # 6 glVertex3f(self.xMax, self.yMax, self.zMin) # 3 glVertex3f(self.xMax, self.yMax, self.zMax) # 7 glVertex3f(self.xMin, self.yMax, self.zMin) # 4 glVertex3f(self.xMin, self.yMax, self.zMax) # 8 glEnd() glFlush() self.SwapBuffers() return glEnableClientState(GL_VERTEX_ARRAY) if self.colorsNum >= self.dataNum: glEnableClientState(GL_COLOR_ARRAY) glDrawBuffer(GL_FRONT_AND_BACK) if self._startPointIdx + self._drawnPointsNum >= self.dataNum: glDrawArrays(GL_POINTS, self._startPointIdx, self.dataNum - self._startPointIdx) if self.displaySelected: selNum = len(self.displayedSelPoints) if selNum >= 2: glLineWidth(2.0) glColor3f(0.0, 1.0, 0.0) glBegin(GL_LINES) for i in xrange(1, selNum): glVertex3f(self.displayedSelPoints[i - 1][0], self.displayedSelPoints[i - 1][1], self.displayedSelPoints[i - 1][2]) glVertex3f(self.displayedSelPoints[i][0], self.displayedSelPoints[i][1], self.displayedSelPoints[i][2]) glVertex3f(self.displayedSelPoints[selNum - 1][0], self.displayedSelPoints[selNum - 1][1], self.displayedSelPoints[selNum - 1][2]) glVertex3f(self.displayedSelPoints[0][0], self.displayedSelPoints[0][1], self.displayedSelPoints[0][2]) glEnd() self._refreshAll = True else: glDrawArrays(GL_POINTS, self._startPointIdx, self._drawnPointsNum) self._refreshAll = False self._isFront = not self._isFront self._startPointIdx += self._drawnPointsNum if self._isFront else 0 glDisableClientState(GL_VERTEX_ARRAY) if self.colorsNum >= self.dataNum: glDisableClientState(GL_COLOR_ARRAY) glFlush() self.SwapBuffers() # drawingTime = time.time() - startTime - prepareTime - userCalculationTime # print "preparation time:", str(prepareTime), "user calculation time:",\ # str(userCalculationTime), "drawing time:", str(drawingTime) if not self._refreshAll: PostEvent(self, PaintEvent()) event.Skip()
def look(self): glMatrixMode(GL_MODELVIEW) glLoadIdentity() gluLookAt(self.pos.x, self.pos.y, self.pos.z, self.target.x, self.target.y, self.target.z, self.up.x, self.up.y, self.up.z)
def rungame(): global gsh global tickinterval global playerlist global chatitems global scene_matrix tickinterval = 50 try: mode = argv[1] if mode == "s": port = argv[2] if len(argv) > 3: tickinterval = int(argv[3]) elif mode == "c": addr = argv[2] port = argv[3] except: print "usage:" print argv[0], "s port [ticksize=50]" print argv[0], "c addr port" print "s is for server mode, c is for client mode." sys.exit() if mode == "c": init() loadImagery() if mode == "s": # in server mode gs = network.initServer(int(port)) elif mode == "c": # in client mode gs = network.initClient(addr,int(port)) else: print "specify either 's' or 'c' as mode." sys.exit() # sets some stuff for the network sockets. network.setupConn() # this is important for the simulation. gs.tickinterval = tickinterval # in order to be reactive, the state history, which is currently server-side # only, has to incorporate input events at the time they actually happened, # rather than when they were received. Thus, a number of old gamestates is # preserved. # # on the client, the history simply deals with python-object changes that # update proxy objects. gsh = StateHistory(gs) # since the server is dedicated and headless now, we don't need a ship for it if mode == "c": # this is used to fix the camera on the ship and display information about # his ship to the player. mystateid = network.clients[None].stateid # a proxy is an object, that will automatically be updated by the gamestate # history object to always reflect the current object. This is accomplished # with black magic. localplayer = gs.getById(mystateid).getProxy(gsh) # yay! play the game! # inits pygame and opengl. running = True timer.wantedFrameTime = tickinterval * 0.001 timer.startTiming() timer.gameSpeed = 1 # this variable is used to determine, when it would be wise to skip # displaying a single gamestate, to catch up with the time the data # from the server is received. catchUpAccum = 0 cam_h = 10 cam_v = 10 if mode == "c": playerlist = [] makePlayerList() # used for chat. sentence = "" textthing = Text(sentence) def updateTextThing(): textthing.renderText(sentence) pick = [0, 0] while running: timer.startFrame() if mode == "c": for event in pygame.event.get(): if event.type == QUIT: running = False elif event.type == MOUSEMOTION: try: pick = pickFloor(*event.pos) except: pass elif event.type == MOUSEBUTTONDOWN: sendCmd("t" + pack("!dd", *pick)) elif event.type == KEYDOWN: if event.key == K_ESCAPE: running = False # chat stuff elif K_a <= event.key <= K_z: sentence += chr(ord('a') + event.key - K_a) updateTextThing() elif event.key == K_SPACE: sentence += " " updateTextThing() elif event.key == K_BACKSPACE: sentence = sentence[:-1] updateTextThing() elif event.key == K_RETURN: if sentence: network.sendChat(sentence) sentence = "" updateTextThing() # end chat stuff # player control stuff kp = pygame.key.get_pressed() if kp[K_LEFT]: cam_h -= 1 if kp[K_RIGHT]: cam_h += 1 if kp[K_UP]: cam_v += 1 if kp[K_DOWN]: cam_v -= 1 # end player control stuff catchUpAccum += timer.catchUp # only if the catchUp time is below our patience or we run the server, # the gamestate should be rendered and calculated. if catchUpAccum < 2: glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) with glIdentityMatrix(): # put the player in the middle of the screen gluLookAt(cam_h, cam_v, 10, localplayer.position[0], localplayer.position[1], 0, 0, 0, 1) scene_matrix = glGetDoublev(GL_MODELVIEW_MATRIX) # render everything with glMatrix(): renderGameGrid(localplayer) renderWholeState(gsh[-1]) with glMatrix(): glDisable(GL_TEXTURE_2D) with glPrimitive(GL_LINES): glVertex(pick[0], pick[1], 4) glVertex(pick[0], pick[1], -4) glEnable(GL_TEXTURE_2D) with glIdentityMatrix(): glScalef(1./32, 1./32, 1) # do gui stuff here with glMatrix(): glScale(3, 3, 1) for pli in playerlist: pli.draw() glTranslate(0, 16, 0) with glMatrix(): glScale(2, 2, 1) glTranslate(24, 540, 0) for msg in [textthing] + chatitems[::-1]: msg.draw() glTranslate(0, -17, 0) pygame.display.flip() # for the server, this lets new players in, distributes chat messages and # reacts to player inputs. network.pumpEvents() if mode == "c": if catchUpAccum > 2: print "catchUpAccum is", catchUpAccum catchUpAccum = 0 timer.endFrame() # exit pygame if mode == "c": pygame.quit()
def __init__(self, w, h, depth, fullscreen, caption, font = None): """ Initializes the engine. Parameters: w,h: screen width/height. depth: bits per pixel. fullscreen: if true, the window is fullscreen. caption: the windows caption. font: the pygame font the engine should use. if None, the default is loaded. """ pygame.init() pygame.font.init() pygame.mixer.init() self.ratio_x = w self.ratio_y = h self.screen_w = w self.screen_h = h self.ticks= pygame.time.get_ticks() self.camx = 0.0 self.camy = 0.0 self.zoom = 1.0 self.hud_mode = False self.loop = 0 self.quad_v = [ -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5] self.quad_v_gl = (GLfloat * len(self.quad_v))(*self.quad_v) self.quad_uvs = [0,0, 1,0, 1,1, 0,1] self.quad_uvs_gl = (GLfloat * len(self.quad_uvs))(*self.quad_uvs) if fullscreen: self.screen = pygame.display.set_mode((w, h), OPENGL | DOUBLEBUF | FULLSCREEN) else: self.screen = pygame.display.set_mode((w, h), OPENGL | DOUBLEBUF) pygame.display.set_caption(caption) glEnable(GL_TEXTURE_2D) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glShadeModel(GL_SMOOTH) glClearDepth(1.0) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LEQUAL) glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST) glEnable(GL_ALPHA_TEST) self.face = glGenLists(1) glNewList(self.face,GL_COMPILE) glBegin(GL_QUADS) glTexCoord2f(0,0) glVertex3f(-0.5, -0.5, 0) glTexCoord2f(1,0) glVertex3f(0.5, -0.5, 0) glTexCoord2f(1,1) glVertex3f(0.5, 0.5, 0) glTexCoord2f(0,1) glVertex3f(-0.5, 0.5, 0) glEnd() glEndList() if font == None: self.font = pygame.font.Font("freesansbold.ttf", 80) else: self.font = font self.text = self.Text("", self.font) #set the default viewport glMatrixMode( GL_PROJECTION ); glLoadIdentity(); glOrtho( (-w/2), (w/2), (h/2), (-h/2), -100, 100 ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); gluLookAt(0,0,20, 0,0,0, 0,1,0);