Exemplo n.º 1
0
    def paintGL(self):
        if self.crashFlag:      #run cleanup operations
            glUseProgram(0)
            glDisableVertexAttribArray(self.attrID)
            glDeleteBuffers(1,[self.vertexBuffer])
            glDeleteVertexArrays(1, [self.vertexArrayID])

        glLoadIdentity()
        gluPerspective(45, self.sizeX / self.sizeY, 0.1, 110.0)    #set perspective
        glTranslatef(0, 0, self.zoomLevel)
        glRotatef(self.rotateDegreeV + self.vOffset, 1, 0, 0)
        glRotatef(self.rotateDegreeH, 0, 0, 1)
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

        self.vertexData = [
            -1, 1, 0,
            0, -1, 0,
            1, 1, 0
        ]

        arrayType = GLfloat * len(self.vertexData)

        target = GL_ARRAY_BUFFER
        offset = 0
        size = len(self.vertexData) * ctypes.sizeof(ctypes.c_float)
        data = arrayType(*self.vertexData)
        glBufferSubData(target, offset, size, data)

        glDrawArrays(GL_TRIANGLES, 0, 3)
Exemplo n.º 2
0
 def draw(self, reset, modelview):
     """Binds the shaders and things to draw the lamp itself.
     Takes a reference to the 'matrix reset' function, and a modelview matrix to draw by."""
     glUseProgram(shaderl)
     reset(shaderl)
     glUniformMatrix4fv(glGetUniformLocation(shaderl, 'modelmatrix'), 1, False, modelview)
     self.model.draw()
Exemplo n.º 3
0
    def render(self) -> None:
        """Render ViewCube to canvas."""
        if not self.init():
            return

        glViewport(*self._get_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)
        glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, ctypes.c_void_p(0))

        self._render_highlighted()

        glBindVertexArray(0)
        glUseProgram(0)
Exemplo n.º 4
0
    def plot(self):

        # Specify shader to be used
        glUseProgram(self.gls_pgr.program_id)

        # Bind VAO - this will automatically
        # bind all the vbo's saving us a bunch
        # of calls
        #glBindVertexArray(self.vao_id)

        glUniform4fv(self.gls_id_xy_color,1, self.plot_color)

        # Modern GL makes the draw call really simple
        # All the complexity has been pushed elsewhere


        glEnableVertexAttribArray(self.vertIndex)


        # set buffers
        glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer)
        glVertexAttribPointer(self.vertIndex,2, GL_FLOAT, GL_FALSE, 0, None)

        glDrawArrays(GL_LINE_STRIP, 0, self.data_points-1)

        # Lets unbind the shader and vertex array state
        glUseProgram(0)
        # disable arrays
        glDisableVertexAttribArray(self.vertIndex)

        glBindVertexArray(0)
Exemplo n.º 5
0
    def initGL(self):
        self.vertexData = [-1, -1, 0,
                           1, -1, 0,
                           0, 1, 0]

        self.vertexArrayID = glGenVertexArrays(1)
        glBindVertexArray(self.vertexArrayID)

        self.attrID = 0
        self.vertexBuffer = glGenBuffers(1)
        glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer)
        arrayType = GLfloat * len(self.vertexData)

        #initialize data for the buffer
        target = GL_ARRAY_BUFFER
        size = len(self.vertexData) * ctypes.sizeof(ctypes.c_float)
        data = arrayType(*self.vertexData)
        usage = GL_STATIC_DRAW
        glBufferData(target, size, data, usage)
                     
        glVertexAttribPointer(self.attrID, 3, GL_FLOAT, False, 0, None)
        glEnableVertexAttribArray(self.attrID)
        
        #access the code for the vertex and fragment shaders
        with open(self.vertPath, 'r') as vertProg:
            self.vertCode = vertProg.read()
        
        with open(self.fragPath, 'r') as fragProg:
            self.fragCode = fragProg.read()
        
        #compile those shaders
        self.vertShader = shaders.compileShader(self.vertCode, GL_VERTEX_SHADER)
        self.fragShader = shaders.compileShader(self.fragCode, GL_FRAGMENT_SHADER)
        self.shader = shaders.compileProgram(self.vertShader, self.fragShader)
        glUseProgram(self.shader)
