Beispiel #1
0
 def bind(self):
     super(HardwareFbo, self).bind()
     HardwareFbo.fbo_stack.append(self.framebuffer)
     glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, self.framebuffer)
     if self.push_viewport:
         glPushAttrib(GL_VIEWPORT_BIT)
         glViewport(0, 0, self.size[0], self.size[1])
Beispiel #2
0
def drawShadowMaps(lights, layerLoc):
    """
    draws shadow maps for debugging.
    note that a special shader is required to display the depth-component-only textures
    """
    
    i = 0
    for light in lights:
        if light.shadowMapArray==None: continue
        shadowMapArray = light.shadowMapArray
        shadowMaps = shadowMapArray.shadowMaps
        
        glBindTexture( GL_TEXTURE_2D_ARRAY, shadowMapArray.texture.glID )
        glTexParameteri( GL_TEXTURE_2D_ARRAY, GL_TEXTURE_COMPARE_MODE, GL_NONE )
        
        for j in range(len(shadowMaps)):
            glViewport(130*i, 0, 128, 128)
            
            glUniform1f(layerLoc, float(j))
            
            glBegin(GL_QUADS)
            glVertex3f(-1.0, -1.0, 0.0)
            glVertex3f( 1.0, -1.0, 0.0)
            glVertex3f( 1.0,  1.0, 0.0)
            glVertex3f(-1.0,  1.0, 0.0)
            glEnd()
            
            i += 1
        
        if shadowMapArray.textureType=="sampler2DArrayShadow":
            glTexParameteri( GL_TEXTURE_2D_ARRAY, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE )
        else:
            glTexParameteri( GL_TEXTURE_2D_ARRAY, GL_TEXTURE_COMPARE_MODE, GL_NONE )
    def resizeGL(self, width, height):
        """
        Called by QtGL when the drawing window is resized.
        """
        #bruce 080912 moved this from GLPane into GLPane_minimal

        self._resize_counter += 1 #bruce 080922
        
        self.width = width
        self.height = height

        glViewport(0, 0, self.width, self.height)
            # example of using a smaller viewport:
            ## glViewport(10, 15, (self.width - 10)/2, (self.height - 15)/3)

        # modify width and height for trackball
        # (note: this was done in GLPane but not in ThumbView until 080912)
        if width < 300:
            width = 300
        if height < 300:
            height = 300
        self.trackball.rescale(width, height)
        
        self.initialised = True
        
        return
Beispiel #4
0
    def initialize(self):
        """
        Set up the viewport.
        """
        x, y = self.viewSize

        # Hide things that are behind other things
        glEnable(GL_DEPTH_TEST)

        # Create the OpenGL viewport, setting the size of the window (in pixels)
        # and defining how the scene is projected onto it.
        glViewport(0, 0, x, y)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        # Field of view, aspect ratio, near clipping, far clipping
        gluPerspective(45.0, x / y, 0.5, 1000.0)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

        # This makes material color properties be defined by glColor calls,
        # necessary to get the right colors when lighting is enabled.
        glEnable(GL_COLOR_MATERIAL)
        # This might be desirable at some point, who knows.
        # glColorMaterial(GL_FRONT_AND_BACK, GL_EMISSION)

        # Make lighting work, because we like lights.
        glEnable(GL_LIGHTING)

        # Make textures work too.
        glEnable(GL_TEXTURE_2D)
Beispiel #5
0
    def do_configure_event(self, event):
        ClientWindow.do_configure_event(self, event)
        drawable = self.glarea.get_gl_drawable()
        context = self.glarea.get_gl_context()

        self.yuv420_shader = None

        # Re-create textures
        self.current_mode = GLClientWindow.MODE_UNINITIALIZED

        if not drawable.gl_begin(context):
            raise Exception("** Cannot create OpenGL rendering context!")

        w, h = self.get_size()
        log("Configure widget size: %d x %d" % (w, h))
        glViewport(0, 0, w, h)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glOrtho(0.0, w, h, 0.0, -1.0, 1.0)
        glMatrixMode(GL_MODELVIEW)
        glEnableClientState(GL_VERTEX_ARRAY)
        glEnableClientState(GL_TEXTURE_COORD_ARRAY)
        glDisable(GL_FRAGMENT_PROGRAM_ARB)

        if self.textures is None:
            self.textures = glGenTextures(3)

        drawable.gl_end()
Beispiel #6
0
    def _set_view_volume(self):
        '''
        '''

        glOrtho(-20, 20, -20, 20, 50, -50)

        size = self.GetSize()
        glViewport(0, 0, size.width, size.height)
    def setupViewport(self, width, height):
        side = min(width, height)
        glViewport((width - side) // 2, (height - side) // 2, side, side)

        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glOrtho(-0.5, +0.5, +0.5, -0.5, 4.0, 15.0)
        glMatrixMode(GL_MODELVIEW)
Beispiel #8
0
 def _reshape(self, width, height):
     self.width = width
     self.height = height
     glViewport(0, 0, width, height)
     self.PMatrix = perspective(40.0, float(width)/height, 0.1, 10000.0)
     self.ball.place([width/2, height/2], height/2)
     self.reshape_hook()
     OpenGL.GLUT.glutPostRedisplay()
Beispiel #9
0
    def gl_init(self):
        drawable = self.gl_begin()
        w, h = self.size
        debug("GL Pixmap backing size: %d x %d, drawable=%s", w, h, drawable)
        if not drawable:
            return  None
        if not self.gl_setup:
            # Ask GL to send us all debug messages
            if GL_DEBUG_OUTPUT and gl_debug_callback and glInitDebugKHR() == True:
                glEnable(GL_DEBUG_OUTPUT)
                glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS)
                glDebugMessageCallback(gl_debug_callback, None)
                glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, None, GL_TRUE)
            # Initialize string_marker GL debugging extension if available
            if glInitStringMarkerGREMEDY and glInitStringMarkerGREMEDY() == True:
                log.info("Extension GL_GREMEDY_string_marker available. Will output detailed information about each frame.")
            else:
                # General case - running without debugger, extension not available
                glStringMarkerGREMEDY = None
            # Initialize frame_terminator GL debugging extension if available
            if glInitFrameTerminatorGREMEDY and glInitFrameTerminatorGREMEDY() == True:
                glFrameTerminatorGREMEDY = None



            self.gl_marker("Initializing GL context for window size %d x %d" % (w, h))
            # Initialize viewport and matrices for 2D rendering
            glViewport(0, 0, w, h)
            glMatrixMode(GL_PROJECTION)
            glLoadIdentity()
            glOrtho(0.0, w, h, 0.0, -1.0, 1.0)
            glMatrixMode(GL_MODELVIEW)
            #TODO glEnableClientState(GL_VERTEX_ARRAY)
            #TODO glEnableClientState(GL_TEXTURE_COORD_ARRAY)

            # Clear to white
            glClearColor(1.0, 1.0, 1.0, 1.0)

            # Default state is good for YUV painting:
            #  - fragment program enabled
            #  - render to offscreen FBO
            glEnable(GL_FRAGMENT_PROGRAM_ARB)
            if self.textures is None:
                self.textures = glGenTextures(5)
                debug("textures for wid=%s of size %s : %s", self.wid, self.size, self.textures)
            if self.offscreen_fbo is None:
                self.offscreen_fbo = glGenFramebuffers(1)

            # Define empty FBO texture and set rendering to FBO
            glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO])
            glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0)

            glBindFramebuffer(GL_FRAMEBUFFER, self.offscreen_fbo)
            glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO], 0)
            glClear(GL_COLOR_BUFFER_BIT)

            self.gl_setup = True
        return drawable
Beispiel #10
0
    def resizeGL(self, width, height):
        if height == 0:
            height = 1

        glViewport(0, 0, width, height)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(45.0, float(width)/float(height), 0.1, 100.0)
        glMatrixMode(GL_MODELVIEW)
Beispiel #11
0
def show(molecule, width=500, height=500,
         show_bonds=True, bonds_method='radii', bonds_param=None,
         camera=None, title='mogli'):
    """
    Interactively show the given molecule with OpenGL. By default, bonds are
    drawn, if this is undesired the show_bonds parameter can be set to False.
    For information on the bond calculation, see Molecule.calculate_bonds.
    If you pass a tuple of camera position, center of view and an up vector to
    the camera parameter, the camera will be set accordingly. Otherwise the
    molecule will be viewed in the direction of the z axis, with the y axis
    pointing upward.
    """
    global _camera
    molecule.positions -= np.mean(molecule.positions, axis=0)
    max_atom_distance = np.max(la.norm(molecule.positions, axis=1))
    if show_bonds:
        molecule.calculate_bonds(bonds_method, bonds_param)

    # If GR3 was initialized earlier, it would use a different context, so
    # it will be terminated first.
    gr3.terminate()

    # Initialize GLFW and create an OpenGL context
    glfw.init()
    glfw.window_hint(glfw.SAMPLES, 16)
    window = glfw.create_window(width, height, title, None, None)
    glfw.make_context_current(window)
    glEnable(GL_MULTISAMPLE)

    # Set up the camera (it will be changed during mouse rotation)
    if camera is None:
        camera_distance = -max_atom_distance*2.5
        camera = ((0, 0, camera_distance),
                  (0, 0, 0),
                  (0, 1, 0))
    camera = np.array(camera)
    _camera = camera

    # Create the GR3 scene
    gr3.setbackgroundcolor(255, 255, 255, 0)
    _create_gr3_scene(molecule, show_bonds)
    # Configure GLFW
    glfw.set_cursor_pos_callback(window, _mouse_move_callback)
    glfw.set_mouse_button_callback(window, _mouse_click_callback)
    glfw.swap_interval(1)
    # Start the GLFW main loop
    while not glfw.window_should_close(window):
        glfw.poll_events()
        width, height = glfw.get_window_size(window)
        glViewport(0, 0, width, height)
        _set_gr3_camera()
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        gr3.drawimage(0, width, 0, height,
                      width, height, gr3.GR3_Drawable.GR3_DRAWABLE_OPENGL)
        glfw.swap_buffers(window)
    glfw.terminate()
    gr3.terminate()
    def gl_init(self):
        #must be called within a context!
        #performs init if needed
        if not self.debug_setup:
            self.debug_setup = True
            self.gl_init_debug()

        if not self.gl_setup:
            w, h = self.size
            self.gl_marker("Initializing GL context for window size %d x %d", w, h)
            # Initialize viewport and matrices for 2D rendering
            glViewport(0, 0, w, h)
            glMatrixMode(GL_PROJECTION)
            glLoadIdentity()
            glOrtho(0.0, w, h, 0.0, -1.0, 1.0)
            glMatrixMode(GL_MODELVIEW)
            # Mesa docs claim: this hint can improve the speed of texturing
            #when perspective-correct texture coordinate interpolation isn't needed,
            #such as when using a glOrtho() projection:
            glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST)
            # Could be more optimal to use vertex arrays:
            # glEnableClientState(GL_VERTEX_ARRAY)
            # glEnableClientState(GL_TEXTURE_COORD_ARRAY)

            # Clear background to transparent black
            glClearColor(0.0, 0.0, 0.0, 0.0)

            # we don't use the depth (2D only):
            glDisable(GL_DEPTH_TEST)
            # only do alpha blending in present_fbo:
            glDisable(GL_BLEND)

            # Default state is good for YUV painting:
            #  - fragment program enabled
            #  - YUV fragment program bound
            #  - render to offscreen FBO
            if self.textures is None:
                self.gl_init_textures()

            # Define empty FBO texture and set rendering to FBO
            glEnable(GL_FRAGMENT_PROGRAM_ARB)
            glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO])
            # nvidia needs this even though we don't use mipmaps (repeated through this file):
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0)
            glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, self.texture_pixel_format, w, h, 0, self.texture_pixel_format, GL_UNSIGNED_BYTE, None)
            glBindFramebuffer(GL_FRAMEBUFFER, self.offscreen_fbo)
            glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO], 0)
            glClear(GL_COLOR_BUFFER_BIT)

            # Create and assign fragment programs
            if not self.shaders:
                self.gl_init_shaders()

            # Bind program 0 for YUV painting by default
            glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.shaders[YUV2RGB_SHADER])
            self.gl_setup = True
