Example #1
0
    def swapBuffers(self):
        # first call the swap on the QGLWidget
        start = long(now() * 1000)

        self.glw.swapBuffers()

        #self.glw.makeCurrent()

        # The following is taken from the PsychToolbox
        # Draw a single pixel in left-top area of back-buffer.
        # This will wait/stall the rendering pipeline
        # until the buffer flip has happened, aka immediately after the VBL has started.
        # We need the pixel as "synchronization token", so the following glFinish() really
        # waits for VBL instead of just "falling through" due to the asynchronous nature of
        # OpenGL:
        glDrawBuffer(GL_BACK)
        # We draw our single pixel with an alpha-value of zero - so effectively it doesn't
        # change the color buffer - just the z-buffer if z-writes are enabled...
        glColor4f(0.0, 0.0, 0.0, 0.0)
        glBegin(GL_POINTS)
        glVertex2i(10, 10)
        glEnd()
        # This glFinish() will wait until point drawing is finished, ergo backbuffer was ready
        # for drawing, ergo buffer swap in sync with start of VBL has happened.
        glFinish()

        finish = long(now() * 1000)
        fdiff = finish - self.last_finish
        self.last_finish = finish
        return (start, finish - start, fdiff)
Example #2
0
    def _capture_saved_bg_image(self):
        """
        """
        # TODO: investigate better ways to do this, which don't involve the CPU.
        # For example, frame buffer objects, or "render to texture":
        # - by glCopyTexImage2D,
        #   http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=36
        #   (which can do color -- I don't know about depth),
        # - or by more platform-specific ways, e.g. pbuffer.
        # [bruce 081002]

        print "_capture_saved_bg_image", self._print_data()
        sys.stdout.flush()

        if 1:
            from OpenGL.GL import glFlush, glFinish
            glFlush(
            )  # might well be needed, based on other code in NE1; not enough by itself
            glFinish()  # try this too if needed
        w = _trim(self.width)
        h = _trim(self.height)

        # grab the color image part
        image = glReadPixels(0, 0, w, h, _GL_FORMAT_FOR_COLOR,
                             GL_UNSIGNED_BYTE)
        self._cached_bg_color_image = image

        # grab the depth part
        ## image = glReadPixels( 0, 0, w, h, GL_DEPTH_COMPONENT, _GL_TYPE_FOR_DEPTH )
        image = glReadPixelsf(0, 0, w, h, GL_DEPTH_COMPONENT)  #####
        self._cached_bg_depth_image = image
        print "grabbed depth at 0,0:", image[0][0]  ######

        return
    def _capture_saved_bg_image(self):
        """
        """
        # TODO: investigate better ways to do this, which don't involve the CPU.
        # For example, frame buffer objects, or "render to texture":
        # - by glCopyTexImage2D,
        #   http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=36
        #   (which can do color -- I don't know about depth),
        # - or by more platform-specific ways, e.g. pbuffer.
        # [bruce 081002]
        
        print "_capture_saved_bg_image", self._print_data()
        sys.stdout.flush()
        
        if 1:
            from OpenGL.GL import glFlush, glFinish
            glFlush() # might well be needed, based on other code in NE1; not enough by itself
            glFinish() # try this too if needed
        w = _trim(self.width)
        h = _trim(self.height)
        
        # grab the color image part
        image = glReadPixels( 0, 0, w, h, _GL_FORMAT_FOR_COLOR, GL_UNSIGNED_BYTE )
        self._cached_bg_color_image = image
        
        # grab the depth part
        ## image = glReadPixels( 0, 0, w, h, GL_DEPTH_COMPONENT, _GL_TYPE_FOR_DEPTH )
        image = glReadPixelsf(0, 0, w, h, GL_DEPTH_COMPONENT) #####
        self._cached_bg_depth_image = image
        print "grabbed depth at 0,0:", image[0][0]######

        return
Example #4
0
    def swapBuffers(self):
        # first call the swap on the QGLWidget
        start = long(now()*1000)

        self.glw.swapBuffers()

        #self.glw.makeCurrent()

        # The following is taken from the PsychToolbox
        # Draw a single pixel in left-top area of back-buffer. 
        # This will wait/stall the rendering pipeline
        # until the buffer flip has happened, aka immediately after the VBL has started.
        # We need the pixel as "synchronization token", so the following glFinish() really
        # waits for VBL instead of just "falling through" due to the asynchronous nature of
        # OpenGL:
        glDrawBuffer(GL_BACK)
        # We draw our single pixel with an alpha-value of zero - so effectively it doesn't
        # change the color buffer - just the z-buffer if z-writes are enabled...
        glColor4f(0.0,0.0,0.0,0.0)
        glBegin(GL_POINTS)
        glVertex2i(10,10)
        glEnd()
        # This glFinish() will wait until point drawing is finished, ergo backbuffer was ready
        # for drawing, ergo buffer swap in sync with start of VBL has happened.
        glFinish()

        finish = long(now()*1000)
        fdiff = finish - self.last_finish
        self.last_finish = finish
        return (start,finish-start,fdiff)