Exemplo n.º 6
0
    def _draw(self, transformation_matrix: numpy.ndarray):
        glUseProgram(self._shader)
        glUniformMatrix4fv(
            self._transform_location,
            1,
            GL_FALSE,
            transformation_matrix.T.astype(numpy.float32),
        )
        glUniform1i(self._texture_location, 0)
        try:
            glBindVertexArray(self._vao)
        except GLError:  # There seems to be errors randomly when binding the VBO
            log.debug(
                f"Failed binding the OpenGL state for {self}. Trying to reload it."
            )
            self.unload()
            self._setup()
            glBindVertexArray(self._vao)
        glActiveTexture(GL_TEXTURE0)
        glBindTexture(GL_TEXTURE_2D, self._texture)

        glDrawArrays(self.draw_mode, self.draw_start, self.draw_count)

        glBindVertexArray(0)
        glUseProgram(0)
Exemplo n.º 7
0
    def plot(self):

        # Specify shader to be used
        glUseProgram(self.gls_pgr.program_id)

        # Bind VAO - this will automatically
        # bind all the vbo's saving us a bunch
        # of calls
        #glBindVertexArray(self.vao_id)

        glUniform4fv(self.gls_id_xy_color, 1, self.plot_color)

        # Modern GL makes the draw call really simple
        # All the complexity has been pushed elsewhere

        glEnableVertexAttribArray(self.vertIndex)

        # set buffers
        glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer)
        glVertexAttribPointer(self.vertIndex, 2, GL_FLOAT, GL_FALSE, 0, None)

        glDrawArrays(GL_LINE_STRIP, 0, self.data_points - 1)

        # Lets unbind the shader and vertex array state
        glUseProgram(0)
        # disable arrays
        glDisableVertexAttribArray(self.vertIndex)

        glBindVertexArray(0)
Exemplo n.º 8
0
    def render(self) -> None:
        """Render chamber to canvas."""
        if not self.init():
            return

        glDisable(GL_LINE_SMOOTH)

        proj = self.parent.projection_matrix
        modelview = self.parent.modelview_matrix

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

        if self._grid_shown:
            self._render_gridlines()

        if self._axes_shown:
            self._render_axes()

        if self._bbox_shown:
            self._render_bounding_box()

        glBindVertexArray(0)
        glUseProgram(0)
        glEnable(GL_LINE_SMOOTH)
Exemplo n.º 9
0
    def render(self, model, view_matrix, projection_matrix):
        glUseProgram(self.program)

        glEnableVertexAttribArray(self.texcoords)
        glEnableVertexAttribArray(self.vertices)

        glUniformMatrix4fv(
            self.model_view_matrix, 1, GL_TRUE,
            np.dot(view_matrix, model.matrix)
        )
        glUniformMatrix4fv(
            self.projection_matrix, 1, GL_TRUE, projection_matrix
        )

        for group in model.groups:
            glBindTexture(GL_TEXTURE_2D, group.material.texture)
            glUniform1i(self.texture, 0)
            glVertexAttribPointer(
                self.vertices, 3, GL_FLOAT, GL_FALSE, 0, group.vertex_buffer
            )
            glVertexAttribPointer(
                self.texcoords, 2, GL_FLOAT, GL_FALSE, 0, group.texcoord_buffer
            )

            glDrawArrays(GL_TRIANGLES, 0, len(group.vertex_buffer))

        glDisableVertexAttribArray(self.vertices)
        glDisableVertexAttribArray(self.texcoords)
Exemplo n.º 10
0
def init(resources):

    glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT)
    glUseProgram(resources.init_program)
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, resources.seed_buffer)
    glDispatchCompute(RAY_COUNT // 16, 1, 1)
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, 0)
    glUseProgram(0)
Exemplo n.º 11
0
    def _render_objects_for_picking(self) -> None:
        """Render objects with RGB color corresponding to id for picking."""
        self._objectvis.render_for_picking()
        self._actionvis.render_for_picking()
        self._viewcube.render_for_picking()

        glBindVertexArray(0)
        glUseProgram(0)
Exemplo n.º 12
0
    def draw_hud(self):
        """Render HUD."""

        # TODO: add resize changes
        # glUseProgram(self.hud_shader)
        # temporary solution
        glUseProgram(0)
        self.test_label.draw()
