示例#1
0
    def render(self):
        """ The render pass for the scene """
        self.init_view()

        # Enable lighting and color
        glEnable(GL_LIGHTING)

        glClearColor(0.4, 0.4, 0.4, 0.0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        # Load the modelview matrix from the current state of the trackball
        glMatrixMode(GL_MODELVIEW)
        glPushMatrix()
        glLoadIdentity()
        loc = self.interaction.translation
        glTranslated(-loc[0], -loc[1], -loc[2])
        glMultMatrixf(self.interaction.trackball.matrix)

        # store the inverse of the current modelview.
        currentModelView = numpy.array(glGetFloatv(GL_MODELVIEW_MATRIX))
        self.modelView = numpy.transpose(currentModelView)
        self.inverseModelView = inv(numpy.transpose(currentModelView))

        # render the scene. This will call the render function for each object in the scene
        self.scene.render()

        # draw the grid
        glDisable(GL_LIGHTING)
        glCallList(G_OBJ_PLANE)
        glPopMatrix()

        # flush the buffers so that the scene can be drawn
        glFlush()
示例#2
0
文件: viewer.py 项目: darius/chispa
    def render(self):
        """ The render pass for the scene """
        self.init_view()

        # Enable lighting and color
        glEnable(GL_LIGHTING)

        glClearColor(0.4, 0.4, 0.4, 0.0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        # Load the modelview matrix from the current state of the trackball
        glMatrixMode(GL_MODELVIEW)
        glPushMatrix()
        glLoadIdentity()
        loc = self.interaction.translation
        glTranslated(-loc[0], -loc[1], -loc[2])
        glMultMatrixf(self.interaction.trackball.matrix)

        # store the inverse of the current modelview.
        currentModelView = numpy.array(glGetFloatv(GL_MODELVIEW_MATRIX))
        self.modelView = numpy.transpose(currentModelView)
        self.inverseModelView = inv(numpy.transpose(currentModelView))

        # render the scene. This will call the render function for each object in the scene
        self.scene.render()

        # draw the grid
        glDisable(GL_LIGHTING)
        glCallList(G_OBJ_PLANE)
        glPopMatrix()

        # flush the buffers so that the scene can be drawn
        glFlush()
示例#3
0
def mouseMove(event):
    global lastPosX, lastPosY, zoomScale, xRot, yRot, zRot

    if event.type == pygame.MOUSEBUTTONDOWN and event.button == 4:
        glScaled(1.05, 1.05, 1.05)
    elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 5:
        glScaled(0.95, 0.95, 0.95)

    if event.type == pygame.MOUSEMOTION:
        x, y = event.pos
        dx = x - lastPosX
        dy = y - lastPosY

        mouseState = pygame.mouse.get_pressed()
        if mouseState[0]:
            modelView = (GLfloat * 16)()
            mvm = glGetFloatv(GL_MODELVIEW_MATRIX, modelView)

            temp = (GLfloat * 3)()
            temp[0] = modelView[0] * dy + modelView[1] * dx
            temp[1] = modelView[4] * dy + modelView[5] * dx
            temp[2] = modelView[8] * dy + modelView[9] * dx
            norm_xy = math.sqrt(temp[0] * temp[0] + temp[1] * temp[1] +
                                temp[2] * temp[2])
            glRotatef(math.sqrt(dx * dx + dy * dy), temp[0] / norm_xy,
                      temp[1] / norm_xy, temp[2] / norm_xy)

        lastPosX = x
        lastPosY = y
示例#4
0
文件: stencil.py 项目: gavine199/pymt
def stencilPush():
    '''Create a new stack in stencil stack.
    All the next draw will be done in stencil buffer until
    stencilUse() will be called.'''
    global __stencil_stack
    glPushAttrib(GL_STENCIL_BUFFER_BIT | GL_STENCIL_TEST)

    # enable stencil test if not yet enabled
    if not glIsEnabled(GL_STENCIL_TEST):
        glClearStencil(0)
        glClear(GL_STENCIL_BUFFER_BIT)
        glEnable(GL_STENCIL_TEST)

    # increment the draw buffer
    glStencilFunc(GL_NEVER, 0x0, 0x0)
    glStencilOp(GL_INCR, GL_INCR, GL_INCR)
    glColorMask(0, 0, 0, 0)

    # save model view
    m = glGetFloatv(GL_MODELVIEW_MATRIX)
    __stencil_stack_view.append(m)

    # start recording GL operation
    dl = GlDisplayList()
    dl.start()
    __stencil_stack_dl.append(dl)

    __stencil_stack += 1
示例#5
0
    def SetupProjection(self, width = 640, 
                              height = 480, 
                              zNear = 5., 
                              zFar = 300.):
        """ Sets up the projection matrix for opengl.
        """
    	# set the projection transformation
	glMatrixMode(GL_PROJECTION)
	glLoadIdentity()

	#TODO: replace the glu call with something else.
	#gluPerspective(45.0, float(width) / height, scale * 50.0, scale * 1000.0)
	#gluPerspective(45.0, float(self.width) / float(self.height), 5.0, 1000.0)
        self.zNear = zNear
	self.zFar = zFar
        self.buffer_calc_a = self.zFar / ( self.zFar - self.zNear )
        self.buffer_calc_b = self.zFar * self.zNear / ( self.zNear - self.zFar )



	gluPerspective(45.0, 
	               float(width) / float(height), 
		       self.zNear,
		       self.zFar)

	self.gl_projection_matrix = glGetFloatv(GL_PROJECTION_MATRIX)

	# set the model transformation
	glMatrixMode(GL_MODELVIEW)
示例#6
0
    def render(self):
        #init shadow matrix
        self.init_view()

        #open light
        glEnable(GL_LIGHTING)

        #clear color and depth caches
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        #set model view matrix(danwei matrix is ok)
        #set trackball's rotate matrix as Modelview
        glMatrixMode(GL_MODELVIEW)
        glPushMatrix()

        #replace now-matrix with hengdeng matrix
        glLoadIdentity()
        glMultMatrixf(self.interaction.trackball.matrix)

        #save Modelview matrix, later change system with anti-matrix
        currentModelView = numpy.array(glGetFloatv(GL_MODELVIEW_MATRIX))
        self.modelView = numpy.transpose(currentModelView)
        self.inverseModelView = inv(numpy.transpose(currentModelView))

        #rend the scene
        self.scene.render()

        #after each shadow , huifu light state
        glDisable(GL_LIGHTING)
        glPopMatrix()

        glFlush()
示例#7
0
文件: stencil.py 项目: Markitox/pymt
def stencilPush():
    '''Create a new stack in stencil stack.
    All the next draw will be done in stencil buffer until
    stencilUse() will be called.'''
    global __stencil_stack
    glPushAttrib(GL_STENCIL_BUFFER_BIT | GL_STENCIL_TEST)

    # enable stencil test if not yet enabled
    if not glIsEnabled(GL_STENCIL_TEST):
        glClearStencil(0)
        glClear(GL_STENCIL_BUFFER_BIT)
        glEnable(GL_STENCIL_TEST)

    # increment the draw buffer
    glStencilFunc(GL_NEVER, 0x0, 0x0)
    glStencilOp(GL_INCR, GL_INCR, GL_INCR)
    glColorMask(0, 0, 0, 0)

    # save model view
    m = glGetFloatv(GL_MODELVIEW_MATRIX)
    __stencil_stack_view.append(m)

    # start recording GL operation
    dl = GlDisplayList()
    dl.start()
    __stencil_stack_dl.append(dl)

    __stencil_stack += 1
示例#8
0
    def render(self):
        #初始化投影矩阵
        self.init_view()

        #启动光照
        glEnable(GL_LIGHTING)
        #清空颜色缓存与深度缓存
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        #设置模型视图矩阵,这节课先用单位矩阵就行了。
        glMatrixMode(GL_MODELVIEW)
        glPushMatrix()
        glLoadIdentity()
        glMultMatrixf(self.interaction.trackball.matrix)

        # 存储ModelView矩阵与其逆矩阵之后做坐标系转换用
        currentModelView = numpy.array(glGetFloatv(GL_MODELVIEW_MATRIX))
        self.modelView = numpy.transpose(currentModelView)
        self.inverseModelView = inv(numpy.transpose(currentModelView))
        #渲染场景
        self.scene.render()

        #每次渲染后复位光照状态
        glDisable(GL_LIGHTING)
        glCallList(G_OBJ_PLANE)
        glPopMatrix()
        #把数据刷新到显存上
        glFlush()
示例#9
0
文件: View.py 项目: char-lie/mfm
 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')
示例#10
0
文件: View.py 项目: fossabot/mfm
 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')
示例#11
0
 def loadMatrixSlow(self):
     """ set the texture matrix to: bias * crop * projection * modelView * inverseSceneModelView. """
     glLoadMatrixf( ShadowProjectiveTextureMatrix.biasMatrix )
     glMultMatrixf( self.camera.modelViewProjectionCropMatrix )
     glMultMatrixf( self.sceneCamera.inverseModelViewMatrix )
     
     # compute a normal matrix for the same thing (to transform the normals)
     # Basically, N = ((L)^-1)^-t
     self.normalMatrix = transpose( inv(
             glGetFloatv( GL_TEXTURE_MATRIX ) ) )
示例#12
0
 def get_hardware(self) :
   ''' Return the current MODELVIEW matrix as an array. '''
   
   matrix_get=glGetFloatv(GL_MODELVIEW_MATRIX)
   
   modelview_matrix[0]=matrix_get[0][0] ; modelview_matrix[4]=matrix_get[0][1] ; modelview_matrix[8] =matrix_get[0][2] ; modelview_matrix[12]=matrix_get[0][3] ;
   modelview_matrix[1]=matrix_get[1][0] ; modelview_matrix[5]=matrix_get[1][1] ; modelview_matrix[9] =matrix_get[1][2] ; modelview_matrix[13]=matrix_get[1][3] ;
   modelview_matrix[2]=matrix_get[2][0] ; modelview_matrix[6]=matrix_get[2][1] ; modelview_matrix[10]=matrix_get[2][2] ; modelview_matrix[14]=matrix_get[2][3] ;
   modelview_matrix[4]=matrix_get[3][0] ; modelview_matrix[7]=matrix_get[3][1] ; modelview_matrix[11]=matrix_get[3][2] ; modelview_matrix[15]=matrix_get[3][3] ;
   
   return modelview_matrix
示例#13
0
    def calc_rotation_matrix(self, x, y, z):
        '''
        '''
        glPushMatrix()
        glLoadIdentity()
        for r in [[x, 1, 0, 0], [y, 0, 1, 0], [z, 0, 0, 1]]:
            glRotatef(*r)
        m = glGetFloatv(GL_MODELVIEW_MATRIX)
        glPopMatrix()

        rot = [[y for j, y in enumerate(x) if j <= 2] for i, x in enumerate(m) if i <= 2]
        return m, rot
示例#14
0
    def _set_raster_pos(x, y):  # staticmethod
        """
        """
        # If x or y is exactly 0, then numerical roundoff errors can make the raster position invalid.
        # Using 0.1 instead apparently fixes it, and causes no noticable image quality effect.
        # (Presumably they get rounded to integer window positions after the view volume clipping,
        #  though some effects I saw implied that they don't get rounded, so maybe 0.1 is close enough to 0.0.)
        # This only matters when GLPane size is 100x100 or less,
        # or when drawing this in lower left corner for debugging,
        # so we don't have to worry about whether it's perfect.
        # (The known perfect fix is to initialize both matrices, but we don't want to bother,
        #  or to worry about exceeding the projection matrix stack depth.)
        x1 = max(x, 0.1)
        y1 = max(y, 0.1)

        depth = 0.1  # this should not matter, as long as it's within the viewing volume
        x1, y1, z1 = gluUnProject(x1, y1, depth)
        glRasterPos3f(
            x1, y1, z1
        )  # z1 does matter (when in perspective view), since this is a 3d position
        # Note: using glWindowPos would be simpler and better, but it's not defined
        # by the PyOpenGL I'm using. [bruce iMac G5 070626]
        ### UPDATE [bruce 081203]: glWindowPos2i *is* defined, at least on my newer Mac.
        # There are lots of variants, all suffix-typed with [23][dfis]{,v}.
        # I need to check whether it's defined on the older Macs too, then use it here. ####FIX

        if not glGetBooleanv(GL_CURRENT_RASTER_POSITION_VALID):
            # This was happening when we used x, y = exact 0,
            # and was causing the image to not get drawn sometimes (when mousewheel zoom was used).
            # It can still happen for extreme values of mousewheel zoom (close to the ones
            # which cause OpenGL exceptions), mostly only when pos = (0, 0) but not entirely.
            # Sometimes the actual drawing positions can get messed up then, too.
            # This doesn't matter much, but indicates that re-initing the matrices would be
            # a better solution if we could be sure the projection stack depth was sufficient
            # (or if we reset the standard projection when done, rather than using push/pop).
            print "bug: not glGetBooleanv(GL_CURRENT_RASTER_POSITION_VALID); pos =", x, y
            # if this happens, the subsequent effect is that glDrawPixels draws nothing
        else:
            # verify correct raster position
            px, py, pz, pw = glGetFloatv(GL_CURRENT_RASTER_POSITION)
            if not (0 <= px - x < 0.4) and (0 <= py - y <
                                            0.4):  # change to -0.4 < px - x ??
                print "LIKELY BUG: glGetFloatv(GL_CURRENT_RASTER_POSITION) = %s" % [
                    px, py, pz, pw
                ]
                # seems to be in window coord space, but with float values,
                # roughly [0.1, 0.1, 0.1, 1.0] but depends on viewpoint, error about 10**-5
            pass

        return
示例#15
0
    def set_perspective(self, fovy):
        """
        Set the perspective view
        """
        # Calculate aspect
        aspect = self.width / self.height

        # Make changes to projection matrix
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        # Set the perspective accordingly
        gluPerspective(fovy, aspect, 0.1, 10.0)

        self.matrix = glGetFloatv(GL_PROJECTION_MATRIX)
示例#16
0
    def set_perspective(self, fovy):
        """
        Set the perspective view
        """
        # Calculate aspect
        aspect = self.width / self.height

        # Make changes to projection matrix
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        # Set the perspective accordingly
        gluPerspective(fovy, aspect, 0.1, 10.0)

        self.matrix = glGetFloatv(GL_PROJECTION_MATRIX)
示例#17
0
 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 )
示例#18
0
 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 )