Example #5
0
def get_gl_info_string(glpane):  # grantham 20051129
    """Return a string containing some useful information about the OpenGL
    implementation.

    Use the GL context from the given QGLWidget glpane (by calling
    glpane.makeCurrent()).
    """

    glpane.makeCurrent()  #bruce 070308 added glpane arg and makeCurrent call

    gl_info_string = ''

    gl_info_string += 'GL_VENDOR : "%s"\n' % glGetString(GL_VENDOR)
    gl_info_string += 'GL_VERSION : "%s"\n' % glGetString(GL_VERSION)
    gl_info_string += 'GL_RENDERER : "%s"\n' % glGetString(GL_RENDERER)
    gl_info_string += 'GL_EXTENSIONS : "%s"\n' % glGetString(GL_EXTENSIONS)

    from utilities.debug_prefs import debug_pref, Choice_boolean_False
    if debug_pref("get_gl_info_string call glAreTexturesResident?",
                  Choice_boolean_False):
        # Give a practical indication of how much video memory is available.
        # Should also do this with VBOs.

        # I'm pretty sure this code is right, but PyOpenGL seg faults in
        # glAreTexturesResident, so it's disabled until I can figure that
        # out. [grantham] [bruce 070308 added the debug_pref]

        all_tex_in = True
        tex_bytes = '\0' * (512 * 512 * 4)
        tex_names = []
        tex_count = 0
        tex_names = glGenTextures(1024)
        glEnable(GL_TEXTURE_2D)
        while all_tex_in:
            glBindTexture(GL_TEXTURE_2D, tex_names[tex_count])
            gluBuild2DMipmaps(GL_TEXTURE_2D, 4, 512, 512, GL_RGBA,
                              GL_UNSIGNED_BYTE, tex_bytes)
            tex_count += 1

            glTexCoord2f(0.0, 0.0)
            glBegin(GL_QUADS)
            glVertex2f(0.0, 0.0)
            glVertex2f(1.0, 0.0)
            glVertex2f(1.0, 1.0)
            glVertex2f(0.0, 1.0)
            glEnd()
            glFinish()

            residences = glAreTexturesResident(tex_names[:tex_count])
            all_tex_in = reduce(lambda a, b: a and b, residences)
            # bruce 070308 sees this exception from this line:
            # TypeError: reduce() arg 2 must support iteration

        glDisable(GL_TEXTURE_2D)
        glDeleteTextures(tex_names)

        gl_info_string += "Could create %d 512x512 RGBA resident textures\n" \
                          % tex_count
    return gl_info_string
Example #6
0
def get_gl_info_string(glpane): # grantham 20051129
    """Return a string containing some useful information about the OpenGL
    implementation.

    Use the GL context from the given QGLWidget glpane (by calling
    glpane.makeCurrent()).
    """

    glpane.makeCurrent() #bruce 070308 added glpane arg and makeCurrent call

    gl_info_string = ''

    gl_info_string += 'GL_VENDOR : "%s"\n' % glGetString(GL_VENDOR)
    gl_info_string += 'GL_VERSION : "%s"\n' % glGetString(GL_VERSION)
    gl_info_string += 'GL_RENDERER : "%s"\n' % glGetString(GL_RENDERER)
    gl_info_string += 'GL_EXTENSIONS : "%s"\n' % glGetString(GL_EXTENSIONS)

    from utilities.debug_prefs import debug_pref, Choice_boolean_False
    if debug_pref("get_gl_info_string call glAreTexturesResident?",
                  Choice_boolean_False):
        # Give a practical indication of how much video memory is available.
        # Should also do this with VBOs.

        # I'm pretty sure this code is right, but PyOpenGL seg faults in
        # glAreTexturesResident, so it's disabled until I can figure that
        # out. [grantham] [bruce 070308 added the debug_pref]

        all_tex_in = True
        tex_bytes = '\0' * (512 * 512 * 4)
        tex_names = []
        tex_count = 0
        tex_names = glGenTextures(1024)
        glEnable(GL_TEXTURE_2D)
        while all_tex_in:
            glBindTexture(GL_TEXTURE_2D, tex_names[tex_count])
            gluBuild2DMipmaps(GL_TEXTURE_2D, 4, 512, 512, GL_RGBA,
                              GL_UNSIGNED_BYTE, tex_bytes)
            tex_count += 1

            glTexCoord2f(0.0, 0.0)
            glBegin(GL_QUADS)
            glVertex2f(0.0, 0.0)
            glVertex2f(1.0, 0.0)
            glVertex2f(1.0, 1.0)
            glVertex2f(0.0, 1.0)
            glEnd()
            glFinish()

            residences = glAreTexturesResident(tex_names[:tex_count])
            all_tex_in = reduce(lambda a,b: a and b, residences)
                # bruce 070308 sees this exception from this line:
                # TypeError: reduce() arg 2 must support iteration

        glDisable(GL_TEXTURE_2D)
        glDeleteTextures(tex_names)

        gl_info_string += "Could create %d 512x512 RGBA resident textures\n" \
                          % tex_count
    return gl_info_string