Beispiel #13
0
    def gl_init(self):
        drawable = self.gl_begin()
        w, h = self.size
        log("%s.gl_init() GL Pixmap backing size: %d x %d, drawable=%s", self, w, h, drawable)
        if not drawable:
            return  None

        if not self.debug_setup:
            self.debug_setup = True
            self.gl_init_debug()

        if not self.gl_setup:
            self.gl_marker("Initializing GL context for window size %d x %d" % (w, h))
            # Initialize viewport and matrices for 2D rendering
            glViewport(0, 0, w, h)
            glMatrixMode(GL_PROJECTION)
            glLoadIdentity()
            glOrtho(0.0, w, h, 0.0, -1.0, 1.0)
            glMatrixMode(GL_MODELVIEW)
            # Could be more optimal to use vertex arrays:
            # glEnableClientState(GL_VERTEX_ARRAY)
            # glEnableClientState(GL_TEXTURE_COORD_ARRAY)

            # Clear background to transparent black
            glClearColor(0.0, 0.0, 0.0, 0.0)

            # we don't use the depth (2D only):
            glDisable(GL_DEPTH_TEST)
            # only do alpha blending in present_fbo:
            glDisable(GL_BLEND)

            # Default state is good for YUV painting:
            #  - fragment program enabled
            #  - YUV fragment program bound
            #  - render to offscreen FBO
            if self.textures is None:
                self.gl_init_textures()

            # Define empty FBO texture and set rendering to FBO
            glEnable(GL_FRAGMENT_PROGRAM_ARB)
            glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO])
            # nvidia needs this even though we don't use mipmaps (repeated through this file):
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0)
            glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, self.texture_pixel_format, w, h, 0, self.texture_pixel_format, GL_UNSIGNED_BYTE, None)
            glBindFramebuffer(GL_FRAMEBUFFER, self.offscreen_fbo)
            glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO], 0)
            glClear(GL_COLOR_BUFFER_BIT)

            # Create and assign fragment programs
            if not self.shaders:
                self.gl_init_shaders()

            # Bind program 0 for YUV painting by default
            glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.shaders[YUV2RGB_SHADER])
            self.gl_setup = True
        return drawable
Beispiel #14
0
 def _on_configure_event(self, *args):
     log.info("_on_configure_event(%s) size=%s", args, self.size)
     drawable = self.gl_begin()
     assert drawable
     w, h = self.size
     glViewport(0, 0, w, h)
     self._set_view()
     if self.texture_id is None:
         self.config_texture()
     self.gl_end(drawable)
Beispiel #15
0
    def draw_all(self):
        glViewport(0, 0, *self.fb_size)

        self.update_vector_uniform('fb_size', self.fb_size)

        glClearColor(*self.clear_color.as_tuple())
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glEnable(GL_DEPTH_TEST)

        for comm in self._draw_commands.values():
            self._draw_one(comm)
Beispiel #16
0
    def resizeGL(self, w, h):        
        glViewport(0, 0, w, h)
        if self.opengl_resize and self.opengl_data is not None:
            x_scale = self.width() / float(self.opengl_width)
            y_scale = self.height() / float(self.opengl_height)

            if self.opengl_keep_aspect:
                scale = min(x_scale, y_scale)
                glPixelZoom(scale, scale)
            else:
                glPizelZoom(x_scale, y_scale)
Beispiel #17
0
    def init_view(self):
        """ initialize the projection matrix """
        xSize, ySize = glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)
        aspect_ratio = float(xSize) / float(ySize)

        # load the projection matrix. Always the same
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()

        glViewport(0, 0, xSize, ySize)
        gluPerspective(70, aspect_ratio, 0.1, 1000.0)
        glTranslated(0, 0, -15)
Beispiel #18
0
def reshape(w, h):
    glViewport(0, 0, w, h)
    ratio = float(w) / h
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    viewport_center = HEIGHT * ratio / 2
    photo_center = HEIGHT * mosaic_factory.ratio / 2
    left = photo_center - viewport_center
    right = photo_center + viewport_center
    glOrtho(left, right, 0.0, HEIGHT, -1.0, 1.0)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
Beispiel #19
0
    def set_3d(self):
        """Set 3D render mode."""

        glEnable(GL_DEPTH_TEST)

        glViewport(0, 0, self.width, self.height)

        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(75.0, 1.0 * self.width / self.height, 0.001, 1000.0)

        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
Beispiel #20
0
    def set_2d(self):
        """Set 2D render mode."""

        glDisable(GL_DEPTH_TEST)

        glViewport(0, 0, self.width, self.height)

        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glOrtho(0, self.width, 0, self.height, -1, 1)

        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
Beispiel #21
0
    def resize(self, width, height):
        if width < 400:
            glutReshapeWindow(400, height)
        if height < 300:
            glutReshapeWindow(width, 300)
        if height == 0:
            height = 1

        glViewport(0, 0, width, height)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(45.0, float(width)/float(height), 0.1, 10000.0)
        glMatrixMode(GL_MODELVIEW)
Beispiel #22
0
    def resizeGL(self, width, height):
        """
        Called by QtGL when the drawing window is resized.
        """
        self.width = width
        self.height = height

        glViewport(0, 0, self.width, self.height)

        self.trackball.rescale(width, height)

        if not self.initialised:
            self.initialised = True
Beispiel #23
0
    def on_resize(self, width, height):
        """Prepare perspective for window size."""

        print('on resize')

        if height == 0:

            height = 1

        glViewport(0, 0, width, height)

        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(75, 1.0 * width / height, 0.001, 1000.0)
Beispiel #24
0
    def orthogonalPass(self, debugShadows=False):
        """
        draw stuff in orthogonal projection.
        mainly the scene can be post processed here
        and some gui elements could be drawn.
        """

        ### DRAW THE SCENE ###

        # TODO: post shader magic !
        glUseProgram(0)

        # enable the scene texture
        # Note that texture unit 0 should be active now.
        glEnable(GL_TEXTURE_2D)
        glBindTexture(GL_TEXTURE_2D, self.sceneTexture.glID)
        # make sure texture matrix is set to identity
        glMatrixMode(GL_TEXTURE)
        glLoadIdentity()
        glMatrixMode(GL_MODELVIEW)

        glBegin(GL_QUADS)
        glTexCoord2f(0.0, 0.0)
        glVertex3f(0.0, 0.0, -1.0)
        glTexCoord2f(1.0, 0.0)
        glVertex3f(self.winSize[0], 0.0, -1.0)
        glTexCoord2f(1.0, 1.0)
        glVertex3f(self.winSize[0], self.winSize[1], -1.0)
        glTexCoord2f(0.0, 1.0)
        glVertex3f(0.0, self.winSize[1], -1.0)
        glEnd()

        ### DEBUG DRAWINGS ###

        # debug shadow maps
        if debugShadows:
            # draw the shadow maps
            self.visualizeDepthShader.enable()
            layerLoc = glGetUniformLocation(self.visualizeDepthShader.program, "layer")
            drawShadowMaps(self.lights, layerLoc)

            # reset viewport and reset to ffp
            glViewport(0, 0, self.winSize[0], self.winSize[1])
            glUseProgram(0)

        glBindTexture(GL_TEXTURE_2D, 0)
        glDisable(GL_TEXTURE_2D)

        GLApp.orthogonalPass(self)
Beispiel #25
0
    def on_resize(self, width, height):
        # Override the default on_resize handler to create a 3D projection
        glViewport(0, 0, width, height)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(60., width / float(height), .1, 1000.)
        
        glMatrixMode(GL_MODELVIEW)
        
        self.rotspeed = 45 # degrees per second
        
        from ArcBall import ArcBallT
        self.arcball = ArcBallT(width, height)

        return pyglet.event.EVENT_HANDLED
Beispiel #26
0
 def __resize(self, widget, event):
     gldrawable = widget.get_gl_drawable()
     glcontext = widget.get_gl_context()
     # OpenGL begin.
     if not gldrawable.gl_begin(glcontext):
         return
     width = widget.allocation.width
     height = widget.allocation.height
     glViewport (0, 0, width, height)
     glMatrixMode(GL_PROJECTION)
     glLoadIdentity()
     glFrustum(-1.0, 1.0, -1.0, 1.0, 1.5, 300.0)
     glMatrixMode (GL_MODELVIEW)
     gldrawable.gl_end()
     # OpenGL end
     return
    def resizeGL(self, w, h):
        '''
		Resize the GL window
		'''

        glViewport(0, 0, w, h)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glOrtho(0, w, h, 0, -1, 1)
        glMatrixMode(GL_MODELVIEW)
        glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
        self.w = w
        self.h = h

        if self.logoon == "On":
            if self.logo[0] and len(self.logo) == 5:
                self.logo[4].setDrawRect([0, 0, w, h])
Beispiel #28
0
    def init_view(self):
        """ 初始化投影矩阵 """
        xSize, ySize = glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)
        #得到屏幕宽高比
        aspect_ratio = float(xSize) / float(ySize)

        #设置投影矩阵
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()

        #设置视口,应与窗口重合
        glViewport(0, 0, xSize, ySize)
        #设置透视,摄像机上下视野幅度70度
        #视野范围到距离摄像机1000个单位为止。
        gluPerspective(70, aspect_ratio, 0.1, 1000.0)
        #摄像机镜头从原点后退15个单位
        glTranslated(0, 0, -15)
Beispiel #29
0
    def __init__(self, width, height, eyeshift, *args, **kwargs):
        """
        Initiate the projection by recording the width and height of
        the opened window
        """
        self.width = width
        self.height = height

        self.eyeshiftset = [[eyeshift[0].real, eyeshift[0].imag, VIEW_DIST],
                            [eyeshift[1].real, eyeshift[1].imag, VIEW_DIST]]
        self.frust = [
            -0.5 * SCREEN_WIDTH, 0.5 * SCREEN_WIDTH, -0.5 * SCREEN_HEIGHT,
            0.5 * SCREEN_HEIGHT, -200, 40
        ]

        glViewport(0, 0, self.width, self.height)
        glDepthRange(0, 10)