示例#19
0
文件: main.py 项目: iwyoo/Vivaldi
	def get_function_package(function_name, argument_package_list, return_package, work_range, merge_func='', merge_order=''):
		fp = Function_package()
		fp.set_function_name(function_name)
		fp.set_function_args(argument_package_list)
		from OpenGL.GL import glGetFloatv, GL_MODELVIEW_MATRIX
		fp.mmtx					= glGetFloatv(GL_MODELVIEW_MATRIX)
		def flip_diagonal(mmtx):
			new_mmtx = numpy.empty((4,4),dtype=numpy.float32)		
			for i in range(4):
				for j in range(4):
					new_mmtx[i][j] = mmtx[j][i]
			return new_mmtx
		fp.mmtx = flip_diagonal(fp.mmtx)
		
		fp.work_range = work_range
		fp.output = return_package
		return fp
示例#20
0
文件: main.py 项目: hvcl-old/Vivaldi
	def get_function_package(function_name, argument_package_list, return_package, work_range, merge_func='', merge_order=''):
		fp = Function_package()
		fp.set_function_name(function_name)
		fp.set_function_args(argument_package_list)
		from OpenGL.GL import glGetFloatv, GL_MODELVIEW_MATRIX
		fp.mmtx					= glGetFloatv(GL_MODELVIEW_MATRIX)
		def flip_diagonal(mmtx):
			new_mmtx = numpy.empty((4,4),dtype=numpy.float32)		
			for i in range(4):
				for j in range(4):
					new_mmtx[i][j] = mmtx[j][i]
			return new_mmtx
		fp.mmtx = flip_diagonal(fp.mmtx)
		
		fp.work_range = work_range
		fp.output = return_package
		return fp
    def _set_raster_pos(x, y): # staticmethod
        """
        """
        # If x or y is exactly 0, then numerical roundoff errors can make the raster position invalid.
        # Using 0.1 instead apparently fixes it, and causes no noticable image quality effect.
        # (Presumably they get rounded to integer window positions after the view volume clipping,
        #  though some effects I saw implied that they don't get rounded, so maybe 0.1 is close enough to 0.0.)
        # This only matters when GLPane size is 100x100 or less,
        # or when drawing this in lower left corner for debugging,
        # so we don't have to worry about whether it's perfect.
        # (The known perfect fix is to initialize both matrices, but we don't want to bother,
        #  or to worry about exceeding the projection matrix stack depth.)
        x1 = max(x, 0.1)
        y1 = max(y, 0.1)

        depth = 0.1 # this should not matter, as long as it's within the viewing volume
        x1, y1, z1 = gluUnProject(x1, y1, depth)
        glRasterPos3f(x1, y1, z1) # z1 does matter (when in perspective view), since this is a 3d position
            # Note: using glWindowPos would be simpler and better, but it's not defined
            # by the PyOpenGL I'm using. [bruce iMac G5 070626]
            ### UPDATE [bruce 081203]: glWindowPos2i *is* defined, at least on my newer Mac.
            # There are lots of variants, all suffix-typed with [23][dfis]{,v}.
            # I need to check whether it's defined on the older Macs too, then use it here. ####FIX

        if not glGetBooleanv(GL_CURRENT_RASTER_POSITION_VALID):
            # This was happening when we used x, y = exact 0,
            # and was causing the image to not get drawn sometimes (when mousewheel zoom was used).
            # It can still happen for extreme values of mousewheel zoom (close to the ones
            # which cause OpenGL exceptions), mostly only when pos = (0, 0) but not entirely.
            # Sometimes the actual drawing positions can get messed up then, too.
            # This doesn't matter much, but indicates that re-initing the matrices would be
            # a better solution if we could be sure the projection stack depth was sufficient
            # (or if we reset the standard projection when done, rather than using push/pop).
            print "bug: not glGetBooleanv(GL_CURRENT_RASTER_POSITION_VALID); pos =", x, y
                # if this happens, the subsequent effect is that glDrawPixels draws nothing
        else:
            # verify correct raster position
            px, py, pz, pw = glGetFloatv(GL_CURRENT_RASTER_POSITION)
            if not (0 <= px - x < 0.4) and (0 <= py - y < 0.4): # change to -0.4 < px - x ??
                print "LIKELY BUG: glGetFloatv(GL_CURRENT_RASTER_POSITION) = %s" % [px, py, pz, pw]
                # seems to be in window coord space, but with float values,
                # roughly [0.1, 0.1, 0.1, 1.0] but depends on viewpoint, error about 10**-5
            pass
        
        return