Example #7
0
File: View.py Project: fossabot/mfm
    def __display(self):
        """Render the model by existent vertices, colors and triangles."""
        self.__rotate_model()
        self.__generate_shadows()
        self.__generate_model()

        glutSwapBuffers()
        if self.__synchronous:
            glFinish()
        elif self.__callback is not None:
            self.__callback()
Example #8
0
File: View.py Project: char-lie/mfm
    def __display(self):
        """Render the model by existent vertices, colors and triangles."""
        self.__rotate_model()
        self.__generate_shadows()
        self.__generate_model()

        glutSwapBuffers()
        if self.__synchronous:
            glFinish()
        elif self.__callback is not None:
            self.__callback()
Example #9
0
    def paint_rgb24(self, img_data, x, y, width, height, rowstride):
        # OpenGL begin
        if not self.gldrawable.gl_begin(self.glcontext):
            log.error("OUCH")
            return False

        # Upload texture
        if not self.texture:
            self.texture = glGenTextures(1)

        glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.texture)
        glEnable(GL_TEXTURE_RECTANGLE_ARB)
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER,
                        GL_NEAREST)
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER,
                        GL_NEAREST)
        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE)
        glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstride / 3)
        glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGB, width, height, 0,
                     GL_RGB, GL_UNSIGNED_BYTE, img_data)

        vtxarrays = 1
        if vtxarrays == 1:
            texcoords = [[0, 0], [0, height], [width, height], [width, 0]]
            vtxcoords = texcoords

            glVertexPointeri(vtxcoords)
            glTexCoordPointeri(texcoords)
            glDrawArrays(GL_QUADS, 0, 4)
        else:
            glBegin(GL_QUADS)
            glTexCoord2i(0, 0)
            glVertex2i(0, 0)

            glTexCoord2i(0, height)
            glVertex2i(0, height)

            glTexCoord2i(width, height)
            glVertex2i(width, height)

            glTexCoord2i(width, 0)
            glVertex2i(width, 0)
            glEnd()

        # OpenGL end
#self.gldrawable.swap_buffers()
#       self.gldrawable.swap_buffers()
        glFinish()
        self.gldrawable.gl_end()
Example #10
0
    def paint_rgb24(self, img_data, x, y, width, height, rowstride):
        # OpenGL begin
        if not self.gldrawable.gl_begin(self.glcontext):
            log.error("OUCH")
            return False

        # Upload texture
        if not self.texture:
            self.texture = glGenTextures(1)

        glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.texture)
        glEnable(GL_TEXTURE_RECTANGLE_ARB)
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE)
        glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstride/3)
        glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, img_data);

        vtxarrays=1
        if vtxarrays == 1:
            texcoords = [ [ 0, 0 ],
                          [ 0, height],
                          [ width, height],
                          [ width, 0] ]
            vtxcoords = texcoords

            glVertexPointeri(vtxcoords)
            glTexCoordPointeri(texcoords)
            glDrawArrays(GL_QUADS, 0, 4);
        else:
            glBegin(GL_QUADS);
            glTexCoord2i(0, 0);
            glVertex2i(0, 0);

            glTexCoord2i(0, height);
            glVertex2i(0, height);

            glTexCoord2i(width, height);
            glVertex2i(width, height);

            glTexCoord2i(width, 0);
            glVertex2i(width, 0);
            glEnd()

        # OpenGL end
#self.gldrawable.swap_buffers()
#       self.gldrawable.swap_buffers()
        glFinish()
        self.gldrawable.gl_end()