Beispiel #30
0
class GLPixmapBacking(PixmapBacking):
    def __init__(self, wid, w, h, old_backing, mmap_enabled, mmap):
        Backing.__init__(self, wid, mmap_enabled, mmap)
        display_mode = (gtk.gdkgl.MODE_RGB | gtk.gdkgl.MODE_SINGLE)
        # We use single buffer because double doesn't work, figure out why
        try:
            self.glconfig = gtk.gdkgl.Config(mode=display_mode)
        except gtk.gdkgl.NoMatches, e:
            raise Exception("could not find matching mode for %s: %s" %
                            (display_mode, e))
        self._backing = gtk.gdkgl.ext(
            gdk.Pixmap(gdk.get_default_root_window(), w, h))
        log.info("Creating GL pixmap size %d %d " % (w, h))
        self.gldrawable = self._backing.set_gl_capability(self.glconfig)
        log.info("drawable ok")
        # Then create an indirect OpenGL rendering context.
        self.glcontext = gtk.gdkgl.Context(self.gldrawable, direct=True)
        log.info("context ok")
        if not self.glcontext:
            raise Exception("** Cannot create OpenGL rendering context!")
        log.info("OpenGL rendering context is created.")
        self.texture = None
        self.textures = [0]
        self.use_openGL_CSC = True
        self.yuv420_shader = None

        # OpenGL begin
        if not self.gldrawable.gl_begin(self.glcontext):
            return False

        glViewport(0, 0, w, h)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glOrtho(0.0, w, h, 0.0, -1.0, 1.0)
        glMatrixMode(GL_MODELVIEW)
        glEnableClientState(GL_VERTEX_ARRAY)
        glEnableClientState(GL_TEXTURE_COORD_ARRAY)
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
        self.gldrawable.gl_end()

        cr = self._backing.cairo_create()
        if old_backing is not None and old_backing._backing is not None:
            # Really we should respect bit-gravity here but... meh.
            cr.set_operator(cairo.OPERATOR_SOURCE)
            cr.set_source_pixmap(old_backing._backing, 0, 0)
            cr.paint()
            old_w, old_h = old_backing._backing.get_size()
            cr.move_to(old_w, 0)
            cr.line_to(w, 0)
            cr.line_to(w, h)
            cr.line_to(0, h)
            cr.line_to(0, old_h)
            cr.line_to(old_w, old_h)
            cr.close_path()
        else:
            cr.rectangle(0, 0, w, h)
        cr.set_source_rgb(1, 1, 1)
        cr.fill()
    def Start(self):
        """ """
	self._debug("starting", 4)


	width, height = 640, 480
	#width, height = 1024, 768
        self.width, self.height = width, height


        self.InitDisplay(width, height, first_time = 1)

        glViewport(0,0, width, height)

        # sets up the projection matrix.
	self.SetupProjection(width, height)

        self.Load()
Beispiel #32
0
    def init_view(self):
        """ initialize the projection matrix """

        xSize, ySize = glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)

        aspect_ratio = float(xSize) / float(ySize)

        # load the projection matrix. Always the same

        glMatrixMode(GL_PROJECTION)

        glLoadIdentity()

        glViewport(0, 0, xSize, ySize)

        gluPerspective(70, aspect_ratio, 0.1, 1000.0)

        glTranslated(0, 0, -15)
Beispiel #33
0
    def init_view(self):
        """init shadow matrix"""
        xSize, ySize = glutGet(GLUT_WINDOW_WIDTH), gluGet(GLUT_WINDOW_HEIGHT)
        #get screen's kuangaobi
        aspect_ratio = float(xSize) / float(ySize)

        #set shadow matrix
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()

        #set viewport, should be chonghe with window
        glViewport(0, 0, xSize, ySize)

        #set toushi, eyesight width 70 degree, 1000 distance fron camare
        gluPerspective(70, aspect_ratio, 0.1, 1000.0)

        #jinftou back 15 distances from o
        glTranslated(0, 0, -15)
Beispiel #34
0
    def on_resize(self, width, height):
        '''Event called when the window is resized'''
        glViewport(0, 0, width, height)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glFrustum(-width / 2, width / 2, -height / 2, height / 2, .1, 1000)
        glScalef(5000, 5000, 1)
        glTranslatef(-width / 2, -height / 2, -500)
        glMatrixMode(GL_MODELVIEW)

        for w in self.children:
            shw, shh = w.size_hint
            if shw and shh:
                w.size = shw * width, shh * height
            elif shw:
                w.width = shw * width
            elif shh:
                w.height = shh * height
Beispiel #35
0
 def gl_init(self):
     drawable = self.gl_begin()
     w, h = self.size
     log("GL Pixmap backing size: %d x %d, drawable=%s", w, h, drawable)
     if not drawable:
         return None
     if not self.gl_setup:
         glViewport(0, 0, w, h)
         glMatrixMode(GL_PROJECTION)
         glLoadIdentity()
         glOrtho(0.0, w, h, 0.0, -1.0, 1.0)
         glMatrixMode(GL_MODELVIEW)
         glEnableClientState(GL_VERTEX_ARRAY)
         glEnableClientState(GL_TEXTURE_COORD_ARRAY)
         glDisable(GL_FRAGMENT_PROGRAM_ARB)
         if self.textures is None:
             self.textures = glGenTextures(3)
         self.gl_setup = True
     return drawable
Beispiel #36
0
 def gl_init(self):
     drawable = self.gl_begin()
     w, h = self.size
     log("GL Pixmap backing size: %d x %d, drawable=%s", w, h, drawable)
     if not drawable:
         return  None
     if not self.gl_setup:
         glViewport(0, 0, w, h)
         glMatrixMode(GL_PROJECTION)
         glLoadIdentity()
         glOrtho(0.0, w, h, 0.0, -1.0, 1.0)
         glMatrixMode(GL_MODELVIEW)
         glEnableClientState(GL_VERTEX_ARRAY)
         glEnableClientState(GL_TEXTURE_COORD_ARRAY)
         glDisable(GL_FRAGMENT_PROGRAM_ARB)
         if self.textures is None:
             self.textures = glGenTextures(3)
         self.gl_setup = True
     return drawable
Beispiel #37
0
    def paintGL(self, region=None, viewport=None, useItemNames=False):
        """
        viewport specifies the arguments to glViewport. If None, then we use self.opts['viewport']
        region specifies the sub-region of self.opts['viewport'] that should be rendered.
        Note that we may use viewport != self.opts['viewport'] when exporting.
        """
        if viewport is None:
            glViewport(*self.getViewport())
        else:
            glViewport(*viewport)

        bgcolor = self.props.background_color
        glClearColor(*bgcolor)
        glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT)
        self.drawItemTree(useItemNames=useItemNames)

        self.frame_count += 1
        fps = self.frame_count / (self.frame_time.elapsed() / 1000.0)
        if CONFIG.debug:
            _log.debug("FPS: {}".format(fps))
    def _on_configure_event(self, *args):
        """
        Called when the drawing area is resized.

        Sets up the OpenGL view port dimensions.
        """
        print("_on_configure_event(%s)" % str(args))
        gldrawable = self.get_gl_drawable()
        glcontext = self.get_gl_context()
        if gldrawable is None:
            return False
        if not gldrawable.gl_begin(glcontext):
            return False
        glViewport(0, 0, self.allocation.width, self.allocation.height)
        ratio = self.allocation.width / float(self.allocation.height)
        self._set_view(ratio)
        if self.texture_id is None:
            self._create_texture()
        gldrawable.gl_end()
        return False
Beispiel #39
0
    def bind(self):
        super(SoftwareFbo, self).bind()

        # Save current buffer
        w = pymt.getWindow()
        glReadBuffer(GL_BACK)
        self.pixels = glReadPixels(0, 0, w.width, w.height, GL_RGBA, GL_UNSIGNED_BYTE)

        # Push current attrib
        glPushAttrib(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_TEST | GL_STENCIL_BUFFER_BIT)
        glDisable(GL_STENCIL_TEST)

        # Save viewport if asked
        if self.push_viewport:
            glPushAttrib(GL_VIEWPORT_BIT)
            glViewport(0, 0, self.size[0], self.size[1])

        # Draw old Framebuffer
        set_color(1, 1, 1)
        drawTexturedRectangle(self.texture, size=self.size)
Beispiel #40
0
    def updateCamera(self):
        glViewport(0, 0, self._width, self._height)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        aspect = self._width / float(self._height)

        GLU.gluPerspective(45.0, aspect, 1, 1000)

        cx, cy, cz = self.camera_xyz
        rotX, rotY, rotZ = self.camera_rpy
        #print "rotationg", rotX, rotY, rotZ
        #print "moving", cx, cy, cz

        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

        glRotatef(rotX, 1.0, 0.0, 0.0)
        glRotatef(rotY, 0.0, 1.0, 0.0)
        glRotatef(rotZ, 0.0, 0.0, 1.0)
        glTranslatef(-cx, -cy, -cz)
Beispiel #41
0
    def reshapeWindow(self, w, h):

        # preventing dividing by zero if window height is 0
        if h == 0:
            h = 1

        # coefficient to maintain the proportions of the picture when resizing the window
        coef = float(w) / h
        glViewport(0, 0, w, h)

        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()

        if w > h:
            gluOrtho2D(-20.0 * coef, 20.0 * coef, -20.0, 20.0)
        else:
            gluOrtho2D(-20.0, 20.0, -20.0 / coef, 20.0 / coef)

        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
Beispiel #42
0
    def bind(self):
        super(SoftwareFbo, self).bind()

        # Save current buffer
        w = pymt.getWindow()
        glReadBuffer(GL_BACK)
        self.pixels = glReadPixels(0, 0, w.width, w.height, GL_RGBA, GL_UNSIGNED_BYTE)

        # Push current attrib
        glPushAttrib(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_TEST | GL_STENCIL_BUFFER_BIT)
        glDisable(GL_STENCIL_TEST)

        # Save viewport if asked
        if self.push_viewport:
            glPushAttrib(GL_VIEWPORT_BIT)
            glViewport(0, 0, self.size[0], self.size[1])

        # Draw old Framebuffer
        set_color(1, 1, 1)
        drawTexturedRectangle(self.texture, size=self.size)
Beispiel #43
0
    def update(self,
               field_view=None,
               width=None,
               height=None,
               znear=None,
               zfar=None):
        if field_view != None:
            self.field_view = field_view
        if width != None:
            self.width = width
        if height != None:
            self.height = height
        if znear != None:
            self.znear = znear
        if zfar != None:
            self.zfar = zfar

        glViewport(0, 0, self.width, self.height)
        self.__matrix = glm.perspective(self.field_view,
                                        self.width / self.height, self.znear,
                                        self.zfar)
Beispiel #44
0
    def prerenderTiles(self, tiles):
        if not tiles:
            return
        minX = self.pos[0]
        minY = self.pos[1]
        maxX = self.pos[0] + self.micronSize
        maxY = self.pos[1] + self.micronSize
        viewBox = ((minX, minY), (maxX, maxY))
        newTiles = []
        for tile in tiles:
            if tile.intersectsBox(viewBox):
                newTiles.append(tile)
        if newTiles:
            # Allocate memory for our texture, if needed.
            if not self.haveAllocatedMemory:
                self.bindTexture()
                self.refresh()
                self.haveAllocatedMemory = True
            self.numRenderedTiles += len(newTiles)
            glBindFramebuffer(GL_DRAW_FRAMEBUFFER, megaTileFramebuffer)
            glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER,
                    GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
                    self.texture, 0)
            
            glPushMatrix()
            glLoadIdentity()
            glViewport(0, 0, self.pixelSize, self.pixelSize)
            glMatrixMode(GL_PROJECTION)
            glLoadIdentity()
            glOrtho(0, self.micronSize, self.micronSize, 0, 1, 0)
            glTranslatef(-self.pos[0], -self.pos[1], 0)
            glMatrixMode(GL_MODELVIEW)

            glEnable(GL_TEXTURE_2D)
            for tile in newTiles:
                tile.render(viewBox)

            glPopMatrix()            
            glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0)
Beispiel #45
0
    def render_for_picking(self) -> None:
        """Render ViewCube for picking pass."""
        if not self.init():
            return

        glViewport(*self.viewport)

        proj = glm.ortho(-2.3, 2.3, -2.3, 2.3, -2.3, 2.3)
        mat = glm.lookAt(
            vec3(0.0, -1.0, 0.0),  # position
            vec3(0.0, 0.0, 0.0),  # target
            vec3(0.0, 0.0, 1.0))  # up
        modelview = mat * glm.mat4_cast(self.parent.rot_quat)

        glUseProgram(self.parent.shaders['default'])
        glUniformMatrix4fv(0, 1, GL_FALSE, glm.value_ptr(proj))
        glUniformMatrix4fv(1, 1, GL_FALSE, glm.value_ptr(modelview))
        glBindVertexArray(self._vao_picking)
        glDrawArrays(GL_QUADS, 0, 24)

        glBindVertexArray(0)
        glUseProgram(0)