示例#22
0
 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()
示例#23
0
    def render(self):
        """ The render pass for the scene """
        self.init_view()

        glEnable(GL_LIGHTING)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        # Load the modelview matrix from the current state of the trackball
        glMatrixMode(GL_MODELVIEW)
        glPushMatrix()
        glLoadIdentity()
        tar = self.interaction.LookAttarget;
        self.Camera.target = (tar[0],tar[1],tar[2])
        if self.Camera.CameraMode == 'Trackball':
            loc = self.Camera.position;
            #Camera.position
            glTranslated(-loc[0], -loc[1], -loc[2])
            glMultMatrixf(self.interaction.trackball.matrix)
        elif self.Camera.CameraMode == 'LookAt':
            # embed()
            self.Camera.point()
        elif self.Camera.CameraMode == 'LookAtFollow':
            self.Camera.follow()
            self.Camera.point()
        else:
            glMultMatrixf(self.interaction.trackball.matrix) # by default revert to trackball if mode is set incorrectly

        # store the inverse of the current modelview.
        currentModelView = numpy.array(glGetFloatv(GL_MODELVIEW_MATRIX))
        self.modelView = numpy.transpose(currentModelView)
        self.inverseModelView = inv(numpy.transpose(currentModelView))

        # render the scene. This will call the render function for each object in the scene
        self.scene.render()

        # draw the grid
        glDisable(GL_LIGHTING)
        glCallList(G_OBJ_PLANE)
        glPopMatrix()

        # flush the buffers so that the scene can be drawn
        glFlush()