Exemplo n.º 13
0
    def init_shader(self, vertex=None, fragment=None):

        if self.gls_pgr:
           glUseProgram(0)
           if self.gls_pgr.shader_id:
              glDeleteShader(self.gls_pgr.shader_id)

        if vertex is None:

           vertex = """
                        #version 330
                        attribute vec2 xy_pos;
                        uniform vec4 xy_color;
                        uniform vec4 xy_color1;

                        varying vec4 frg_color;

                        void main(void)
                        {
                            frg_color = xy_color;
                            gl_Position = vec4(xy_pos,0, 1.0);
                        }
                    """
           print vertex

        if fragment is None:
           fragment = """
                         #version 330
                         varying vec4 frg_color;

                         void main(void)
                          {
                            gl_FragColor = frg_color;
                          }
                      """
           print fragment

        self.gls_pgr = ShaderProgram(vertex,fragment)
        glUseProgram(self.gls_pgr.program_id)



        self.vertIndex = self.gls_pgr.attribute_location('xy_pos')

        #glVertexAttribPointer(self.gls_pgr.attribute_location('xy_pos'), 2, GL_FLOAT, GL_FALSE, 0, None)

        # Turn on this vertex attribute in the shader
        #glEnableVertexAttribArray(0)


        self.gls_id_xy_color = self.gls_pgr.uniform_location("xy_color")
        print self.gls_id_xy_color

        cid=glGetUniformLocation(self.gls_pgr.program_id,"xy_color1")
        print cid
        glUniform4fv(self.gls_id_xy_color,1, self.color)
Exemplo n.º 14
0
      def GLBatch(self,idx,ch_idx,data=None,tlines=GL_LINE_STRIP):
          
          self.trafo_matrix = jtr.ortho(self.xmin,self.xmax,self.data_min_max[idx,0],self.data_min_max[idx,1],0,1)
          #print "TRMAT"
          #print self.trafo_matrix
                  
          #---TODO viewport to GLS TrafoMatrix  like C++ example or  Perspective Matrix  as GeometryShader split x,y into VBOs cp only y7signal value
           #--- set border scissor
          #i=idx
          #idx=0          
         
          glViewport(self.mvp[idx,0],self.mvp[idx,1],self.mvp[idx,2],self.mvp[idx,3])
          #glRasterPos2f(self.mvp[idx,0],self.mvp[idx,1])
          #glLoadIdentity()          
          glRasterPos2f( -1.0,0.0)
          glColor4f(0.0,0.0,0.0,1.0)
          
          
          for idx_chr in str( self.info.plt_channels.label[ch_idx] ):
              glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord( idx_chr ) )
             # glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord( str(idx_chr) ))
       
      
         
         
          #glScissor(0.1,0.1,0.8,0.8)
          #glClearColor(0.5,0.5,0.5,0.0)
          #glClear(GL_COLOR_BUFFER_BIT)
         

          #idx=i 
          glUseProgram(self.GLSL.program_id)

         #--- set trafo matrix
          glUniformMatrix4fv(self.glsl_u_trafomatrix, 1, GL_FALSE, self.trafo_matrix)
         #--- set color
         
         
          color_idx = self.info.plt_channels.color_index[ch_idx]
          co = self.info.plt_color.index2colour(color_idx)
         
          # glUniform4fv(self.glsl_u_color, 1,self.plot_color[idx])
          glUniform4fv(self.glsl_u_color, 1,co)

         #--- enable arrays
          glEnableVertexAttribArray(self.glsl_a_position2d)
          self.vbo_sig_data.vbo_update_y( data=data)#.ctypes.data )
          # self.vbo_sig_data.vbo_update_y( data=self.data[idx,:] )
  
        
          glVertexAttribPointer(self.glsl_a_position2d,2, GL_FLOAT, GL_FALSE, 0, None)
          glDrawArrays(tlines, 0, self.vbo_sig_data.data_points-1)

          glDisableVertexAttribArray(self.glsl_a_position2d)
Exemplo n.º 15
0
 def use(self) -> bool:
     """Use GLSL Program.
     This method should be called before setting any variables or rendering
     any entities
     """
     if self.program == -1:
         logging.error("Shader not compiled")
         return False
     glUseProgram(self.program)
     glEnable(GL_PROGRAM_POINT_SIZE)
     return True
Exemplo n.º 16
0
def enableGammaCorrection(window):
    """Enables M16 or C48 shader gamma correction"""
    from OpenGL.GL import glUseProgram, glUniform3f, glGetUniformLocation, glUniform1i
    if not hasattr(window, '_DPShaderProg'):
        raise Warning(
            "Shader not set up! make sure you call setUpShaderAndWindow before setting up gamma correction."
        )
        return
    glUseProgram(window._DPShaderProg)
    glUniform1i(
        glGetUniformLocation(window._DPShaderProg, "gamma_correction_flag"), 1)