Example #11
0
File: View.py Project: char-lie/mfm
    def __generate_shadows(self):
        """Generate shadow matrix for rotated model."""
        glDisable(GL_CULL_FACE)
        glEnable(GL_POLYGON_OFFSET_FILL)
        glPolygonOffset(3, 0)

        self.__sh.change_shader(vertex=1, fragment=1)
        self.__prepare_shaders(self.__model_matrix, self.__light_matrix, True)
        self.__sh.bind_fbo()
        glClear(GL_DEPTH_BUFFER_BIT)
        glDrawElements(GL_TRIANGLES, View.__triangles.size,
                       GL_UNSIGNED_SHORT, View.__triangles)
        glFinish()
        glBindFramebuffer(GL_FRAMEBUFFER, 0)
        self.__sh.clear()
Example #12
0
File: View.py Project: fossabot/mfm
    def __generate_shadows(self):
        """Generate shadow matrix for rotated model."""
        glDisable(GL_CULL_FACE)
        glEnable(GL_POLYGON_OFFSET_FILL)
        glPolygonOffset(3, 0)

        self.__sh.change_shader(vertex=1, fragment=1)
        self.__prepare_shaders(self.__model_matrix, self.__light_matrix, True)
        self.__sh.bind_fbo()
        glClear(GL_DEPTH_BUFFER_BIT)
        glDrawElements(GL_TRIANGLES, View.__triangles.size, GL_UNSIGNED_SHORT,
                       View.__triangles)
        glFinish()
        glBindFramebuffer(GL_FRAMEBUFFER, 0)
        self.__sh.clear()
Example #13
0
def debug_info(setup):
    from OpenGL.GL import (
        glClearColor,
        glClear,
        GL_COLOR_BUFFER_BIT,
        GL_DEPTH_BUFFER_BIT,
        glGetString,
        GL_VENDOR,
        GL_EXTENSIONS,
        glFinish,
    )

    display, ctx, surface = setup
    glClearColor(1.0, 1.0, 1.0, 1.0)
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    log.info("Vendor: %s", glGetString(GL_VENDOR))
    log.info("Extensions: %s", glGetString(GL_EXTENSIONS))
    glFinish()
Example #14
0
    def paint_yuv420(self, img_data, x, y, width, height, rowstrides):
        #import time
        #before=time.time()

        # OpenGL begin
        if not self.gldrawable.gl_begin(self.glcontext):
            log.error("OUCH")
            return False

        # Upload texture
        if self.textures[0] == 0:
            self.textures = glGenTextures(3)

        glEnable(GL_FRAGMENT_PROGRAM_ARB)

        if not self.yuv420_shader:
            self.yuv420_shader = [ 1 ]
            glGenProgramsARB(1, self.yuv420_shader)
            glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.yuv420_shader[0])