示例#24
0
    def SetupProjection(self, width=640, height=480, zNear=5., zFar=300.):
        """ Sets up the projection matrix for opengl.
        """
        # set the projection transformation
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()

        #TODO: replace the glu call with something else.
        #gluPerspective(45.0, float(width) / height, scale * 50.0, scale * 1000.0)
        #gluPerspective(45.0, float(self.width) / float(self.height), 5.0, 1000.0)
        self.zNear = zNear
        self.zFar = zFar
        self.buffer_calc_a = self.zFar / (self.zFar - self.zNear)
        self.buffer_calc_b = self.zFar * self.zNear / (self.zNear - self.zFar)

        gluPerspective(45.0,
                       float(width) / float(height), self.zNear, self.zFar)

        self.gl_projection_matrix = glGetFloatv(GL_PROJECTION_MATRIX)

        # set the model transformation
        glMatrixMode(GL_MODELVIEW)
示例#25
0
文件: cube.py 项目: mihaiv95/cube
    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()
示例#26
0
文件: cube.py 项目: mihaiv95/cube
 def rotate(self):
     glPushMatrix()
     glLoadMatrixf(self._trans_mat)
     glRotatef(0.5, 0, 1, 0)
     self._trans_mat = glGetFloatv(GL_MODELVIEW_MATRIX)
     glPopMatrix()