Exemplo n.º 17
0
    def init_shader(self, vertex=None, fragment=None):

        if self.gls_pgr:
            glUseProgram(0)
            if self.gls_pgr.shader_id:
                glDeleteShader(self.gls_pgr.shader_id)

        if vertex is None:

            vertex = """
                        #version 330
                        attribute vec2 xy_pos;
                        uniform vec4 xy_color;
                        uniform vec4 xy_color1;

                        varying vec4 frg_color;

                        void main(void)
                        {
                            frg_color = xy_color;
                            gl_Position = vec4(xy_pos,0, 1.0);
                        }
                    """
            print vertex

        if fragment is None:
            fragment = """
                         #version 330
                         varying vec4 frg_color;

                         void main(void)
                          {
                            gl_FragColor = frg_color;
                          }
                      """
            print fragment

        self.gls_pgr = ShaderProgram(vertex, fragment)
        glUseProgram(self.gls_pgr.program_id)

        self.vertIndex = self.gls_pgr.attribute_location('xy_pos')

        #glVertexAttribPointer(self.gls_pgr.attribute_location('xy_pos'), 2, GL_FLOAT, GL_FALSE, 0, None)

        # Turn on this vertex attribute in the shader
        #glEnableVertexAttribArray(0)

        self.gls_id_xy_color = self.gls_pgr.uniform_location("xy_color")
        print self.gls_id_xy_color

        cid = glGetUniformLocation(self.gls_pgr.program_id, "xy_color1")
        print cid
        glUniform4fv(self.gls_id_xy_color, 1, self.color)
Exemplo n.º 18
0
    def use_shader(self, shader_name):
        """Use cached shader.

        Args:
            shader_name (str): shader name in cache dict
        """

        if shader_name in self.shader_programs:

            glUseProgram(self.shader_programs[shader_name])

        else:

            glUseProgram(0)
Exemplo n.º 19
0
 def draw_detector(self):
     glUseProgram(self.shader)
     try:
         self.dom_positions_vbo.bind()
         try:
             glEnableClientState(GL_VERTEX_ARRAY)
             glVertexPointerf(self.dom_positions_vbo)
             glPointSize(2)
             glDrawArrays(GL_POINTS, 0, len(self.dom_positions)*3)
         finally:
             self.dom_positions_vbo.unbind()
             glDisableClientState(GL_VERTEX_ARRAY)
     finally:
         glUseProgram(0)
Exemplo n.º 20
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)
Exemplo n.º 21
0
def setUpC48gammaCorrection(window, monitor, gamma_grid=None):
    """Sets up the gamma correction for C48
    
    Args:
        window (PsychoPy.Window object): A PsychoPy Window object
        monitor (PsychoPy.Monitor object): The current monitor being used
        gamma_grid (list, optional): The gamma information if it is not contained in the monitor. (gamma_rgb; b_rgb, k_rgb)
    """
    if not hasattr(window, '_DPShaderProg'):
        raise Warning(
            "Shader not set up! make sure you call setUpShaderAndWindow before setting up gamma correction."
        )
        return

    from OpenGL.GL import glUseProgram, glUniform3f, glGetUniformLocation, glUniform1i
    glUseProgram(window._DPShaderProg)

    loc = glGetUniformLocation(window._DPShaderProg, "gamma_rgb")
    if loc == -1:
        raise Warning(
            "The current shader is not the right shader, are you sure you are in M16 mode?"
        )
        return

    if gamma_grid is None:
        gamma_grid = monitor.getGammaGrid()
        if gamma_grid is None:
            raise Warning(
                "You did not provide gamma information and your monitor does not have any."
            )
            return
        gamma_rgb = [gamma_grid[1][2], gamma_grid[2][2],
                     gamma_grid[3][2]]  # gamma
        b_rgb = [gamma_grid[1][4], gamma_grid[2][4], gamma_grid[3][4]]  # b
        k_rgb = [gamma_grid[1][5], gamma_grid[2][5], gamma_grid[3][5]]  # k
    else:
        gamma_rgb = [gamma_grid[0][0], gamma_grid[0][1],
                     gamma_grid[0][2]]  # gamma
        b_rgb = [gamma_grid[1][0], gamma_grid[1][1], gamma_grid[1][2]]  # b
        k_rgb = [gamma_grid[2][0], gamma_grid[2][1], gamma_grid[2][2]]  # k

    glUniform3f(glGetUniformLocation(window._DPShaderProg, "b_rgb"), b_rgb[0],
                b_rgb[1], b_rgb[2])
    glUniform3f(glGetUniformLocation(window._DPShaderProg, "k_rgb"), k_rgb[0],
                k_rgb[1], k_rgb[2])
    glUniform3f(glGetUniformLocation(window._DPShaderProg, "gamma_rgb"),
                gamma_rgb[0], gamma_rgb[1], gamma_rgb[2])
    glUniform1i(
        glGetUniformLocation(window._DPShaderProg, "gamma_correction_flag"), 1)