Beispiel #46
0
    def update_viewport(self):
        width, height = self.system_size
        w2 = width / 2.
        h2 = height / 2.

        # prepare the viewport
        glViewport(0, 0, width, height)

        # set the projection
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glFrustum(-w2, w2, -h2, h2, .1, 1000)
        glScalef(5000, 5000, 1)

        # use the rotated size.
        width, height = self.size
        w2 = width / 2.
        h2 = height / 2.
        glTranslatef(-w2, -h2, -500)

        # set the model view
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        glTranslatef(w2, h2, 0)
        glRotatef(self._rotation, 0, 0, 1)
        glTranslatef(-w2, -h2, 0)

        # update window size
        for w in self.children:
            shw, shh = w.size_hint
            if shw and shh:
                w.size = shw * width, shh * height
            elif shw:
                w.width = shw * width
            elif shh:
                w.height = shh * height
Beispiel #47
0
    def openglSetup(self):
        glClearColor(0.0, 0.0, 0.0, 0.0)
        glEnable(GL.GL_DEPTH_TEST)
        glEnable(GL.GL_COLOR_MATERIAL)

        glViewport(0, 0, self.surf.get_width(), self.surf.get_height())
        glMatrixMode(GL.GL_PROJECTION)
        glLoadIdentity()
        glFrustum(-1.0, 1.0, -1.0, 1.0, 1.5, 20.0)
        glMatrixMode(GL.GL_MODELVIEW)

        self.cardList = glGenLists(1)
        glNewList(self.cardList, GL.GL_COMPILE)
        glColor3f(1, 1, 1)
        with begin(GL.GL_QUADS):
            glTexCoord2f(0.0, 1.0)
            glVertex3f(-1.0, -1.0, 0.0)
            glTexCoord2f(1.0, 1.0)
            glVertex3f(1.0, -1.0, 0.0)
            glTexCoord2f(1.0, 0.0)
            glVertex3f(1.0, 1.0, 0.0)
            glTexCoord2f(0.0, 0.0)
            glVertex3f(-1.0, 1.0, 0.0)
        glEndList()
Beispiel #48
0
 def on_configure_event(self, widget, event):
     if not self.get_gl_drawable().gl_begin(self.get_gl_context()): return
     glViewport(0, 0, event.width, event.height)
     vb = context.application.vis_backend
     vb.tool.compile_total_list()
     self.get_gl_drawable().gl_end()