示例#27
0
    def _compute_frustum_planes(self): # Piotr 080331
        """
        Compute six planes to be used for frustum culling
        (assuming the use of that feature is enabled,
         which is up to the client code in the main class).

        Whenever the main class client code changes the projection matrix,
        it must either call this method, or set
        self._frustum_planes_available = False to turn off frustum culling.

        @note: this must only be called when the matrices are set up
               to do drawing in absolute model space coordinates.
               Callers which later change those matrices should review
               whether they need to set self._frustum_planes_available = False
               when they change them, to avoid erroneous culling.
        """
        # Get current projection and modelview matrices 
        pmat = glGetFloatv(GL_PROJECTION_MATRIX)
        mmat = glGetFloatv(GL_MODELVIEW_MATRIX)

        # Allocate a composite matrix float[4, 4]
        cmat = [None] * 4
        for i in range(0, 4):
            cmat[i] = [0.0] * 4

        # Compute a composite transformation matrix. 
        # cmat = mmat * pmat         
        for i in range(0, 4):            
            for j in range (0, 4):
                cmat[i][j] = (mmat[i][0] * pmat[0][j] + 
                              mmat[i][1] * pmat[1][j] + 
                              mmat[i][2] * pmat[2][j] + 
                              mmat[i][3] * pmat[3][j])

        # Allocate six frustum planes
        self.fplanes = [None] * 6
        for p in range(0, 6):
            self.fplanes[p] = [0.0] * 4

        # subtract and add the composite matrix rows to get the plane equations
        
        for p in range(0, 3):
            for i in range(0, 4):
                self.fplanes[2*p][i] = cmat[i][3] - cmat[i][p]
                self.fplanes[2*p+1][i] = cmat[i][3] + cmat[i][p]

        # normalize the plane normals
        for p in range(0, 6):
            n = math.sqrt(float(self.fplanes[p][0] * self.fplanes[p][0] +
                                self.fplanes[p][1] * self.fplanes[p][1] +
                                self.fplanes[p][2] * self.fplanes[p][2]))
            if n > 1e-8:
                self.fplanes[p][0] /= n
                self.fplanes[p][1] /= n
                self.fplanes[p][2] /= n
                self.fplanes[p][3] /= n

        # cause self.is_sphere_visible() to use these planes
        self._frustum_planes_available = True # [bruce 080331]

        return