Exemplo n.º 22
0
    def on_render(self, area, *args):
        area.attach_buffers()

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glUseProgram(self.shaderContent.shader_prog)
        self.timer()
        glUniform1f(self.time_l, self.time)
        glBindVertexArray(self.vertex_array_object)
        glDrawArrays(GL_TRIANGLES, 0, 6)
        glBindVertexArray(0)

        glUseProgram(0)
        glFlush()
        self.shaderContent.queue_render()
        return True
Exemplo n.º 23
0
Arquivo: Ray.py Projeto: meuns/Sandbox
def trace(resources, iteration, world_buffer, random_buffer):

    glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT)
    glUseProgram(resources.trace_program)
    #glUniform1ui(0, iteration)
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, world_buffer)
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, _select_input_buffer(resources, iteration))
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, _select_output_buffer(resources, iteration))
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, random_buffer)
    glDispatchCompute(RAY_COUNT // RAY_GROUP_SIZE, 1, 1)
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, 0)
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, 0)
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, 0)
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, 0)
    glUseProgram(0)
Exemplo n.º 24
0
Arquivo: Ray.py Projeto: meuns/Sandbox
def display_lines(resources, view_projection, iteration):

    glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT)
    glEnable(GL_BLEND)
    glBlendEquation(GL_FUNC_ADD)
    glBlendFunc(GL_ONE, GL_ONE)
    glBindVertexArray(resources.display_vertex_array)
    glUseProgram(resources.display_program)
    update_view_projection(view_projection)
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, _select_input_buffer(resources, iteration))
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, _select_output_buffer(resources, iteration))
    glDrawArrays(GL_LINES, 0, RAY_COUNT << 1)
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, 0)
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, 0)
    glUseProgram(0)
    glBindVertexArray(0)
    glDisable(GL_BLEND)
Exemplo n.º 25
0
 def _setup(self):
     """Setup OpenGL attributes if required"""
     if self._vao is None:  # if the opengl state has not been set
         self._shader = get_shader(self.context_identifier, self.shader_name)
         glUseProgram(self._shader)
         self._transform_location = glGetUniformLocation(
             self._shader, "transformation_matrix"
         )
         self._texture_location = glGetUniformLocation(self._shader, "image")
         self._vao = glGenVertexArrays(1)  # create the array
         glBindVertexArray(self._vao)
         self._vbo = glGenBuffers(1)  # and the buffer
         glBindBuffer(GL_ARRAY_BUFFER, self._vbo)
         self._setup_opengl_attrs()
         self._change_verts()
         glBindVertexArray(0)
         glBindBuffer(GL_ARRAY_BUFFER, 0)
         glUseProgram(0)
Exemplo n.º 26
0
def render_with_context(context):
    glUseProgram(context["shader"])

    # need true because our matrices are row-major and opengl wants column major by default.
    modelview = context["modelview"]
    projection = context["projection"]

    glUniformMatrix4fv(modelview["location"], 1, True, modelview["matrix"])
    glUniformMatrix4fv(projection["location"], 1, True, projection["matrix"])
    position_location = context["position_location"]
    normal_location = context["normal_location"]
    color_location = context["color_location"]

    stack = [modelview["matrix"]]
    try:
        render_thing(context["thing"], position_location, normal_location, color_location, modelview["location"], stack)
    finally:
        shaders.glUseProgram( 0 )
def main():
    # Initialize the library
    if not glfw.init():
        return
    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(640, 480, "Triangle_test", None, None)
    if not window:
        glfw.terminate()
        return

    # Make the window's context current
    glfw.make_context_current(window)
    glfw.window_hint(
        glfw.CONTEXT_VERSION_MAJOR,
        3)  # didn't find it in docs, just in __init__.py of glfwpy in git.
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR,
                     2)  # works, ofc, well with 120 shaders and 330.
    glClearColor(0.85, 0.9, 0.85, 0)  # background color
    program = ShaderProgram(vertpath="test_vert.glsl",
                            fragpath="test_frag.glsl")
    vao_id = getTriangleVAO(program)
    vao_id1 = getTriangleVAO1(program)
    # Loop until the user closes the window
    while not glfw.window_should_close(window):
        # Render here, e.g. using pyOpenGL
        glClear(GL_COLOR_BUFFER_BIT)
        # use our shader program in this part -> make program object to be a part of a rendering process.
        glUseProgram(program.program_id)
        # use vao with coords and colors buffers for triangle
        glBindVertexArray(vao_id)
        # how to draw
        glDrawArrays(GL_TRIANGLES, 0, 3)
        # unbind shader program
        glUseProgram(0)
        # unbind vao
        glBindVertexArray(0)
        # here we can draw something another
        # some more objects in another vao.
        glUseProgram(program.program_id)
        # use vao with coords and colors buffers for triangle
        glBindVertexArray(vao_id1)
        # how to draw
        glDrawArrays(GL_TRIANGLES, 0, 3)
        # unbind shader program
        glUseProgram(0)
        # unbind vao
        glBindVertexArray(0)
        # Swap front and back buffers
        glfw.swap_buffers(window)
        # Poll for and process events
        glfw.poll_events()

    glfw.terminate()