Beispiel #49
0
def main():
    global width
    global height
    global camera

    width = 1024
    height = 1024

    delta_time = 0.0
    last_frame = 0.0

    if not glfw.init():
        return

    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
    glfw.window_hint(glfw.RESIZABLE, GL_FALSE)
    window = glfw.create_window(width, height, "opengl_lab1", None, None)

    glfw.set_key_callback(window, key_callback)
    glfw.set_cursor_pos_callback(window, mousemove_callback)
    glfw.set_mouse_button_callback(window, mouseclick_callback)

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)

    fun1 = lambda x, z: math.sin(x+z)
    fun2 = lambda x, z: math.exp(-x*x - z*z)
    fun3 = lambda x, z: (x**2 + z**2) / (x*z)
    contour_plot = lambda x, z: 0.0
    heightmap_dummy_fun = lambda x, z: 0.0

    surface_size = 50

    (fun_vao1, ind_fun1) = create_surface(100, 100, surface_size, fun1, False)
    (fun_vao2, ind_fun2) = create_surface(100, 100, surface_size, fun2, False)
    (fun_vao3, ind_fun3) = create_surface(100, 100, surface_size, fun3, False)
    (grad_vao, grad_point_count) = create_grad(100, 100, surface_size)
    (contour_plot_vao, ind_con, vec_lines, vector_line_indexes) = create_surface(100, 100, surface_size, 0, False, True)
    (heightmap_vao, ind_hm) = create_surface(100,100, surface_size, heightmap_dummy_fun, True)
    (sphere_vao, sphere_ind, normals_for_glyph) = uv_sphere(22, 11)
    (torus_vao, torus_ind) = uv_torus(5, 10, 100, 100)
    (cm_vao, ind_cm) = create_surface(100, 100, surface_size, heightmap_dummy_fun, True)
    (cloud_vao, points_count) = read_ply()
    (perlin_vao, ind_perlin) = create_surface(100, 100, surface_size, heightmap_dummy_fun, False)
    (div_vao, ind_div) = create_surface(100, 100, surface_size, heightmap_dummy_fun, False)
    (traj_vao, ind_traj) = simple_cube()

    fun_shader_sources = [(GL_VERTEX_SHADER, "shaders/functions.vert"), (GL_FRAGMENT_SHADER, "shaders/functions.frag")]

    fun_program = ShaderProgram(fun_shader_sources)

    hm_shader_sources = [(GL_VERTEX_SHADER, "shaders/heightmap.vert"), (GL_FRAGMENT_SHADER, "shaders/heightmap.frag")]

    hm_program = ShaderProgram(hm_shader_sources)

    hm_texture = read_texture("1.jpg")

    contour_plot_shader_sources = [(GL_VERTEX_SHADER, "shaders/contourplot.vert"), (GL_FRAGMENT_SHADER, "shaders/contourplot.frag")]

    contour_plot_program = ShaderProgram(contour_plot_shader_sources)

    sphere_shader_sources = [(GL_VERTEX_SHADER, "shaders/sphere.vert"), (GL_FRAGMENT_SHADER, "shaders/sphere.frag")]
    sphere_program = ShaderProgram(sphere_shader_sources)

    glyph_shader_sources = [(GL_VERTEX_SHADER, "shaders/glyph.vert"), (GL_GEOMETRY_SHADER, "shaders/glyph.geom"), (GL_FRAGMENT_SHADER, "shaders/glyph.frag")]
    glyph_program = ShaderProgram(glyph_shader_sources)

    grad_shader_sources = [(GL_VERTEX_SHADER, "shaders/grad.vert"), (GL_GEOMETRY_SHADER, "shaders/grad.geom"), (GL_FRAGMENT_SHADER, "shaders/grad.frag")]
    grad_program = ShaderProgram(grad_shader_sources)

    cm_shader_sources = [(GL_VERTEX_SHADER, "shaders/colormap.vert"), (GL_FRAGMENT_SHADER, "shaders/colormap.frag")]
    cm_program = ShaderProgram( cm_shader_sources )

    perlin_shader_sources = [(GL_VERTEX_SHADER, "shaders/perlin.vert"), (GL_FRAGMENT_SHADER, "shaders/perlin.frag")]
    perlin_program = ShaderProgram(perlin_shader_sources)

    cloud_shader_sources = [(GL_VERTEX_SHADER, "shaders/ply.vert"), (GL_FRAGMENT_SHADER, "shaders/ply.frag")]
    cloud_program = ShaderProgram(cloud_shader_sources)

    vf_shader_sources = [(GL_VERTEX_SHADER, "shaders/vector_field.vert"), (GL_FRAGMENT_SHADER, "shaders/vector_field.frag")]
    vf_program = ShaderProgram(vf_shader_sources)

    traj_shader_sources = [(GL_VERTEX_SHADER, "shaders/trajectory.vert"),
                         (GL_FRAGMENT_SHADER, "shaders/trajectory.frag")]

    traj_program = ShaderProgram(traj_shader_sources)



    check_gl_errors()

    projection = projectionMatrixTransposed(60.0, float(width) / float(height), 1, 1000.0)

    HDR_TEXTURES_AMOUNT = 33

    cm_textures = read_cm_textures(HDR_TEXTURES_AMOUNT)

    cm_texture_num = 0

    cm_change_counter = 0

    hdr_textures_speed = 6

    perlin_time = 0.0
    perlin_time_step = 0.03



    cube_multiplier = 1.0
    cube_center = [0.0, 0.0, 0.0]
    traj_points_list = [ cube_center ]
    cube_edge_length = 2.0 * cube_multiplier

    offset = cube_edge_length / 10
    left_cube_pos = -25 * cube_edge_length
    cube_steps = -left_cube_pos / offset - 10
    traj_points_count = int(cube_steps)


    for i in range(traj_points_count):
        traj_points_list.append( [0.5*cube_edge_length * i, 0.0, 0.0] )

    traj_part_index = 0



    while not glfw.window_should_close(window):
        current_frame = glfw.get_time()
        delta_time = current_frame - last_frame
        last_frame = current_frame
        glfw.poll_events()

        doCameraMovement(camera, delta_time)

        model = translateM4x4(np.array([0.0, 0.0, 0.0]))
        view = camera.get_view_matrix()

        glClearColor(0.5, 0.5, 0.5, 1.0)
        glViewport(0, 0, width, height)
        glEnable(GL_DEPTH_TEST)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        fun_program.bindProgram()

        glUniform3fv(fun_program.uniformLocation("col"), 1 , [1.0, 0, 0] )

        glUniformMatrix4fv(fun_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten())
        glUniformMatrix4fv(fun_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten())
        glUniformMatrix4fv(fun_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten())

        glBindVertexArray(fun_vao1)
        glDrawElements(GL_TRIANGLE_STRIP, ind_fun1, GL_UNSIGNED_INT, None)

        model = translateM4x4(np.array([-1.5*surface_size,0.0 ,0.0 ]))
        glUniform3fv(fun_program.uniformLocation("col"), 1, [0.0, 1.0, 0])
        glUniformMatrix4fv(fun_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten())
        glBindVertexArray(fun_vao2)
        glDrawElements(GL_TRIANGLE_STRIP, ind_fun2, GL_UNSIGNED_INT, None)

        model = translateM4x4(np.array([1.5 * surface_size, 0.0, 0.0]))
        glUniform3fv(fun_program.uniformLocation("col"), 1, [0.0, 0.0, 1.0])
        glUniformMatrix4fv(fun_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten())
        glBindVertexArray(fun_vao3)
        glDrawElements(GL_TRIANGLE_STRIP, ind_fun3, GL_UNSIGNED_INT, None)

        cloud_program.bindProgram()

        translate_cloud = translateM4x4(np.array([-2.5*surface_size,0.0 ,0.0 ]))
        # rotate_cloud = rotateYM4x4(math.radians(180))
        model = translate_cloud
        # glUniform3fv(fun_program.uniformLocation("col"), 1, [0.0, 1.0, 0])
        glUniformMatrix4fv(cloud_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten())
        glUniformMatrix4fv(cloud_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten())
        glUniformMatrix4fv(cloud_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten())
        glBindVertexArray(cloud_vao)
        glDrawArrays(GL_POINTS, 0, points_count)

        sphere_program.bindProgram()

        sph_scale = scaleM4x4(np.array([sphere_radius, sphere_radius, sphere_radius]))
        sph_translate = translateM4x4(np.array([0.0, 0.0, 2.0 * surface_size]))

        glUniformMatrix4fv(sphere_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(sph_translate + sph_scale).flatten())
        glUniformMatrix4fv(sphere_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten())
        glUniformMatrix4fv(sphere_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten())
        glBindVertexArray(sphere_vao)
        glDrawElements(GL_TRIANGLES, sphere_ind, GL_UNSIGNED_INT, None)

        torus_translate = translateM4x4(np.array([0.0, 0.0, 3.0 * surface_size]))
        glUniformMatrix4fv(sphere_program.uniformLocation("model"), 1, GL_FALSE,
                           np.transpose(torus_translate + sph_scale).flatten())
        glBindVertexArray(torus_vao)
        glDrawElements(GL_TRIANGLES, torus_ind, GL_UNSIGNED_INT, None)

        glyph_program.bindProgram()
        sph_scale = scaleM4x4(np.array([sphere_radius, sphere_radius, sphere_radius]))
        sph_translate = translateM4x4(np.array([0.0, 0.0, 2.0 * surface_size]))

        glUniformMatrix4fv(glyph_program.uniformLocation("model"), 1, GL_FALSE,
                           np.transpose(sph_translate + sph_scale).flatten())
        glUniformMatrix4fv(glyph_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten())
        glUniformMatrix4fv(glyph_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten())

        vao = glGenVertexArrays(1)
        glBindVertexArray(vao)
        vbo = glGenBuffers(1)
        glBindBuffer(GL_ARRAY_BUFFER, vbo)
        glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(normals_for_glyph), normals_for_glyph.flatten(),
                     GL_STATIC_DRAW)
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None)
        glEnableVertexAttribArray(0)
        glDrawArrays(GL_POINTS, 0, 10000)
        glBindVertexArray(0)

        contour_plot_program.bindProgram()

        model = translateM4x4(np.array([-1.5 * surface_size, 0.0, -1.5 * surface_size]))

        glUniformMatrix4fv(contour_plot_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten())
        glUniformMatrix4fv(contour_plot_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten())
        glUniformMatrix4fv(contour_plot_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten())
        glBindVertexArray(contour_plot_vao)
        glDrawElements(GL_TRIANGLE_STRIP, ind_con, GL_UNSIGNED_INT, None)

        fun_program.bindProgram()
        lines_vao = glGenVertexArrays(1)
        glBindVertexArray(lines_vao)
        vbo_lines = glGenBuffers(1)
        vbo_indices = glGenBuffers(1)
        glBindBuffer(GL_ARRAY_BUFFER, vbo_lines)
        glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vec_lines), vec_lines.flatten(),
                     GL_STATIC_DRAW)  #
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None)
        glEnableVertexAttribArray(0)
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_indices)
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vector_line_indexes), vector_line_indexes.flatten(),
                     GL_STATIC_DRAW)

        glUniformMatrix4fv(fun_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten())
        glUniformMatrix4fv(fun_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten())
        glUniformMatrix4fv(fun_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten())
        glBindVertexArray(lines_vao)
        glDrawElements(GL_LINES, vector_line_indexes.size, GL_UNSIGNED_INT, None)

        hm_program.bindProgram()

        model = translateM4x4(np.array([0.0, 0.0, -1.5 * surface_size]))

        bindTexture(0, hm_texture)

        glUniform1i(hm_program.uniformLocation("tex"), 0)
        glUniformMatrix4fv(hm_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten())
        glUniformMatrix4fv(hm_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten())
        glUniformMatrix4fv(hm_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten())
        glBindVertexArray(heightmap_vao)
        glDrawElements(GL_TRIANGLE_STRIP, ind_hm, GL_UNSIGNED_INT, None)

        cm_program.bindProgram()

        model = translateM4x4(np.array([1.5 * surface_size, 0.0, -1.5 * surface_size]))

        cur_cm_texture = cm_textures[cm_texture_num % HDR_TEXTURES_AMOUNT]

        bindTexture(1, cur_cm_texture)

        if cm_change_counter % hdr_textures_speed == 0:
            cm_texture_num += 1

        cm_change_counter += 1

        glUniform1i(cm_program.uniformLocation("cm_switch"), False)

        glUniform1i(cm_program.uniformLocation("tex"), 1)
        glUniformMatrix4fv(cm_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten())
        glUniformMatrix4fv(cm_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten())
        glUniformMatrix4fv(cm_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten())
        glBindVertexArray(cm_vao)
        glDrawElements(GL_TRIANGLE_STRIP, ind_cm, GL_UNSIGNED_INT, None)

        # draw second animated hdr on the same shader
        model = translateM4x4(np.array([2.5 * surface_size, 0.0, -2.5 * surface_size]))
        glUniformMatrix4fv(cm_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten())
        glUniform1i(cm_program.uniformLocation("cm_switch"), True)
        glDrawElements(GL_TRIANGLE_STRIP, ind_cm, GL_UNSIGNED_INT, None)

        perlin_program.bindProgram()
        model = translateM4x4(np.array([0.0, 0.0, -3.5 * surface_size]))
        glUniformMatrix4fv(perlin_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten())
        glUniformMatrix4fv(perlin_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten())
        glUniformMatrix4fv(perlin_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten())
        glUniform1f(perlin_program.uniformLocation("time"), perlin_time)
        perlin_time += perlin_time_step

        glBindVertexArray(perlin_vao)
        glDrawElements(GL_TRIANGLE_STRIP, ind_perlin, GL_UNSIGNED_INT, None)

        grad_program.bindProgram()
        model = translateM4x4(np.array([-25.0, 0.0, -7.0 * surface_size]))
        glUniformMatrix4fv(grad_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten())
        glUniformMatrix4fv(grad_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten())
        glUniformMatrix4fv(grad_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten())
        glBindVertexArray(grad_vao)
        glDrawArrays(GL_LINES, 0, grad_point_count)

        vf_program.bindProgram()
        model = translateM4x4(np.array([0.0, 0.0, -5.5 * surface_size]))
        glUniformMatrix4fv(vf_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten())
        glUniformMatrix4fv(vf_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten())
        glUniformMatrix4fv(vf_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten())
        glUniform1i(vf_program.uniformLocation("cm_switch"), True)
        glBindVertexArray(div_vao)
        glDrawElements(GL_TRIANGLE_STRIP, ind_div, GL_UNSIGNED_INT, None)

        glUniform1i(vf_program.uniformLocation("cm_switch"), False)
        model = translateM4x4(np.array([1.0 * surface_size, 0.0, -6.5 * surface_size]))
        glUniformMatrix4fv(vf_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten())
        glDrawElements(GL_TRIANGLE_STRIP, ind_div, GL_UNSIGNED_INT, None)


        traj_program.bindProgram()

        l_traj_part =[]
        r_traj_part =[]

        if offset > 0:
            traj_part_index = int(traj_points_count - cm_change_counter % cube_steps)
            r_traj_part = traj_points_list[0:traj_part_index]
            for traj_coords in r_traj_part:
                l_traj_part.append( [-x for x in traj_coords] )
        else:
            traj_part_index = int(traj_points_count - cm_change_counter % cube_steps)
            # traj_part_index = int(cm_change_counter % cube_steps)
            l_traj_part = traj_points_list[0:traj_part_index]
            for traj_coords in l_traj_part:
                r_traj_part.append([-x for x in traj_coords])

        l_traj_vec = np.array(l_traj_part, dtype=np.float32)
        r_traj_vec = np.array(r_traj_part, dtype=np.float32)

        indices_list = [i for i in range(len(r_traj_part))]
        indices_vec = np.array(indices_list, dtype=np.uint32)

        left_traj_vao = glGenVertexArrays(1)
        right_traj_vao = glGenVertexArrays(1)
        left_traj_vertices = glGenBuffers(1)
        left_traj_indices = glGenBuffers(1)
        right_traj_vertices = glGenBuffers(1)
        right_traj_indices = glGenBuffers(1)

        glBindVertexArray(left_traj_vao)
        glPointSize( 3.0 )

        glBindBuffer(GL_ARRAY_BUFFER, left_traj_vertices)
        glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(l_traj_vec), l_traj_vec.flatten(),
                     GL_STATIC_DRAW)
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None)
        glEnableVertexAttribArray(0)

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, left_traj_indices)

        glBufferData(GL_ELEMENT_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(indices_vec), indices_vec.flatten(),
                     GL_STATIC_DRAW)


        glBindVertexArray(right_traj_vao)

        glBindBuffer(GL_ARRAY_BUFFER, right_traj_vertices)
        glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(r_traj_vec), r_traj_vec.flatten(),
                     GL_STATIC_DRAW)
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None)
        glEnableVertexAttribArray(0)

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, right_traj_indices)

        glBufferData(GL_ELEMENT_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(indices_vec), indices_vec.flatten(),
                     GL_STATIC_DRAW)

        glBindVertexArray(0)




        cube_scale_ = scaleM4x4(np.array([1.0, 1.0, 1.0]))

        left_cube_pos += offset

        left_translation = translateM4x4(np.array([left_cube_pos, 0.0, -7.5 * surface_size]))
        glUniformMatrix4fv(traj_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(left_translation).flatten())
        glUniformMatrix4fv(traj_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten())
        glUniformMatrix4fv(traj_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten())

        glBindVertexArray(left_traj_vao)
        glDrawElements(GL_LINE_STRIP, indices_vec.size, GL_UNSIGNED_INT, None)

        glBindVertexArray(traj_vao)
        glDrawElements(GL_TRIANGLE_STRIP, ind_traj, GL_UNSIGNED_INT, None)

        right_translation = translateM4x4(np.array([-left_cube_pos, 0.0, -8.5 * surface_size]))
        glUniformMatrix4fv(traj_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(right_translation).flatten())
        glDrawElements(GL_TRIANGLE_STRIP, ind_traj, GL_UNSIGNED_INT, None)


        glBindVertexArray(right_traj_vao)
        glDrawElements(GL_LINE_STRIP, indices_vec.size, GL_UNSIGNED_INT, None)







        if not cm_change_counter % cube_steps:
            # left_cube_pos = left_cube_pos + offset * (cube_steps-1)
            offset *= -1
            # r_traj_part, l_traj_part = l_traj_part, r_traj_part


        traj_program.unbindProgram()

        glfw.swap_buffers(window)

    glfw.terminate()
    def do_present_fbo(self):
        self.gl_marker("Presenting FBO on screen")
        # Change state to target screen instead of our FBO
        glBindFramebuffer(GL_FRAMEBUFFER, 0)

        if self._alpha_enabled:
            # transparent background:
            glClearColor(0.0, 0.0, 0.0, 0.0)
        else:
            # plain white no alpha:
            glClearColor(1.0, 1.0, 1.0, 1.0)

        # Draw FBO texture on screen
        self.set_rgb_paint_state()
        bw, bh = self.size
        ww, wh = self.render_size

        if self.glconfig.is_double_buffered() or bw!=ww or bh!=wh:
            #refresh the whole window:
            rectangles = ((0, 0, bw, bh), )
        else:
            #paint just the rectangles we have accumulated:
            rectangles = self.pending_fbo_paint
        self.pending_fbo_paint = []
        log("do_present_fbo: painting %s", rectangles)

        glEnable(GL_TEXTURE_RECTANGLE_ARB)
        glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO])
        if self._alpha_enabled:
            # support alpha channel if present:
            glEnablei(GL_BLEND, self.textures[TEX_FBO])
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE)

        #viewport for painting to window:
        glViewport(0, 0, ww, wh)
        if ww!=bw or wh!=bh:
            glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
            glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR)

        glBegin(GL_QUADS)
        for x,y,w,h in rectangles:
            #note how we invert coordinates..
            tx1, ty1, tx2, ty2 = x, bh-y,  x+w, bh-y-h
            vx1, vy1, vx2, vy2 = x, y,     x+w, y+h
            glTexCoord2i(tx1, ty1)
            glVertex2i(vx1, vy1)        #top-left of window viewport
            glTexCoord2i(tx1, ty2)
            glVertex2i(vx1, vy2)        #bottom-left of window viewport
            glTexCoord2i(tx2, ty2)
            glVertex2i(vx2, vy2)        #bottom-right of window viewport
            glTexCoord2i(tx2, ty1)
            glVertex2i(vx2, vy1)        #top-right of window viewport
        glEnd()
        glDisable(GL_TEXTURE_RECTANGLE_ARB)

        if self.paint_spinner:
            #add spinner:
            dim = min(bw/3.0, bh/3.0)
            t = time.time()
            count = int(t*4.0)
            bx = bw//2
            by = bh//2
            for i in range(8):      #8 lines
                glBegin(GL_POLYGON)
                c = cv.trs[count%8][i]
                glColor4f(c, c, c, 1)
                mi1 = math.pi*i/4-math.pi/16
                mi2 = math.pi*i/4+math.pi/16
                glVertex2i(int(bx+math.sin(mi1)*10), int(by+math.cos(mi1)*10))
                glVertex2i(int(bx+math.sin(mi1)*dim), int(by+math.cos(mi1)*dim))
                glVertex2i(int(bx+math.sin(mi2)*dim), int(by+math.cos(mi2)*dim))
                glVertex2i(int(bx+math.sin(mi2)*10), int(by+math.cos(mi2)*10))
                glEnd()

        #if desired, paint window border
        if self.border and self.border.shown:
            #double size since half the line will be off-screen
            glLineWidth(self.border.size*2)
            glBegin(GL_LINE_LOOP)
            glColor4f(self.border.red, self.border.green, self.border.blue, self.border.alpha)
            for px,py in ((0, 0), (bw, 0), (bw, bh), (0, bh)):
                glVertex2i(px, py)
            glEnd()

        # Show the backbuffer on screen
        self.gl_show()
        self.gl_frame_terminator()

        #restore pbo viewport
        glViewport(0, 0, bw, bh)
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST)

        self.unset_rgb_paint_state()
        log("%s(%s, %s)", glBindFramebuffer, GL_FRAMEBUFFER, self.offscreen_fbo)
        glBindFramebuffer(GL_FRAMEBUFFER, self.offscreen_fbo)
        log("%s.do_present_fbo() done", self)