# The following fragprog is:
# * MIT X11 license, Copyright (c) 2007 by:
# *      Michael Dominic K. <*****@*****.**>
#http://www.mdk.org.pl/2007/11/17/gl-colorspace-conversions
            prog = """!!ARBfp1.0
# cgc version 3.1.0010, build date Feb 10 2012
# command line args: -profile arbfp1
# source file: yuv.cg
#vendor NVIDIA Corporation
#version 3.1.0.10
#profile arbfp1
#program main
#semantic main.IN
#var float2 IN.texcoord1 : $vin.TEXCOORD0 : TEX0 : 0 : 1
#var float2 IN.texcoord2 : $vin.TEXCOORD1 : TEX1 : 0 : 1
#var float2 IN.texcoord3 : $vin.TEXCOORD2 : TEX2 : 0 : 1
#var samplerRECT IN.texture1 : TEXUNIT0 : texunit 0 : 0 : 1
#var samplerRECT IN.texture2 : TEXUNIT1 : texunit 1 : 0 : 1
#var samplerRECT IN.texture3 : TEXUNIT2 : texunit 2 : 0 : 1
#var float4 IN.color : $vin.COLOR0 : COL0 : 0 : 1
#var float4 main.color : $vout.COLOR0 : COL : -1 : 1
#const c[0] = 1.1643835 2.017231 0 0.5
#const c[1] = 0.0625 1.1643835 -0.3917616 -0.81296802
#const c[2] = 1.1643835 0 1.5960271
PARAM c[3] = { { 1.1643835, 2.017231, 0, 0.5 },
        { 0.0625, 1.1643835, -0.3917616, -0.81296802 },
        { 1.1643835, 0, 1.5960271 } };
TEMP R0;
TEMP R1;
TEX R0.x, fragment.texcoord[2], texture[2], RECT;
ADD R1.z, R0.x, -c[0].w;
TEX R1.x, fragment.texcoord[0], texture[0], RECT;
TEX R0.x, fragment.texcoord[1], texture[1], RECT;
ADD R1.x, R1, -c[1];
ADD R1.y, R0.x, -c[0].w;
DP3 result.color.z, R1, c[0];
DP3 result.color.y, R1, c[1].yzww;
DP3 result.color.x, R1, c[2];
MOV result.color.w, fragment.color.primary;
END
# 10 instructions, 2 R-regs

                    """
            glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, len(prog), prog)
            log.error(glGetString(GL_PROGRAM_ERROR_STRING_ARB))

        glEnable(GL_FRAGMENT_PROGRAM_ARB)

        glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.yuv420_shader[0])

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[0])
        glEnable(GL_TEXTURE_RECTANGLE_ARB)
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstrides[0])
        glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_LUMINANCE, width, height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, img_data[0]);

        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[1])
        glEnable(GL_TEXTURE_RECTANGLE_ARB)
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstrides[1])
        glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_LUMINANCE, width/2, height/2, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, img_data[1]);

        glActiveTexture(GL_TEXTURE2);
        glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[2])
        glEnable(GL_TEXTURE_RECTANGLE_ARB)
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstrides[2])
        glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_LUMINANCE, width/2, height/2, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, img_data[2]);

        vtxarrays=0
        if vtxarrays == 1:
            texcoords = [ [ 0, 0 ],
                          [ 0, height],
                          [ width, height],
                          [ width, 0] ]
            vtxcoords = texcoords
            texcoords_half = [ [ 0, 0 ],
                          [ 0, height/2],
                          [ width/2, height/2],
                          [ width/2, 0] ]

            glVertexPointeri(vtxcoords)

            glActiveTexture(GL_TEXTURE0);
            glClientActiveTexture(GL_TEXTURE0)
            glEnableClientState(GL_TEXTURE_COORD_ARRAY);
            glTexCoordPointeri(texcoords)

            glActiveTexture(GL_TEXTURE1);
            glClientActiveTexture(GL_TEXTURE1)
            glEnableClientState(GL_TEXTURE_COORD_ARRAY);
            glTexCoordPointeri(texcoords_half)

            glActiveTexture(GL_TEXTURE2);
            glClientActiveTexture(GL_TEXTURE2)
            glEnableClientState(GL_TEXTURE_COORD_ARRAY);
            glTexCoordPointeri(texcoords_half)

            glDrawArrays(GL_QUADS, 0, 4);

        else:
            glBegin(GL_QUADS);
            glMultiTexCoord2i(GL_TEXTURE0, 0, 0);
            glMultiTexCoord2i(GL_TEXTURE1, 0, 0);
            glMultiTexCoord2i(GL_TEXTURE2, 0, 0);
            glVertex2i(0, 0);

            glMultiTexCoord2i(GL_TEXTURE0, 0, height);
            glMultiTexCoord2i(GL_TEXTURE1, 0, height/2);
            glMultiTexCoord2i(GL_TEXTURE2, 0, height/2);
            glVertex2i(0, height);

            glMultiTexCoord2i(GL_TEXTURE0, width, height);
            glMultiTexCoord2i(GL_TEXTURE1, width/2, height/2);
            glMultiTexCoord2i(GL_TEXTURE2, width/2, height/2);
            glVertex2i(width, height);

            glMultiTexCoord2i(GL_TEXTURE0, width, 0);
            glMultiTexCoord2i(GL_TEXTURE1, width/2, 0);
            glMultiTexCoord2i(GL_TEXTURE2, width/2, 0);
            glVertex2i(width, 0);
            glEnd()

        # OpenGL end
#self.gldrawable.swap_buffers()
#       self.gldrawable.swap_buffers()
        glFinish()
        self.gldrawable.gl_end()