示例#28
0
 def rotate(self):
     glPushMatrix()
     glLoadMatrixf(self._identity_mat)
     glRotatef(1, 0, 1, 0)
     self._identity_mat = glGetFloatv(GL_MODELVIEW_MATRIX)
     glPopMatrix()
示例#29
0
    def draw_mesh(m, lighting_on):

        # Supply vertices
        glEnableClientState(GL_VERTEX_ARRAY)
        m.vbo['v'].bind()
        glVertexPointer(3, GL_FLOAT, 0, m.vbo['v'])
        m.vbo['v'].unbind()

        # Supply normals
        if 'vn' in m.vbo.keys():
            glEnableClientState(GL_NORMAL_ARRAY)
            m.vbo['vn'].bind()
            glNormalPointer(GL_FLOAT, 0, m.vbo['vn'])
            m.vbo['vn'].unbind()
        else:
            glDisableClientState(GL_NORMAL_ARRAY)

        # Supply colors
        if 'vc' in m.vbo.keys():
            glEnableClientState(GL_COLOR_ARRAY)
            m.vbo['vc'].bind()
            glColorPointer(3, GL_FLOAT, 0, m.vbo['vc'])
            m.vbo['vc'].unbind()
        else:
            glDisableClientState(GL_COLOR_ARRAY)

        if ('vt' in m.vbo.keys()) and hasattr(m, 'textureID'):
            glEnable(GL_TEXTURE_2D)
            glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
            glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
            glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE)
            glBindTexture(GL_TEXTURE_2D, m.textureID)

            glEnableClientState(GL_TEXTURE_COORD_ARRAY)
            m.vbo['vt'].bind()
            glTexCoordPointer(2, GL_FLOAT, 0, m.vbo['vt'])
            m.vbo['vt'].unbind()
        else:
            glDisable(GL_TEXTURE_2D)
            glDisableClientState(GL_TEXTURE_COORD_ARRAY)

        # Draw
        if len(m.f) > 0:
            # ie if it is triangulated
            if lighting_on:
                glEnable(GL_LIGHTING)
            else:
                glDisable(GL_LIGHTING)
            glDrawElementsui(GL_TRIANGLES, np.arange(m.f.size,
                                                     dtype=np.uint32))
        else:
            # not triangulated, so disable lighting
            glDisable(GL_LIGHTING)
            glPointSize(2)
            glDrawElementsui(GL_POINTS, np.arange(len(m.v), dtype=np.uint32))
        if hasattr(m, 'v_to_text'):

            glEnable(GL_TEXTURE_2D)
            glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
            glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
                            GL_LINEAR_MIPMAP_LINEAR)
            glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)

            # glEnable(GL_TEXTURE_GEN_S)
            # glEnable(GL_TEXTURE_GEN_T)
            # glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR)
            # glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR)

            bgcolor = np.array(glGetDoublev(GL_COLOR_CLEAR_VALUE))
            fgcolor = 1. - bgcolor

            from .lines import Lines
            sc = float(np.max(np.max(m.v, axis=0) - np.min(m.v, axis=0))) / 10.

            cur_mtx = np.linalg.pinv(glGetFloatv(GL_MODELVIEW_MATRIX).T)
            xdir = cur_mtx[:3, 0]
            ydir = cur_mtx[:3, 1]

            glEnable(GL_LINE_SMOOTH)
            glEnable(GL_BLEND)
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

            for vidx, text in m.v_to_text.items():
                pos0 = m.v[vidx].copy()
                pos1 = m.v[vidx].copy()
                if hasattr(m, 'vn'):
                    pos1 += m.vn[vidx] * sc
                glLineWidth(5.0)
                ln = Lines(v=np.vstack((pos0, pos1)), e=np.array([[0, 1]]))
                glEnable(GL_LIGHTING)
                glColor3f(1. - 0.8, 1. - 0.8, 1. - 1.00)
                MeshViewerSingle.draw_lines(ln)

                glDisable(GL_LIGHTING)

                texture_id = get_textureid_with_text(text, bgcolor, fgcolor)
                glBindTexture(GL_TEXTURE_2D, texture_id)

                glPushMatrix()
                glTranslatef(pos1[0], pos1[1], pos1[2])

                dx = xdir * .10
                dy = ydir * .10
                if False:
                    glBegin(GL_QUADS)

                    glTexCoord2f(1., 0.)
                    glVertex3f(*(+dx + dy))

                    glTexCoord2f(1., 1.)
                    glVertex3f(*(+dx - dy))

                    glTexCoord2f(0., 1.)
                    glVertex3f(*(-dx - dy))

                    glTexCoord2f(0., 0.)
                    glVertex3f(*(-dx + dy))

                    # gluSphere(quadratic,0.05,32,32)
                    glEnd()
                else:
                    glBegin(GL_POLYGON)

                    for r in np.arange(0, np.pi * 2., .01):
                        glTexCoord2f(np.cos(r) / 2. + .5, np.sin(r) / 2. + .5)
                        glVertex3f(*(dx * np.cos(r) + -dy * np.sin(r)))

                    glEnd()
                glPopMatrix()