Beispiel #51
0
 def onWindowResize(self, window, width, height):
     self.width = width
     self.height = height
     glViewport(0, 0, width, height)
Beispiel #52
0
    def gl_init(self):
        drawable = self.gl_begin()
        w, h = self.size
        log("%s.gl_init() GL Pixmap backing size: %d x %d, drawable=%s", self,
            w, h, drawable)
        if not drawable:
            return None

        if not self.debug_setup:
            self.debug_setup = True
            self.gl_init_debug()

        if not self.gl_setup:
            self.gl_marker("Initializing GL context for window size %d x %d" %
                           (w, h))
            # Initialize viewport and matrices for 2D rendering
            glViewport(0, 0, w, h)
            glMatrixMode(GL_PROJECTION)
            glLoadIdentity()
            glOrtho(0.0, w, h, 0.0, -1.0, 1.0)
            glMatrixMode(GL_MODELVIEW)
            # Could be more optimal to use vertex arrays:
            # glEnableClientState(GL_VERTEX_ARRAY)
            # glEnableClientState(GL_TEXTURE_COORD_ARRAY)

            # Clear background to transparent black
            glClearColor(0.0, 0.0, 0.0, 0.0)

            # we don't use the depth (2D only):
            glDisable(GL_DEPTH_TEST)
            # only do alpha blending in present_fbo:
            glDisable(GL_BLEND)

            # Default state is good for YUV painting:
            #  - fragment program enabled
            #  - YUV fragment program bound
            #  - render to offscreen FBO
            if self.textures is None:
                self.gl_init_textures()

            # Define empty FBO texture and set rendering to FBO
            glEnable(GL_FRAGMENT_PROGRAM_ARB)
            glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO])
            # nvidia needs this even though we don't use mipmaps (repeated through this file):
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0)
            glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0,
                         self.texture_pixel_format, w, h, 0,
                         self.texture_pixel_format, GL_UNSIGNED_BYTE, None)
            glBindFramebuffer(GL_FRAMEBUFFER, self.offscreen_fbo)
            glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                                   GL_TEXTURE_RECTANGLE_ARB,
                                   self.textures[TEX_FBO], 0)
            glClear(GL_COLOR_BUFFER_BIT)

            # Create and assign fragment programs
            if not self.shaders:
                self.gl_init_shaders()

            # Bind program 0 for YUV painting by default
            glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB,
                             self.shaders[YUV2RGB_SHADER])
            self.gl_setup = True
        return drawable
Beispiel #53
0
    def gl_init(self):
        #must be called within a context!
        #performs init if needed
        if not self.debug_setup:
            self.debug_setup = True
            self.gl_init_debug()

        if not self.gl_setup:
            w, h = self.size
            self.gl_marker("Initializing GL context for window size %d x %d",
                           w, h)
            # Initialize viewport and matrices for 2D rendering
            glViewport(0, 0, w, h)
            glMatrixMode(GL_PROJECTION)
            glLoadIdentity()
            glOrtho(0.0, w, h, 0.0, -1.0, 1.0)
            glMatrixMode(GL_MODELVIEW)
            # Mesa docs claim: this hint can improve the speed of texturing
            #when perspective-correct texture coordinate interpolation isn't needed,
            #such as when using a glOrtho() projection:
            glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST)
            # Could be more optimal to use vertex arrays:
            # glEnableClientState(GL_VERTEX_ARRAY)
            # glEnableClientState(GL_TEXTURE_COORD_ARRAY)

            # Clear background to transparent black
            glClearColor(0.0, 0.0, 0.0, 0.0)

            # we don't use the depth (2D only):
            glDisable(GL_DEPTH_TEST)
            # only do alpha blending in present_fbo:
            glDisable(GL_BLEND)

            # Default state is good for YUV painting:
            #  - fragment program enabled
            #  - YUV fragment program bound
            #  - render to offscreen FBO
            if self.textures is None:
                self.gl_init_textures()

            # Define empty FBO texture and set rendering to FBO
            glEnable(GL_FRAGMENT_PROGRAM_ARB)
            glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO])
            # nvidia needs this even though we don't use mipmaps (repeated through this file):
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0)
            glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0,
                         self.texture_pixel_format, w, h, 0,
                         self.texture_pixel_format, GL_UNSIGNED_BYTE, None)
            glBindFramebuffer(GL_FRAMEBUFFER, self.offscreen_fbo)
            glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                                   GL_TEXTURE_RECTANGLE_ARB,
                                   self.textures[TEX_FBO], 0)
            glClear(GL_COLOR_BUFFER_BIT)

            # Create and assign fragment programs
            if not self.shaders:
                self.gl_init_shaders()

            # Bind program 0 for YUV painting by default
            glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB,
                             self.shaders[YUV2RGB_SHADER])
            self.gl_setup = True
    def do_present_fbo(self):
        bw, bh = self.size
        ww, wh = self.render_size

        self.gl_marker("Presenting FBO on screen")
        # Change state to target screen instead of our FBO
        glBindFramebuffer(GL_FRAMEBUFFER, 0)
        glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0)

        left, top, right, bottom = self.offsets

        #viewport for clearing the whole window:
        glViewport(0, 0, left+ww+right, top+wh+bottom)
        if self._alpha_enabled:
            # transparent background:
            glClearColor(0.0, 0.0, 0.0, 0.0)
        else:
            # black, no alpha:
            glClearColor(0.0, 0.0, 0.0, 1.0)
        if left or top or right or bottom:
            try:
                glClear(GL_COLOR_BUFFER_BIT)
            except:
                log("ignoring glClear(GL_COLOR_BUFFER_BIT) error, buggy driver?", exc_info=True)

        #viewport for painting to window:
        glViewport(left, top, ww, wh)

        # Draw FBO texture on screen
        self.set_rgb_paint_state()

        rect_count = len(self.pending_fbo_paint)
        if self.glconfig.is_double_buffered() or bw!=ww or bh!=wh:
            #refresh the whole window:
            rectangles = ((0, 0, bw, bh), )
        else:
            #paint just the rectangles we have accumulated:
            rectangles = self.pending_fbo_paint
        self.pending_fbo_paint = []
        log("do_present_fbo: painting %s", rectangles)

        glEnable(GL_TEXTURE_RECTANGLE_ARB)
        glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO])
        if self._alpha_enabled:
            # support alpha channel if present:
            glEnablei(GL_BLEND, self.textures[TEX_FBO])
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE)

        if SAVE_BUFFERS:
            glBindFramebuffer(GL_READ_FRAMEBUFFER, self.offscreen_fbo)
            glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO])
            glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO], 0)
            glReadBuffer(GL_COLOR_ATTACHMENT0)
            glViewport(0, 0, bw, bh)
            from OpenGL.GL import glGetTexImage
            size = bw*bh*4
            import numpy
            data = numpy.empty(size)
            img_data = glGetTexImage(GL_TEXTURE_RECTANGLE_ARB, 0, GL_BGRA, GL_UNSIGNED_BYTE, data)
            from PIL import Image, ImageOps
            img = Image.frombuffer("RGBA", (bw, bh), img_data, "raw", "BGRA", bw*4)
            img = ImageOps.flip(img)
            kwargs = {}
            if SAVE_BUFFERS=="jpeg":
                kwargs = {
                          "quality"     : 0,
                          "optimize"    : False,
                          }
            t = time.time()
            tstr = time.strftime("%H-%M-%S", time.localtime(t))
            filename = "./W%i-FBO-%s.%03i.%s" % (self.wid, tstr, (t*1000)%1000, SAVE_BUFFERS)
            log("do_present_fbo: saving %4ix%-4i pixels, %7i bytes to %s", bw, bh, size, filename)
            img.save(filename, SAVE_BUFFERS, **kwargs)
            glBindFramebuffer(GL_READ_FRAMEBUFFER, 0)

        if ww!=bw or wh!=bh:
            glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
            glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR)

        glBegin(GL_QUADS)
        for x,y,w,h in rectangles:
            #note how we invert coordinates..
            tx1, ty1, tx2, ty2 = x, bh-y,  x+w, bh-y-h
            vx1, vy1, vx2, vy2 = x, y,     x+w, y+h
            glTexCoord2i(tx1, ty1)
            glVertex2i(vx1, vy1)        #top-left of window viewport
            glTexCoord2i(tx1, ty2)
            glVertex2i(vx1, vy2)        #bottom-left of window viewport
            glTexCoord2i(tx2, ty2)
            glVertex2i(vx2, vy2)        #bottom-right of window viewport
            glTexCoord2i(tx2, ty1)
            glVertex2i(vx2, vy1)        #top-right of window viewport
        glEnd()
        glDisable(GL_TEXTURE_RECTANGLE_ARB)

        if self.paint_spinner:
            #add spinner:
            dim = min(bw/3.0, bh/3.0)
            t = time.time()
            count = int(t*4.0)
            bx = bw//2
            by = bh//2
            for i in range(8):      #8 lines
                glBegin(GL_POLYGON)
                c = cv.trs[count%8][i]
                glColor4f(c, c, c, 1)
                mi1 = math.pi*i/4-math.pi/16
                mi2 = math.pi*i/4+math.pi/16
                glVertex2i(int(bx+math.sin(mi1)*10), int(by+math.cos(mi1)*10))
                glVertex2i(int(bx+math.sin(mi1)*dim), int(by+math.cos(mi1)*dim))
                glVertex2i(int(bx+math.sin(mi2)*dim), int(by+math.cos(mi2)*dim))
                glVertex2i(int(bx+math.sin(mi2)*10), int(by+math.cos(mi2)*10))
                glEnd()

        #if desired, paint window border
        if self.border and self.border.shown:
            #double size since half the line will be off-screen
            glLineWidth(self.border.size*2)
            glBegin(GL_LINE_LOOP)
            glColor4f(self.border.red, self.border.green, self.border.blue, self.border.alpha)
            for px,py in ((0, 0), (bw, 0), (bw, bh), (0, bh)):
                glVertex2i(px, py)
            glEnd()

        if self.pointer_overlay:
            x, y, _, _, size, start_time = self.pointer_overlay
            elapsed = time.time()-start_time
            if elapsed<6:
                alpha = max(0, (5.0-elapsed)/5.0)
                glLineWidth(1)
                glBegin(GL_LINES)
                glColor4f(0, 0, 0, alpha)
                glVertex2i(x-size, y)
                glVertex2i(x+size, y)
                glVertex2i(x, y-size)
                glVertex2i(x, y+size)
                glEnd()
            else:
                self.pointer_overlay = None

        # Show the backbuffer on screen
        self.gl_show(rect_count)
        self.gl_frame_terminator()

        #restore pbo viewport
        glViewport(0, 0, bw, bh)
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST)

        self.unset_rgb_paint_state()
        log("%s(%s, %s)", glBindFramebuffer, GL_FRAMEBUFFER, self.offscreen_fbo)
        glBindFramebuffer(GL_FRAMEBUFFER, self.offscreen_fbo)
        log("%s.do_present_fbo() done", self)
    def gl_init(self):
        #must be called within a context!
        #performs init if needed
        if not self.debug_setup:
            self.debug_setup = True
            self.gl_init_debug()

        if not self.gl_setup:
            w, h = self.size
            self.gl_marker("Initializing GL context for window size %s, backing size %s", self.render_size, self.size)
            # Initialize viewport and matrices for 2D rendering
            x, _, _, y = self.offsets
            glViewport(x, y, w, h)
            glMatrixMode(GL_PROJECTION)
            glLoadIdentity()
            glOrtho(0.0, w, h, 0.0, -1.0, 1.0)
            glMatrixMode(GL_MODELVIEW)
            # Mesa docs claim: this hint can improve the speed of texturing
            #when perspective-correct texture coordinate interpolation isn't needed,
            #such as when using a glOrtho() projection:
            glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST)
            # Could be more optimal to use vertex arrays:
            # glEnableClientState(GL_VERTEX_ARRAY)
            # glEnableClientState(GL_TEXTURE_COORD_ARRAY)

            # Clear background to transparent black
            glClearColor(0.0, 0.0, 0.0, 0.0)

            # we don't use the depth (2D only):
            glDisable(GL_DEPTH_TEST)
            glDisable(GL_SCISSOR_TEST)
            glDisable(GL_LIGHTING)
            glDisable(GL_DITHER)
            # only do alpha blending in present_fbo:
            glDisable(GL_BLEND)

            # Default state is good for YUV painting:
            #  - fragment program enabled
            #  - YUV fragment program bound
            #  - render to offscreen FBO
            if self.textures is None:
                self.gl_init_textures()

            def clear_fbo():
                try:
                    glClear(GL_COLOR_BUFFER_BIT)
                except Exception as e:
                    log("glClear error", exc_info=True)
                    log.warn("Warning: failed to clear FBO")
                    log.warn(" %r", e)
                    if getattr(e, "err", None)==1286:
                        raise Exception("OpenGL error '%r' likely caused by buggy drivers" % e)

            # Define empty tmp FBO
            glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_TMP_FBO])
            set_texture_level()
            glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, self.texture_pixel_format, w, h, 0, self.texture_pixel_format, GL_UNSIGNED_BYTE, None)
            glBindFramebuffer(GL_FRAMEBUFFER, self.tmp_fbo)
            glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_TMP_FBO], 0)
            clear_fbo()

            # Define empty FBO texture and set rendering to FBO
            glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO])
            # nvidia needs this even though we don't use mipmaps (repeated through this file):
            set_texture_level()
            glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, self.texture_pixel_format, w, h, 0, self.texture_pixel_format, GL_UNSIGNED_BYTE, None)
            glBindFramebuffer(GL_FRAMEBUFFER, self.offscreen_fbo)
            glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO], 0)
            clear_fbo()

            # Create and assign fragment programs
            if not self.shaders:
                self.gl_init_shaders()

            # Bind program 0 for YUV painting by default
            glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.shaders[YUV2RGB_SHADER])
            glEnable(GL_FRAGMENT_PROGRAM_ARB)
            self.gl_setup = True