Example #15
0
    def paint_yuv420(self, img_data, x, y, width, height, rowstrides):
        #import time
        #before=time.time()

        # OpenGL begin
        if not self.gldrawable.gl_begin(self.glcontext):
            log.error("OUCH")
            return False

        # Upload texture
        if self.textures[0] == 0:
            self.textures = glGenTextures(3)

        glEnable(GL_FRAGMENT_PROGRAM_ARB)

        if not self.yuv420_shader:
            self.yuv420_shader = [1]
            glGenProgramsARB(1, self.yuv420_shader)
            glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.yuv420_shader[0])
            # The following fragprog is:
            # * MIT X11 license, Copyright (c) 2007 by:
            # *      Michael Dominic K. <*****@*****.**>
            #http://www.mdk.org.pl/2007/11/17/gl-colorspace-conversions
            prog = """!!ARBfp1.0
# cgc version 3.1.0010, build date Feb 10 2012
# command line args: -profile arbfp1
# source file: yuv.cg
#vendor NVIDIA Corporation
#version 3.1.0.10
#profile arbfp1
#program main
#semantic main.IN
#var float2 IN.texcoord1 : $vin.TEXCOORD0 : TEX0 : 0 : 1
#var float2 IN.texcoord2 : $vin.TEXCOORD1 : TEX1 : 0 : 1
#var float2 IN.texcoord3 : $vin.TEXCOORD2 : TEX2 : 0 : 1
#var samplerRECT IN.texture1 : TEXUNIT0 : texunit 0 : 0 : 1
#var samplerRECT IN.texture2 : TEXUNIT1 : texunit 1 : 0 : 1
#var samplerRECT IN.texture3 : TEXUNIT2 : texunit 2 : 0 : 1
#var float4 IN.color : $vin.COLOR0 : COL0 : 0 : 1
#var float4 main.color : $vout.COLOR0 : COL : -1 : 1
#const c[0] = 1.1643835 2.017231 0 0.5
#const c[1] = 0.0625 1.1643835 -0.3917616 -0.81296802
#const c[2] = 1.1643835 0 1.5960271
PARAM c[3] = { { 1.1643835, 2.017231, 0, 0.5 },
        { 0.0625, 1.1643835, -0.3917616, -0.81296802 },
        { 1.1643835, 0, 1.5960271 } };
TEMP R0;
TEMP R1;
TEX R0.x, fragment.texcoord[2], texture[2], RECT;
ADD R1.z, R0.x, -c[0].w;
TEX R1.x, fragment.texcoord[0], texture[0], RECT;
TEX R0.x, fragment.texcoord[1], texture[1], RECT;
ADD R1.x, R1, -c[1];
ADD R1.y, R0.x, -c[0].w;
DP3 result.color.z, R1, c[0];
DP3 result.color.y, R1, c[1].yzww;
DP3 result.color.x, R1, c[2];
MOV result.color.w, fragment.color.primary;
END
# 10 instructions, 2 R-regs

                    """
            glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB,
                               GL_PROGRAM_FORMAT_ASCII_ARB, len(prog), prog)
            log.error(glGetString(GL_PROGRAM_ERROR_STRING_ARB))

        glEnable(GL_FRAGMENT_PROGRAM_ARB)

        glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.yuv420_shader[0])

        glActiveTexture(GL_TEXTURE0)
        glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[0])
        glEnable(GL_TEXTURE_RECTANGLE_ARB)
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER,
                        GL_NEAREST)
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER,
                        GL_NEAREST)
        glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstrides[0])
        glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_LUMINANCE, width, height,
                     0, GL_LUMINANCE, GL_UNSIGNED_BYTE, img_data[0])

        glActiveTexture(GL_TEXTURE1)
        glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[1])
        glEnable(GL_TEXTURE_RECTANGLE_ARB)
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER,
                        GL_LINEAR)
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER,
                        GL_NEAREST)
        glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstrides[1])
        glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_LUMINANCE, width / 2,
                     height / 2, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE,
                     img_data[1])

        glActiveTexture(GL_TEXTURE2)
        glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[2])
        glEnable(GL_TEXTURE_RECTANGLE_ARB)
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER,
                        GL_LINEAR)
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER,
                        GL_NEAREST)
        glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstrides[2])
        glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_LUMINANCE, width / 2,
                     height / 2, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE,
                     img_data[2])

        vtxarrays = 0
        if vtxarrays == 1:
            texcoords = [[0, 0], [0, height], [width, height], [width, 0]]
            vtxcoords = texcoords
            texcoords_half = [[0, 0], [0, height / 2], [width / 2, height / 2],
                              [width / 2, 0]]

            glVertexPointeri(vtxcoords)

            glActiveTexture(GL_TEXTURE0)
            glClientActiveTexture(GL_TEXTURE0)
            glEnableClientState(GL_TEXTURE_COORD_ARRAY)
            glTexCoordPointeri(texcoords)

            glActiveTexture(GL_TEXTURE1)
            glClientActiveTexture(GL_TEXTURE1)
            glEnableClientState(GL_TEXTURE_COORD_ARRAY)
            glTexCoordPointeri(texcoords_half)

            glActiveTexture(GL_TEXTURE2)
            glClientActiveTexture(GL_TEXTURE2)
            glEnableClientState(GL_TEXTURE_COORD_ARRAY)
            glTexCoordPointeri(texcoords_half)

            glDrawArrays(GL_QUADS, 0, 4)

        else:
            glBegin(GL_QUADS)
            glMultiTexCoord2i(GL_TEXTURE0, 0, 0)
            glMultiTexCoord2i(GL_TEXTURE1, 0, 0)
            glMultiTexCoord2i(GL_TEXTURE2, 0, 0)
            glVertex2i(0, 0)

            glMultiTexCoord2i(GL_TEXTURE0, 0, height)
            glMultiTexCoord2i(GL_TEXTURE1, 0, height / 2)
            glMultiTexCoord2i(GL_TEXTURE2, 0, height / 2)
            glVertex2i(0, height)

            glMultiTexCoord2i(GL_TEXTURE0, width, height)
            glMultiTexCoord2i(GL_TEXTURE1, width / 2, height / 2)
            glMultiTexCoord2i(GL_TEXTURE2, width / 2, height / 2)
            glVertex2i(width, height)

            glMultiTexCoord2i(GL_TEXTURE0, width, 0)
            glMultiTexCoord2i(GL_TEXTURE1, width / 2, 0)
            glMultiTexCoord2i(GL_TEXTURE2, width / 2, 0)
            glVertex2i(width, 0)
            glEnd()

        # OpenGL end