Exemplo n.º 28
0
    def render(self) -> None:
        """Render proxy objects to canvas with a diffuse shader."""
        if not self.init():
            return

        proj = self.parent.projection_matrix
        view = self.parent.modelview_matrix

        glUseProgram(self.parent.shaders['diffuse'])
        glUniformMatrix4fv(0, 1, GL_FALSE, glm.value_ptr(proj))
        glUniformMatrix4fv(1, 1, GL_FALSE, glm.value_ptr(view))

        for mesh in self._meshes:
            glBindVertexArray(mesh.vao)
            glUniform4fv(2, 1, glm.value_ptr(mesh.color))
            glUniform1i(3, int(mesh.selected))
            glDrawElements(GL_TRIANGLES, mesh.count, GL_UNSIGNED_INT,
                           ctypes.c_void_p(0))

        glBindVertexArray(0)
        glUseProgram(0)
Exemplo n.º 29
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)
Exemplo n.º 30
0
    def render(self, model, view_matrix, projection_matrix):
        glUseProgram(self.program)

        glEnableVertexAttribArray(self.vertices)

        glUniformMatrix4fv(self.model_view_matrix, 1, GL_TRUE,
                           np.dot(view_matrix, model.matrix))
        glUniformMatrix4fv(self.projection_matrix, 1, GL_TRUE,
                           projection_matrix)

        glVertexAttribPointer(self.vertices, 3, GL_FLOAT, GL_FALSE, 0,
                              model.vertex_buffer)

        glUniform1f(self.color_uniform, 0)
        glDrawElements(GL_LINES, model.line_buffer.size, GL_UNSIGNED_BYTE,
                       model.line_buffer)

        glUniform1f(self.color_uniform, 0.5)
        glDrawElements(GL_TRIANGLES, model.index_buffer.size, GL_UNSIGNED_BYTE,
                       model.index_buffer)

        glDisableVertexAttribArray(self.vertices)
Exemplo n.º 31
0
    def render_for_picking(self) -> None:
        """Render action "pickables" for picking pass."""
        if not self.init():
            return

        proj = self.parent.projection_matrix
        view = self.parent.modelview_matrix

        glUseProgram(self.parent.shaders['instanced_picking'])
        glUniformMatrix4fv(0, 1, GL_FALSE, glm.value_ptr(proj))
        glUniformMatrix4fv(1, 1, GL_FALSE, glm.value_ptr(view))

        # render cameras for picking
        glBindVertexArray(self._vaos['camera'])
        glDrawArraysInstanced(GL_QUADS, 0, 24, self._num_devices)

        # render points for picking
        if self._num_points > 0:
            glBindVertexArray(self._vaos['box'])
            glDrawArraysInstanced(GL_QUADS, 0, 24, self._num_points)

        glBindVertexArray(0)
        glUseProgram(0)
Exemplo n.º 32
0
    def render(self) -> None:
        """Render actions to canvas."""
        if not self.init():
            return

        proj = self.parent.projection_matrix
        view = self.parent.modelview_matrix
        model = mat4()

        # --- render cameras ---

        glUseProgram(self.parent.shaders['instanced_model_color'])
        glUniformMatrix4fv(0, 1, GL_FALSE, glm.value_ptr(proj))
        glUniformMatrix4fv(1, 1, GL_FALSE, glm.value_ptr(view))
        glBindVertexArray(self._vaos['camera'])
        glDrawArraysInstanced(GL_QUADS, 0, 24, self._num_devices)

        # --- render path lines ---

        glUseProgram(self.parent.shaders['single_color'])
        glUniformMatrix4fv(0, 1, GL_FALSE, glm.value_ptr(proj))
        glUniformMatrix4fv(1, 1, GL_FALSE, glm.value_ptr(view))
        glUniformMatrix4fv(2, 1, GL_FALSE, glm.value_ptr(model))

        for key, value in self._vaos['line'].items():
            color = self.colors[key % len(self.colors)]
            glUniform4fv(3, 1, glm.value_ptr(color))
            glBindVertexArray(value)
            glDrawArrays(GL_LINE_STRIP, 0, len(self._items['line'][key]))

        # --- render points ---

        if self._num_points > 0:
            glUseProgram(self.parent.shaders['instanced_model_color'])
            glUniformMatrix4fv(0, 1, GL_FALSE, glm.value_ptr(proj))
            glUniformMatrix4fv(1, 1, GL_FALSE, glm.value_ptr(view))
            glBindVertexArray(self._vaos['box'])
            glDrawArraysInstanced(GL_QUADS, 0, 24, self._num_points)

        glBindVertexArray(0)
        glUseProgram(0)