Beispiel #56
0
 def viewport(cls, x: int, y: int, width: int, height: int):
     glViewport(x, y, width, height)
Beispiel #57
0
    def do_glselect_if_wanted(self):  #bruce 070919 split this out
        """
        Do the glRenderMode(GL_SELECT) drawing, and/or the glname-color
        drawing for shader primitives, used to guess which object
        might be under the mouse, for one drawing frame,
        if desired for this frame. Report results by storing candidate
        mouseover objects in self.glselect_dict. 
        
        The depth buffer is initially clear, and must be clear
        when we're done as well.

        @note: does not do related individual object depth/stencil 
               buffer drawing -- caller must do that on some or all
               of the objects we store into self.glselect_dict.
        """
        if self.glselect_wanted:  # note: this will be reset below.
            ###@@@ WARNING: The original code for this, here in GLPane, has been duplicated and slightly modified
            # in at least three other places (search for glRenderMode to find them). This is bad; common code
            # should be used. Furthermore, I suspect it's sometimes needlessly called more than once per frame;
            # that should be fixed too. [bruce 060721 comment]
            wX, wY, self.targetdepth = self.glselect_wanted  # wX, wY is the point to do the hit-test at
            # targetdepth is the depth buffer value to look for at that point, during ordinary drawing phase
            # (could also be used to set up clipping planes to further restrict hit-test, but this isn't yet done)
            # (Warning: targetdepth could in theory be out of date, if more events come between bareMotion
            #  and the one caused by its gl_update, whose paintGL is what's running now, and if those events
            #  move what's drawn. Maybe that could happen with mousewheel events or (someday) with keypresses
            #  having a graphical effect. Ideally we'd count intentional redraws, and disable this picking in that case.)
            self.wX, self.wY = wX, wY
            self.glselect_wanted = 0
            pwSize = 1  # Pick window size.  Russ 081128: Was 3.
            # Bruce: Replace 3, 3 with 1, 1? 5, 5? not sure whether this will
            # matter...  in principle should have no effect except speed.
            # Russ: For glname rendering, 1x1 is better because it doesn't
            # have window boundary issues.  We get the coords of a single
            # pixel in the window for the mouse position.

            #bruce 050615 for use by nodes which want to set up their own projection matrix.
            self.current_glselect = (wX, wY, pwSize, pwSize)
            self._setup_projection(glselect=self.current_glselect
                                   )  # option makes it use gluPickMatrix

            # Russ 081209: Added.
            debugPicking = debug_pref("GLPane: debug mouseover picking?",
                                      Choice_boolean_False,
                                      prefs_key=True)

            if self.enabled_shaders():
                # TODO: optimization: find an appropriate place to call
                # _compute_frustum_planes. [bruce 090105 comment]

                # Russ 081122: There seems to be no way to access the GL name
                # stack in shaders. Instead, for mouseover, draw shader
                # primitives with glnames as colors in glRenderMode(GL_RENDER),
                # then read back the pixel color (glname) and depth value.

                # Temporarily replace the full-size viewport with a little one
                # at the mouse location, matching the pick matrix location.
                # Otherwise, we will draw a closeup of that area into the whole
                # window, rather than a few pixels. (This wasn't needed when we
                # only used GL_SELECT rendering mode here, because that doesn't
                # modify the frame buffer -- it just returns hits by graphics
                # primitives when they are inside the clipping boundaries.)
                #
                # (Don't set the viewport *before* _setup_projection(), since
                #  that method needs to read the current whole-window viewport
                #  to set up glselect. See explanation in its docstring.)

                savedViewport = glGetIntegerv(GL_VIEWPORT)
                glViewport(wX, wY, pwSize, pwSize)  # Same as current_glselect.

                # First, clear the pixel RGBA to zeros and a depth of 1.0 (far),
                # so we won't confuse a color with a glname if there are
                # no shader primitives drawn over this pixel.
                saveDepthFunc = glGetInteger(GL_DEPTH_FUNC)
                glDepthFunc(GL_ALWAYS)
                glWindowPos3i(wX, wY, 1)  # Note the Z coord.
                gl_format, gl_type = GL_RGBA, GL_UNSIGNED_BYTE
                glDrawPixels(pwSize, pwSize, gl_format, gl_type, (0, 0, 0, 0))
                glDepthFunc(
                    saveDepthFunc)  # needed, though we'll change it again

                # We must be in glRenderMode(GL_RENDER) (as usual) when this is called.
                # Note: _setup_projection leaves the matrix mode as GL_PROJECTION.
                glMatrixMode(GL_MODELVIEW)
                shaders = self.enabled_shaders()
                try:
                    # Set flags so that we will use glnames-as-color mode
                    # in shaders, and draw only shader primitives.
                    # (Ideally we would also draw all non-shader primitives
                    #  as some other color, unequal to all glname colors
                    #  (or derived from a fake glname for that purpose),
                    #  in order to obscure shader primitives where appropriate.
                    #  This is intended to be done but is not yet implemented.
                    #  [bruce 090105 addendum])
                    for shader in shaders:
                        shader.setPicking(True)
                    self.set_drawing_phase("glselect_glname_color")

                    for stereo_image in self.stereo_images_to_draw:
                        self._enable_stereo(stereo_image)
                        try:
                            self._do_graphicsMode_Draw(
                                for_mouseover_highlighting=True)
                            # note: we can't disable depth writing here,
                            # since we need it to make sure the correct
                            # shader object comes out on top, or is
                            # obscured by a DL object. Instead, we'll
                            # clear the depth buffer again (at this pixel)
                            # below. [bruce 090105]
                        finally:
                            self._disable_stereo()
                except:
                    print_compact_traceback(
                        "exception in or around _do_graphicsMode_Draw() during glname_color;"
                        "drawing ignored; restoring modelview matrix: ")
                    # REVIEW: what does "drawing ignored" mean, in that message? [bruce 090105 question]
                    glMatrixMode(GL_MODELVIEW)
                    self._setup_modelview(
                    )  ### REVIEW: correctness of this is unreviewed!
                    # now it's important to continue, at least enough to restore other gl state
                    pass
                for shader in shaders:
                    shader.setPicking(False)
                self.set_drawing_phase('?')

                # Restore the viewport.
                glViewport(savedViewport[0], savedViewport[1],
                           savedViewport[2], savedViewport[3])

                # Read pixel value from the back buffer and re-assemble glname.
                glFinish()  # Make sure the drawing has completed.
                # REVIEW: is this glFinish needed? [bruce 090105 comment]
                rgba = glReadPixels(wX, wY, 1, 1, gl_format, gl_type)[0][0]
                pixZ = glReadPixelsf(wX, wY, 1, 1, GL_DEPTH_COMPONENT)[0][0]

                # Clear our depth pixel to 1.0 (far), so we won't mess up the
                # subsequent call of preDraw_glselect_dict.
                # (The following is not the most direct way, but it ought to work.
                #  Note that we also clear the color pixel, since (being a glname)
                #  it has no purpose remaining in the color buffer -- either it's
                #  changed later, or, if not, that's a bug, but we'd rather have
                #  it black than a random color.) [bruce 090105 bugfix]
                glDepthFunc(GL_ALWAYS)
                glWindowPos3i(wX, wY, 1)  # Note the Z coord.
                glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE)
                gl_format, gl_type = GL_RGBA, GL_UNSIGNED_BYTE
                glDrawPixels(pwSize, pwSize, gl_format, gl_type, (0, 0, 0, 0))
                glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE)
                glDepthFunc(saveDepthFunc)

                # Comes back sign-wrapped, in spite of specifying UNSIGNED_BYTE.
                def us(b):
                    if b < 0:
                        return 256 + b
                    return b

                bytes = tuple([us(b) for b in rgba])
                ##glname = (bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3])
                ## Temp fix: Ignore the last byte, which always comes back 255 on Windows.
                glname = (bytes[0] << 16 | bytes[1] << 8 | bytes[2])
                if debugPicking:
                    print("shader mouseover xy %d %d, " % (wX, wY) +
                          "rgba bytes (0x%x, 0x%x, 0x%x, 0x%x), " % bytes +
                          "Z %f, glname 0x%x" % (pixZ, glname))
                    pass

                ### XXX This ought to be better-merged with the DL selection below.
                if glname:
                    obj = self.object_for_glselect_name(glname)
                    if debugPicking:
                        print "shader mouseover glname=%r, obj=%r." % (glname,
                                                                       obj)
                    if obj is None:
                        # REVIEW: does this happen for mouse over a non-shader primitive?
                        # [bruce 090105 question]

                        #### Note: this bug is common. Guess: we are still drawing
                        # ordinary colors for some primitives and/or for the
                        # background, and they are showing up here and confusing
                        # us. To help debug this, print the color too. But testing
                        # shows it's not so simple -- e.g. for rung bonds it happens
                        # where shader sphere and cylinder overlap, but not on either
                        # one alone; for strand bonds it also happens on the bonds alone
                        # (tested in Build DNA, in or not in Insert DNA).
                        # [bruce 090218]
                        #
                        # Update: Since it's so common, I need to turn it off by default.
                        # Q: is the situation safe?
                        # A: if a color looks like a real glname by accident,
                        # we'll get some random candidate object -- perhaps a killed one
                        # or from a different Part or even a closed assy --
                        # and try to draw it. That doesn't sound very safe. Unfortunately
                        # there is no perfect way to filter selobjs for safety, in the
                        # current still-informal Selobj_API. The best approximation is
                        # selobj_still_ok, and it should always say yes for the usual kinds,
                        # so I'll add it as a check in the 'else' clause below.
                        # [bruce 090311]
                        if debug_flags.atom_debug:
                            print "bug: object_for_glselect_name returns None for glname %r (color %r)" % (
                                glname, bytes)
                    else:
                        if self.graphicsMode.selobj_still_ok(obj):
                            #bruce 090311 added condition, explained above
                            self.glselect_dict[id(obj)] = obj
                        else:
                            # This should be rare but possible. Leave it on briefly and see
                            # if it's ever common. If possible, gate it by atom_debug before
                            # the release. [bruce 090311]
                            print "fyi: glname-color selobj %r rejected since not selobj_still_ok" % obj
                        pass
                    pass
                pass

            if self._use_frustum_culling:
                self._compute_frustum_planes()
                # piotr 080331 - the frustum planes have to be setup after the
                # projection matrix is setup. I'm not sure if there may
                # be any side effects - see the comment below about
                # possible optimization.
            glSelectBuffer(self.SIZE_FOR_glSelectBuffer)
            # Note: this allocates a new select buffer,
            # and glRenderMode(GL_RENDER) returns it and forgets it,
            # so it's required before *each* call of glRenderMode(GL_SELECT) +
            # glRenderMode(GL_RENDER), not just once to set the size.
            # Ref: http://pyopengl.sourceforge.net/documentation/opengl_diffs.html
            # [bruce 080923 comment]
            glInitNames()

            # REVIEW: should we also set up a clipping plane just behind the
            # hit point, as (I think) is done in ThumbView, to reduce the
            # number of candidate objects? This might be a significant
            # optimization, though I don't think it eliminates the chance
            # of having multiple candidates. [bruce 080917 comment]

            glRenderMode(GL_SELECT)
            glMatrixMode(GL_MODELVIEW)
            try:
                self.set_drawing_phase('glselect')  #bruce 070124
                for stereo_image in self.stereo_images_to_draw:
                    self._enable_stereo(stereo_image)
                    try:
                        self._do_graphicsMode_Draw(
                            for_mouseover_highlighting=True)
                    finally:
                        self._disable_stereo()
            except:
                print_compact_traceback(
                    "exception in or around _do_graphicsMode_Draw() during GL_SELECT; "
                    "ignored; restoring modelview matrix: ")
                glMatrixMode(GL_MODELVIEW)
                self._setup_modelview(
                )  ### REVIEW: correctness of this is unreviewed!
                # now it's important to continue, at least enough to restore other gl state

            self._frustum_planes_available = False  # piotr 080331
            # just to be safe and not use the frustum planes computed for
            # the pick matrix
            self.set_drawing_phase('?')
            self.current_glselect = False
            # REVIEW: On systems with no stencil buffer, I think we'd also need
            # to draw selobj here in highlighted form (in case that form is
            # bigger than when it's not highlighted), or (easier & faster)
            # just always pretend it passes the hit test and add it to
            # glselect_dict -- and, make sure to give it "first dibs" for being
            # the next selobj. I'll implement some of this now (untested when
            # no stencil buffer) but not yet all. [bruce 050612]
            selobj = self.selobj
            if selobj is not None:
                self.glselect_dict[id(selobj)] = selobj
                # (review: is the following note correct?)
                # note: unneeded, if the func that looks at this dict always
                # tries selobj first (except for a kluge near
                # "if self.glselect_dict", commented on below)
            glFlush()
            hit_records = list(glRenderMode(GL_RENDER))
            if debugPicking:
                print "DLs %d hits" % len(hit_records)
            for (near, far,
                 names) in hit_records:  # see example code, renderpass.py
                ## print "hit record: near, far, names:", near, far, names
                # e.g. hit record: near, far, names: 1439181696 1453030144 (1638426L,)
                # which proves that near/far are too far apart to give actual depth,
                # in spite of the 1- or 3-pixel drawing window (presumably they're vertices
                # taken from unclipped primitives, not clipped ones).
                del near, far
                if 1:
                    # partial workaround for bug 1527. This can be removed once that bug (in drawer.py)
                    # is properly fixed. This exists in two places -- GLPane.py and modes.py. [bruce 060217]
                    if names and names[-1] == 0:
                        print "%d(g) partial workaround for bug 1527: removing 0 from end of namestack:" % env.redraw_counter, names
                        names = names[:-1]
                if names:
                    # For now, we only use the last element of names,
                    # though (as of long before 080917) it is often longer:
                    # - some code pushes the same name twice (directly and
                    #   via ColorSorter) (see 060725 debug print below);
                    # - chunks push a name even when they draw atoms/bonds
                    #   which push their own names (see 080411 comment below).
                    #
                    # Someday: if we ever support "name/subname paths" we'll
                    # probably let first name interpret the remaining ones.
                    # In fact, if nodes change projection or viewport for
                    # their kids, and/or share their kids, they'd need to
                    # push their own names on the stack, so we'd know how
                    # to redraw the kids, or which ones are meant when they
                    # are shared.
                    if debug_flags.atom_debug and len(
                            names) > 1:  # bruce 060725
                        if len(names) == 2 and names[0] == names[1]:
                            if not env.seen_before(
                                    "dual-names bug"
                            ):  # this happens for Atoms (colorsorter bug??)
                                print "debug (once-per-session message): why are some glnames duplicated on the namestack?", names
                        else:
                            # Note: as of sometime before 080411, this became common --
                            # I guess that chunks (which recently acquired glselect names)
                            # are pushing their names even while drawing their atoms and bonds.
                            # I am not sure if this can cause any problems -- almost surely not
                            # directly, but maybe the nestedness of highlighted appearances could
                            # violate some assumptions made by the highlight code... anyway,
                            # to reduce verbosity I need to not print this when the deeper name
                            # is that of a chunk, and there are exactly two names. [bruce 080411]
                            if len(names) == 2 and \
                               isinstance( self.object_for_glselect_name(names[0]), self.assy.Chunk ):
                                if not env.seen_before(
                                        "nested names for Chunk"):
                                    print "debug (once-per-session message): nested glnames for a Chunk: ", names
                            else:
                                print "debug fyi: len(names) == %d (names = %r)" % (
                                    len(names), names)
                    obj = self.object_for_glselect_name(
                        names[-1])  #k should always return an obj
                    if obj is None:
                        print "bug: object_for_glselect_name returns None for name %r at end of namestack %r" % (
                            names[-1], names)
                    else:
                        self.glselect_dict[id(obj)] = obj
                        # note: outside of this method, one of these will be
                        # chosen to be saved as self.selobj and rerendered
                        # in "highlighted" form
                        ##if 0:
                        ##    # this debug print was useful for debugging bug 2945,
                        ##    # and when it happens it's usually a bug,
                        ##    # but not always:
                        ##    # - it's predicted to happen for ChunkDrawer._renderOverlayText
                        ##    # - and whenever we're using a whole-chunk display style
                        ##    # so we can't leave it in permanently. [bruce 081211]
                        ##    if isinstance( obj, self.assy.Chunk ):
                        ##        print "\n*** namestack topped with a chunk:", obj
                    pass
                continue  # next hit_record
            #e maybe we should now sort glselect_dict by "hit priority"
            # (for depth-tiebreaking), or at least put selobj first.
            # (or this could be done lower down, where it's used.)
            # [I think we do this now...]

        return  # from do_glselect_if_wanted