#self.gldrawable.swap_buffers()
#       self.gldrawable.swap_buffers()
        glFinish()
        self.gldrawable.gl_end()
def get_gl_info_string(glpane): # grantham 20051129
    """
    Return a string containing some useful information about the OpenGL
    implementation.

    Use the GL context from the given QGLWidget glpane (by calling
    glpane.makeCurrent()).
    """

    glpane.makeCurrent() #bruce 070308 added glpane arg and makeCurrent call

    gl_info_string = ''

    gl_info_string += 'GL_VENDOR : "%s"\n' % glGetString(GL_VENDOR)
    gl_info_string += 'GL_VERSION : "%s"\n' % glGetString(GL_VERSION)
    gl_info_string += 'GL_RENDERER : "%s"\n' % glGetString(GL_RENDERER)
    gl_extensions = glGetString(GL_EXTENSIONS)
    gl_extensions = gl_extensions.strip()
    gl_extensions = gl_extensions.replace(" ", "\n* ")
    gl_info_string += 'GL_EXTENSIONS : \n* %s\n' % gl_extensions

    if debug_pref("Graphics Card Info: call glAreTexturesResident?",
                  Choice_boolean_False):
        # Give a practical indication of how much video memory is available.
        # Should also do this with VBOs.

        # I'm pretty sure this code is right, but PyOpenGL seg faults in
        # glAreTexturesResident, so it's disabled until I can figure that
        # out. [grantham] [bruce 070308 added the debug_pref]

        all_tex_in = True
        tex_bytes = '\0' * (512 * 512 * 4)
        tex_names = []
        tex_count = 0
        tex_names = glGenTextures(1024)
        glEnable(GL_TEXTURE_2D)
        while all_tex_in:
            glBindTexture(GL_TEXTURE_2D, tex_names[tex_count])
            gluBuild2DMipmaps(GL_TEXTURE_2D, 4, 512, 512, GL_RGBA,
                              GL_UNSIGNED_BYTE, tex_bytes)
            tex_count += 1

            glTexCoord2f(0.0, 0.0)
            glBegin(GL_QUADS)
            glVertex2f(0.0, 0.0)
            glVertex2f(1.0, 0.0)
            glVertex2f(1.0, 1.0)
            glVertex2f(0.0, 1.0)
            glEnd()
            glFinish()

            residences = glAreTexturesResident(tex_names[:tex_count])
            all_tex_in = reduce(lambda a,b: a and b, residences)
                # bruce 070308 sees this exception from this line:
                # TypeError: reduce() arg 2 must support iteration

        glDisable(GL_TEXTURE_2D)
        glDeleteTextures(tex_names)

        gl_info_string += "Could create %d 512x512 RGBA resident textures\n" \
                          % tex_count
        pass

    if True: ## or could be a debug_pref("Graphics Card Info: get all GL_MAX symbols?")
        #bruce 090314 new feature
        import OpenGL.GL
        symbols = [x for x in dir(OpenGL.GL) if x.startswith('GL_MAX_')]
        symbols.sort()
        gl_info_string += '\n'
        for symbol in symbols:
            try:
                numeric_symbol = getattr(OpenGL.GL, symbol)
                intval = glGetInteger(numeric_symbol)
            except:
                # this happens to most symbols, not sure why
                if debug_flags.atom_debug:
                    print_compact_traceback( "%s = ??: " % symbol )
                        # overkill, only the exception itself matters
                    # typical output (on Bruce's MacBookPro, 090314):
                    ## GL_MAX_4D_TEXTURE_SIZE_SGIS = ??:
                    ## <type 'exceptions.KeyError'>:
                    ## ('Unknown specifier GL_MAX_4D_TEXTURE_SIZE_SGIS (33080)',
                    ##  'Failure in cConverter <OpenGL.converters.SizedOutput object at 0x1457fab0>',
                    ##  [GL_MAX_4D_TEXTURE_SIZE_SGIS], 1, <OpenGL.wrapper.glGetIntegerv object at 0x1458aa30>)
                    ## [graphics_card_info.py:122] [wrapper.py:676] [converters.py:195] [converters.py:234]
                    pass
                pass ## gl_info_string += "%s = ??\n" % symbol
            else:
                gl_info_string += "%s = %r\n" % (symbol, intval)
            continue
        pass

    return gl_info_string