Exemplo n.º 33
0
Arquivo: Ray.py Projeto: meuns/Sandbox
def display_directions(resources, iteration):

    glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT)
    glUseProgram(resources.gather_dir_program)
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, resources.display_dir_buffer)
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, _select_input_buffer(resources, iteration))
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, _select_output_buffer(resources, iteration))
    glDispatchCompute(RAY_DIR_COUNT // RAY_DIR_GROUP_SIZE, 1, 1)
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, 0)
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, 0)
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, 0)
    glUseProgram(0)

    glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT)
    glBindVertexArray(resources.display_vertex_array)
    glUseProgram(resources.display_dir_program)
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, resources.display_dir_buffer)
    glDrawArrays(GL_LINE_STRIP, 0, RAY_DIR_COUNT)
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, 0)
    glUseProgram(0)
    glBindVertexArray(0)
Exemplo n.º 34
0
    def render_for_picking(self) -> None:
        """Render proxy objects for picking pass."""
        if not self.init():
            return

        proj = self.parent.projection_matrix
        view = self.parent.modelview_matrix

        glUseProgram(self.parent.shaders['solid'])
        glUniformMatrix4fv(0, 1, GL_FALSE, glm.value_ptr(proj))
        glUniformMatrix4fv(1, 1, GL_FALSE, glm.value_ptr(view))

        for mesh in self._meshes:
            glBindVertexArray(mesh.vao)
            glUniform1i(2, MAX_ID - mesh.object_id)
            glDrawElements(GL_TRIANGLES, mesh.count, GL_UNSIGNED_INT,
                           ctypes.c_void_p(0))

        glBindVertexArray(0)
        glUseProgram(0)

        glBindVertexArray(0)
        glUseProgram(0)
Exemplo n.º 35
0
def main():
    pg.init()
    display = (1680, 1050)
    pg.display.set_mode(display, DOUBLEBUF|OPENGL)

    # If everything went well the following calls
    # will display the version of opengl being used
    print('Vendor: %s' % (glGetString(GL_VENDOR)))
    print('Opengl version: %s' % (glGetString(GL_VERSION)))
    print('GLSL Version: %s' % (glGetString(GL_SHADING_LANGUAGE_VERSION)))
    print('Renderer: %s' % (glGetString(GL_RENDERER)))

    glClearColor(0.95, 1.0, 0.95, 0)

    # Lets compile our shaders since the use of shaders is now
    # mandatory. We need at least a vertex and fragment shader
    # begore we can draw anything
    program = ShaderProgram(fragment=fragment, vertex=vertex)

    # Lets create a VAO and bind it
    # Think of VAO's as object that encapsulate buffer state
    # Using a VAO enables you to cut down on calls in your draw
    # loop which generally makes things run faster
    vao_id = glGenVertexArrays(1)
    glBindVertexArray(vao_id)

    # Lets create our Vertex Buffer objects - these are the buffers
    # that will contain our per vertex data
    vbo_id = glGenBuffers(2)

    # Bind a buffer before we can use it
    glBindBuffer(GL_ARRAY_BUFFER, vbo_id[0])

    # Now go ahead and fill this bound buffer with some data
    glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vertex_data), vertex_data, GL_STATIC_DRAW)

    # Now specify how the shader program will be receiving this data
    # In this case the data from this buffer will be available in the shader as the vin_position vertex attribute
    glVertexAttribPointer(program.attribute_location('vin_position'), 3, GL_FLOAT, GL_FALSE, 0, None)

    # Turn on this vertex attribute in the shader
    glEnableVertexAttribArray(0)

    # Now do the same for the other vertex buffer
    glBindBuffer(GL_ARRAY_BUFFER, vbo_id[1])
    glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(color_data), color_data, GL_STATIC_DRAW)
    glVertexAttribPointer(program.attribute_location('vin_color'), 3, GL_FLOAT, GL_FALSE, 0, None)
    glEnableVertexAttribArray(1)

    # Lets unbind our vbo and vao state
    # We will bind these again in the draw loop
    glBindBuffer(GL_ARRAY_BUFFER, 0)
    glBindVertexArray(0)


    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                pg.quit()
                quit()

        glClear(GL_COLOR_BUFFER_BIT)

        # Specify shader to be used
        glUseProgram(program.program_id)

        # Bind VAO - this will automatically
        # bind all the vbo's saving us a bunch
        # of calls
        glBindVertexArray(vao_id)

        # Modern GL makes the draw call really simple
        # All the complexity has been pushed elsewhere
        glDrawArrays(GL_TRIANGLES, 0, 3)

        # Lets unbind the shader and vertex array state
        glUseProgram(0)
        glBindVertexArray(0)

        # Now lets show our master piece on the screen
        pg.display.flip()
        pg.time.wait(10)