Beispiel #58
0
 def _framebuffer_size_callback(self, window, width, height):
     self.width = width
     self.height = height
     glViewport(0, 0, width, height)
Beispiel #59
0
 def on_configure_event(self, widget, _event):
     with GLContext(widget):
         glViewport(0, 0, widget.allocation.width, widget.allocation.height)
     return True
Beispiel #60
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('model', metavar='MODEL.MS3D', type=str)
    parser.add_argument('--show-skeleton', action='store_true')

    args = parser.parse_args()

    pygame.init()
    pygame.display.set_mode((800, 600), pygame.DOUBLEBUF | pygame.OPENGL)

    glViewport(0, 0, 800, 600)

    glEnable(GL_DEPTH_TEST)
    glClearColor(0, 0, 0, 0)

    model = MS3DModel(args.model)
    bone_model = BoneModel()
    start = time.time()

    projection_matrix = matrix.perspective(math.radians(45), 800 / 600, 0.1,
                                           1000)

    # Fit the model into the viewport
    min_vert, max_vert = map(Vector._make, model.bbox)
    model_h = max_vert.y - min_vert.y
    model_w = max_vert.x - min_vert.x

    model_center = lerp(min_vert, max_vert, 1 / 2)

    distance = max(model_h, model_w) / (2 * math.tan(math.radians(45 / 2)))
    distance = distance + max_vert.z

    view_matrix = matrix.look_at(eye=np.subtract(model_center,
                                                 [0, 0, distance]),
                                 center=model_center,
                                 up=UP)

    rot = matrix.rotate_y(math.radians(1))

    running = True
    while running:
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        # Update models current animation frame
        model.timestamp = time.time() - start
        # Draw the model
        model.render(view_matrix, projection_matrix)

        if args.show_skeleton:
            glClear(GL_DEPTH_BUFFER_BIT)
            for M in model_skeleton_matrices(model):
                bone_model.matrix = M
                bone_model.render(view_matrix, projection_matrix)

        # Rotate the view by 1 degree
        view_matrix = np.dot(view_matrix, rot)

        pygame.display.flip()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False