示例#30
0
    def draw_primitives(self,
                        scalefactor=1.0,
                        center=[0.0, 0.0, 0.0],
                        recenter=False,
                        want_camera=False):

        # measure the bounding box of all our primitives, so that we can
        # recenter them in our field of view
        if recenter:
            all_meshes = self.static_meshes + self.dynamic_meshes
            all_lines = self.static_lines + self.dynamic_lines

            if (len(all_meshes) + len(all_lines)) == 0:
                if want_camera:
                    return {
                        'modelview_matrix': glGetDoublev(GL_MODELVIEW_MATRIX),
                        'projection_matrix':
                        glGetDoublev(GL_PROJECTION_MATRIX),
                        'viewport': glGetIntegerv(GL_VIEWPORT)
                    }
                else:
                    return None

            for m in all_meshes:
                m.v = m.v.reshape((-1, 3))

            all_verts = np.concatenate([
                m.v[m.f.flatten() if len(m.f) > 0 else np.arange(len(m.v))]
                for m in all_meshes
            ] + [l.v[l.e.flatten()] for l in all_lines],
                                       axis=0)

            maximum = np.max(all_verts, axis=0)
            minimum = np.min(all_verts, axis=0)
            center = (maximum + minimum) / 2.
            scalefactor = (maximum - minimum) / 4.
            scalefactor = np.max(scalefactor)
        else:
            center = np.array(center)
            #            for mesh in self.dynamic_meshes :
            #                if mesh.f : mesh.reset_normals()
            all_meshes = self.static_meshes + self.dynamic_meshes
            all_lines = self.static_lines + self.dynamic_lines
        self.current_center = center
        self.current_scalefactor = scalefactor

        glMatrixMode(GL_MODELVIEW)
        glPushMatrix()
        # uncomment to add a default rotation (useful when automatically snapshoting kinect data
        # glRotate(220, 0.0, 1.0, 0.0)

        tf = np.identity(4, 'f') / scalefactor
        tf[:3, 3] = -center / scalefactor
        tf[3, 3] = 1
        cur_mtx = glGetFloatv(GL_MODELVIEW_MATRIX).T

        glLoadMatrixf(cur_mtx.dot(tf).T)

        if want_camera:
            result = {
                'modelview_matrix': glGetDoublev(GL_MODELVIEW_MATRIX),
                'projection_matrix': glGetDoublev(GL_PROJECTION_MATRIX),
                'viewport': glGetIntegerv(GL_VIEWPORT)
            }
        else:
            result = None

        for m in all_meshes:
            if not hasattr(m, 'vbo'):
                # Precompute vertex vbo
                fidxs = m.f.flatten() if len(m.f) > 0 else np.arange(len(m.v))
                allpts = m.v[fidxs].astype(np.float32).flatten()
                vbo = OpenGL.arrays.vbo.VBO(allpts)
                m.vbo = {'v': vbo}

                # Precompute normals vbo
                if hasattr(m, 'vn'):
                    ns = m.vn.astype(np.float32)
                    ns = ns[m.f.flatten(), :]
                    m.vbo['vn'] = OpenGL.arrays.vbo.VBO(ns.flatten())
                elif hasattr(m, 'f') and m.f.size > 0:
                    ns = TriNormals(m.v, m.f).reshape(-1, 3)
                    ns = np.tile(ns, (1, 3)).reshape(-1, 3).astype(np.float32)
                    m.vbo['vn'] = OpenGL.arrays.vbo.VBO(ns.flatten())

                # Precompute texture vbo
                if hasattr(m, 'ft') and (m.ft.size > 0):
                    ftidxs = m.ft.flatten()
                    data = m.vt[ftidxs].astype(np.float32)[:, 0:2]
                    data[:, 1] = 1.0 - 1.0 * data[:, 1]
                    m.vbo['vt'] = OpenGL.arrays.vbo.VBO(data)

                # Precompute color vbo
                if hasattr(m, 'vc'):
                    data = m.vc[fidxs].astype(np.float32)
                    m.vbo['vc'] = OpenGL.arrays.vbo.VBO(data)
                elif hasattr(m, 'fc'):
                    data = np.tile(m.fc, (1, 3)).reshape(-1,
                                                         3).astype(np.float32)
                    m.vbo['vc'] = OpenGL.arrays.vbo.VBO(data)

        for e in all_lines:
            self.draw_lines(e)

        for m in all_meshes:
            if hasattr(m, 'texture_image') and not hasattr(m, 'textureID'):
                self.set_texture(m)
            self.draw_mesh(m, self.lighting_on)

        glMatrixMode(GL_MODELVIEW)
        glPopMatrix()

        return result
示例#31
0
文件: cube.py 项目: mihaiv95/cube
 def move_z(self):
     glLoadMatrixf(self._trans_mat)
     glTranslatef(0, 0, self.tz)
     self._trans_mat = glGetFloatv(GL_MODELVIEW_MATRIX)