Exemplo n.º 36
0
 def use_shaders(self):
     """Switch shaders on."""
     glUseProgram(self.__program)
     glBindVertexArray(self.__vao_id)
Exemplo n.º 37
0
 def draw(self):
     self.setup_shader()
     self.draw_vertices()
     glUseProgram(0)
Exemplo n.º 38
0
    def reset(self):
        glUseProgram(0)
        glDisableVertexAttribArray(self.vertIndex)

        glBindVertexArray(0)
Exemplo n.º 39
0
    def reset(self):
        glUseProgram(0)
        glDisableVertexAttribArray(self.vertIndex)

        glBindVertexArray(0)
Exemplo n.º 40
0
 def use_program(self):
     from OpenGL.GL import glUseProgram
     glUseProgram(self._gl_handle)
     yield
     glUseProgram(0)
Exemplo n.º 41
0
 def stop(self):
     '''Stop using the shader'''
     glUseProgram(0)
Exemplo n.º 42
0
 def use(self):
     '''Use the shader'''
     glUseProgram(self.program)
Exemplo n.º 43
0
	def usar(self):
		"""Utilizar este programa."""
		glUseProgram(self.programa)
Exemplo n.º 44
0
def no_usar_shaders():
	"""Deja de utilizar cualquier shader."""
	glUseProgram(0)
		
Exemplo n.º 45
0
 def use(self):
     glUseProgram(self.__programId)
	def useProgram(self):
		glUseProgram(self.program_id)
Exemplo n.º 47
0
    glVertexAttribPointer(program.attribute_location('vin_color'),
        3, GL_FLOAT, GL_FALSE, 0, None)
    glEnableVertexAttribArray(1)

    # Lets unbind our vbo and vao state
    # We will bind these again in the draw loop
    glBindBuffer(GL_ARRAY_BUFFER, 0)
    glBindVertexArray(0)

    running = True

    while running:
        glClear(GL_COLOR_BUFFER_BIT)

        # Specify shader to be used
        glUseProgram(program.program_id)

        # Bind VAO - this will automatically
        # bind all the vbo's saving us a bunch
        # of calls
        glBindVertexArray(vao_id)

        # Modern GL makes the draw call really simple
        # All the complexity has been pushed elsewhere
        glDrawArrays(GL_TRIANGLES, 0, 3)

        # Lets unbind the shader and vertex array state
        glUseProgram(0)
        glBindVertexArray(0)

        # Now lets show our master piece on the screen
Exemplo n.º 48
0
 def _finishFBOrender():
     glUseProgram(0)
Exemplo n.º 49
0
 def unuseProgram(self):
     glUseProgram(0)
Exemplo n.º 50
0
 def use(self):
     glUseProgram(self.program)
Exemplo n.º 51
0
 def enable(self):
     glUseProgram(self.program)
Exemplo n.º 52
0
 def disable(self):
     glUseProgram(0)
Exemplo n.º 53
0
 def bind(self):
     glUseProgram(self._hnd)
     try:
         yield
     finally:
         pass#glUseProgram(0)
Exemplo n.º 54
0
 def setup_shader(self):
     glUseProgram(self.shader)
     # Setup the uniforms
     set_uniform(self.shader, "mvproj", "mat4fv", self.viewer.mvproj)
     set_uniform(self.shader, "lightDir", "3f", self.viewer.ldir)
     set_uniform(self.shader, "camera", "3f", self.viewer.camera.position)
Exemplo n.º 55
0
 def clear(self):
     """Unbind all bound entities and clear cache."""
     self.__attributes = []
     glUseProgram(0)
     glBindVertexArray(0)