Example #17
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
Example #18
0
def get_gl_info_string(glpane):  # grantham 20051129
    """
    Return a string containing some useful information about the OpenGL
    implementation.

    Use the GL context from the given QGLWidget glpane (by calling
    glpane.makeCurrent()).
    """

    glpane.makeCurrent()  #bruce 070308 added glpane arg and makeCurrent call

    gl_info_string = ''

    gl_info_string += 'GL_VENDOR : "%s"\n' % glGetString(GL_VENDOR)
    gl_info_string += 'GL_VERSION : "%s"\n' % glGetString(GL_VERSION)
    gl_info_string += 'GL_RENDERER : "%s"\n' % glGetString(GL_RENDERER)
    gl_extensions = glGetString(GL_EXTENSIONS)
    gl_extensions = gl_extensions.strip()
    gl_extensions = gl_extensions.replace(" ", "\n* ")
    gl_info_string += 'GL_EXTENSIONS : \n* %s\n' % gl_extensions

    if debug_pref("Graphics Card Info: call glAreTexturesResident?",
                  Choice_boolean_False):
        # Give a practical indication of how much video memory is available.
        # Should also do this with VBOs.

        # I'm pretty sure this code is right, but PyOpenGL seg faults in
        # glAreTexturesResident, so it's disabled until I can figure that
        # out. [grantham] [bruce 070308 added the debug_pref]

        all_tex_in = True
        tex_bytes = '\0' * (512 * 512 * 4)
        tex_names = []
        tex_count = 0
        tex_names = glGenTextures(1024)
        glEnable(GL_TEXTURE_2D)
        while all_tex_in:
            glBindTexture(GL_TEXTURE_2D, tex_names[tex_count])
            gluBuild2DMipmaps(GL_TEXTURE_2D, 4, 512, 512, GL_RGBA,
                              GL_UNSIGNED_BYTE, tex_bytes)
            tex_count += 1

            glTexCoord2f(0.0, 0.0)
            glBegin(GL_QUADS)
            glVertex2f(0.0, 0.0)
            glVertex2f(1.0, 0.0)
            glVertex2f(1.0, 1.0)
            glVertex2f(0.0, 1.0)
            glEnd()
            glFinish()

            residences = glAreTexturesResident(tex_names[:tex_count])
            all_tex_in = reduce(lambda a, b: a and b, residences)
            # bruce 070308 sees this exception from this line:
            # TypeError: reduce() arg 2 must support iteration

        glDisable(GL_TEXTURE_2D)
        glDeleteTextures(tex_names)

        gl_info_string += "Could create %d 512x512 RGBA resident textures\n" \
                          % tex_count
        pass

    if True:  ## or could be a debug_pref("Graphics Card Info: get all GL_MAX symbols?")
        #bruce 090314 new feature
        import OpenGL.GL
        symbols = [x for x in dir(OpenGL.GL) if x.startswith('GL_MAX_')]
        symbols.sort()
        gl_info_string += '\n'
        for symbol in symbols:
            try:
                numeric_symbol = getattr(OpenGL.GL, symbol)
                intval = glGetInteger(numeric_symbol)
            except:
                # this happens to most symbols, not sure why
                if debug_flags.atom_debug:
                    print_compact_traceback("%s = ??: " % symbol)
                    # overkill, only the exception itself matters
                    # typical output (on Bruce's MacBookPro, 090314):
                    ## GL_MAX_4D_TEXTURE_SIZE_SGIS = ??:
                    ## <type 'exceptions.KeyError'>:
                    ## ('Unknown specifier GL_MAX_4D_TEXTURE_SIZE_SGIS (33080)',
                    ##  'Failure in cConverter <OpenGL.converters.SizedOutput object at 0x1457fab0>',
                    ##  [GL_MAX_4D_TEXTURE_SIZE_SGIS], 1, <OpenGL.wrapper.glGetIntegerv object at 0x1458aa30>)
                    ## [graphics_card_info.py:122] [wrapper.py:676] [converters.py:195] [converters.py:234]
                    pass
                pass  ## gl_info_string += "%s = ??\n" % symbol
            else:
                gl_info_string += "%s = %r\n" % (symbol, intval)
            continue
        pass

    return gl_info_string
Example #19
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
Example #20
0
 def Exit(self):
     """Stop the simulation and quit"""
     glFinish()
     self.world.DumpGameState()
     sys.exit()