Esempio n. 1
0
    def _set_points(self, points, kind, tris):
        """Helper to set fill and line points"""
        from pyglet import gl

        if points is None:
            self._counts[kind] = 0
        points = np.asarray(points, dtype=np.float32, order='C')
        assert points.ndim == 2 and points.shape[1] == 2
        array_count = points.size // 2 if kind == 'line' else points.size
        if kind == 'fill':
            assert tris is not None
            tris = np.asarray(tris, dtype=np.uint32, order='C')
            assert tris.ndim == 1 and tris.size % 3 == 0
            tris.shape = (-1, 3)
            assert (tris < len(points)).all()
            self._tris[kind] = tris
            del tris
        self._points[kind] = points
        del points

        gl.glUseProgram(self._program)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self._buffers[kind]['array'])
        gl.glBufferData(gl.GL_ARRAY_BUFFER, self._points[kind].size * 4,
                        self._points[kind].tostring(), gl.GL_STATIC_DRAW)
        if kind == 'line':
            self._counts[kind] = array_count
        if kind == 'fill':
            self._counts[kind] = self._tris[kind].size
            gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER,
                            self._buffers[kind]['index'])
            gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER,
                            self._tris[kind].size * 4,
                            self._tris[kind].tostring(), gl.GL_STATIC_DRAW)
        gl.glUseProgram(0)
Esempio n. 2
0
 def draw(self):
     """Draw the object to the display buffer"""
     from pyglet import gl
     gl.glUseProgram(self._program)
     for kind in ('fill', 'line'):
         if self._counts[kind] > 0:
             if kind == 'line':
                 if self._line_width <= 0.0:
                     continue
                 gl.glLineWidth(self._line_width)
                 if self._line_loop:
                     mode = gl.GL_LINE_LOOP
                 else:
                     mode = gl.GL_LINE_STRIP
                 cmd = partial(gl.glDrawArrays, mode, 0, self._counts[kind])
             else:
                 gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER,
                                 self._buffers[kind]['index'])
                 cmd = partial(gl.glDrawElements, gl.GL_TRIANGLES,
                               self._counts[kind], gl.GL_UNSIGNED_INT, 0)
             gl.glBindBuffer(gl.GL_ARRAY_BUFFER,
                             self._buffers[kind]['array'])
             loc_pos = gl.glGetAttribLocation(self._program, b'a_position')
             gl.glEnableVertexAttribArray(loc_pos)
             gl.glVertexAttribPointer(loc_pos, 2, gl.GL_FLOAT, gl.GL_FALSE,
                                      0, 0)
             loc_col = gl.glGetUniformLocation(self._program, b'u_color')
             gl.glUniform4f(loc_col, *self._colors[kind])
             cmd()
             # The following line is probably only necessary because
             # Pyglet makes some assumptions about the GL state that
             # it perhaps shouldn't. Without it, Text might not
             # render properly (see #252)
             gl.glDisableVertexAttribArray(loc_pos)
     gl.glUseProgram(0)
Esempio n. 3
0
def copy_texture_to_screen():
    # select the target to draw into
    gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0)
    gl.glViewport(0, 0, window.width, window.height)

    # clear the destination
    gl.glClearColor(0.4, 0.4, 0.4, 1.0)
    gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

    # select the program for drawing
    gl.glUseProgram(copy_program)

    # send the vertex data
    data = (TEXTURE_VERTEX * 8)(((-0.9, -0.9), (0.0, 0.0)),
                                ((0.5, -0.9), (1.0, 0.0)),
                                ((0.5, 0.5), (1.0, 1.0)),
                                ((-0.9, 0.5), (0.0, 1.0)),

                                ((0.6, 0.6), (0.0, 1.0)),
                                ((1.0, 0.6), (1.0, 1.0)),
                                ((1.0, 1.0), (1.0, 0.0)),
                                ((0.6, 1.0), (0.0, 0.0)),
                                )

    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, copy_vertexbuffer)
    gl.glBufferData(gl.GL_ARRAY_BUFFER, ctypes.sizeof(data), data, gl.GL_DYNAMIC_DRAW)


    # draw
    gl.glBindVertexArray(copy_vao)
    gl.glDrawArrays(gl.GL_QUADS, 0, 8)
    gl.glBindVertexArray(0)
Esempio n. 4
0
 def draw(self):
     """Draw the object to the display buffer"""
     from pyglet import gl
     gl.glUseProgram(self._program)
     for kind in ('fill', 'line'):
         if self._counts[kind] > 0:
             if kind == 'line':
                 if self._line_width <= 0.0:
                     continue
                 gl.glLineWidth(self._line_width)
                 if self._line_loop:
                     mode = gl.GL_LINE_LOOP
                 else:
                     mode = gl.GL_LINE_STRIP
                 cmd = partial(gl.glDrawArrays, mode, 0, self._counts[kind])
             else:
                 gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER,
                                 self._buffers[kind]['index'])
                 cmd = partial(gl.glDrawElements, gl.GL_TRIANGLES,
                               self._counts[kind], gl.GL_UNSIGNED_INT, 0)
             gl.glBindBuffer(gl.GL_ARRAY_BUFFER,
                             self._buffers[kind]['array'])
             loc_pos = gl.glGetAttribLocation(self._program, b'a_position')
             gl.glEnableVertexAttribArray(loc_pos)
             gl.glVertexAttribPointer(loc_pos, 2, gl.GL_FLOAT, gl.GL_FALSE,
                                      0, 0)
             loc_col = gl.glGetUniformLocation(self._program, b'u_color')
             gl.glUniform4f(loc_col, *self._colors[kind])
             cmd()
             # The following line is probably only necessary because
             # Pyglet makes some assumptions about the GL state that
             # it perhaps shouldn't. Without it, Text might not
             # render properly (see #252)
             gl.glDisableVertexAttribArray(loc_pos)
     gl.glUseProgram(0)
Esempio n. 5
0
    def draw(self, uniforms, entities, models, *args, **kwargs):
        glUseProgram(self)

        glUniformMatrix4fv(
            self.uniforms[b'perspective'], 1, GL_TRUE, uniforms.get(b'perspective').ctypes.data_as(POINTER(GLfloat))
        )
        glUniformMatrix4fv(
            self.uniforms[b'view'], 1, GL_TRUE, uniforms.get(b'view').ctypes.data_as(POINTER(GLfloat))
        )

        for model_index, entity_list in entities.items():
            model = models[model_index]

            model.enable()

            for entity in entity_list:
                glUniformMatrix4fv(
                    self.uniforms[b'transformation'], 1, GL_TRUE,
                    entity.get_transformation_matrix().ctypes.data_as(POINTER(GLfloat))
                )
                glUniform3f(self.uniforms[b'color'], *entity.color)

                model.draw()

        glBindBuffer(GL_ARRAY_BUFFER, 0)
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)

        glBindTexture(GL_TEXTURE_2D, 0)


        glDisableVertexAttribArray(0)
Esempio n. 6
0
def render_to_texture():
    # select the target to draw into
    gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, framebuffer)
    draw_buffers = (gl.GLenum * 1)(gl.GL_COLOR_ATTACHMENT0)
    gl.glDrawBuffers(1, draw_buffers)
    gl.glViewport(0, 0, FB_WIDTH, FB_HEIGHT)

    # clear the destination
    gl.glClearColor(0.5, 0.6, 0.7, 1.0)
    gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

    # prepare the rendering
    gl.glUseProgram(render_program)

    # send the vertex data
    data = (COLOR_VERTEX * 3)(((-0.6, -0.5), (1.0, 0.0, 0.0, 1.0)),
                      ((0.6, -0.5), (0.0, 1.0, 0.0, 1.0)),
                      ((0.0, 0.5), (0.0, 0.0, 1.0, 1.0)))

    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, render_vertexbuffer)
    gl.glBufferData(gl.GL_ARRAY_BUFFER, ctypes.sizeof(data), data, gl.GL_DYNAMIC_DRAW)

    # draw using the vertex array for vertex information
    gl.glBindVertexArray(render_vao)
    gl.glDrawArrays(gl.GL_TRIANGLES, 0, 3)
    gl.glBindVertexArray(0)
Esempio n. 7
0
def setup_program():
    '''
    Create the glsl program
    '''
    vertex_shader = b'''
        attribute vec2 position;
        attribute vec4 color;
        
        varying vec4 var_color;
        void main()
        {
            gl_Position = vec4(position, 0.0, 1.0);
            var_color = color;
        }
    '''

    fragment_shader = b'''
        varying vec4 var_color;
        void main()
        {
            gl_FragColor = var_color;
        }
    '''

    program = gl.glCreateProgram()
    gl.glAttachShader(program, shader(gl.GL_VERTEX_SHADER, vertex_shader))
    gl.glAttachShader(program, shader(gl.GL_FRAGMENT_SHADER, fragment_shader))
    gl.glLinkProgram(program)
    gl.glUseProgram(program)
    return program
Esempio n. 8
0
    def unuse(self):
        """P.unuse()

        Disable the program for rendering.
        """

        gl.glUseProgram(0)
Esempio n. 9
0
def copy_texture_to_screen():
    # select the target to draw into
    gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0)
    gl.glViewport(0, 0, window.width, window.height)

    # clear the destination
    gl.glClearColor(0.4, 0.4, 0.4, 1.0)
    gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

    # select the program for drawing
    gl.glUseProgram(copy_program)

    # send the vertex data
    data = (TEXTURE_VERTEX * 8)(
        ((-0.9, -0.9), (0.0, 0.0)),
        ((0.5, -0.9), (1.0, 0.0)),
        ((0.5, 0.5), (1.0, 1.0)),
        ((-0.9, 0.5), (0.0, 1.0)),
        ((0.6, 0.6), (0.0, 1.0)),
        ((1.0, 0.6), (1.0, 1.0)),
        ((1.0, 1.0), (1.0, 0.0)),
        ((0.6, 1.0), (0.0, 0.0)),
    )

    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, copy_vertexbuffer)
    gl.glBufferData(gl.GL_ARRAY_BUFFER, ctypes.sizeof(data), data,
                    gl.GL_DYNAMIC_DRAW)

    # draw
    gl.glBindVertexArray(copy_vao)
    gl.glDrawArrays(gl.GL_QUADS, 0, 8)
    gl.glBindVertexArray(0)
Esempio n. 10
0
    def use(self):
        """P.use()

        Enables the program for rendering.
        """

        gl.glUseProgram(self.__program)
Esempio n. 11
0
 def render(self):
     gl.glUseProgram(self.programA)
     for i in range(args["resolution"]):
         gl.glUniform1i(self.slice_pos, i)
         gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.framebufferA0[i])
         gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
         gl.glDrawArrays(gl.GL_TRIANGLES, 0, 6)
Esempio n. 12
0
def render_to_texture():
    # select the target to draw into
    gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, framebuffer)
    draw_buffers = (gl.GLenum * 1)(gl.GL_COLOR_ATTACHMENT0)
    gl.glDrawBuffers(1, draw_buffers)
    gl.glViewport(0, 0, FB_WIDTH, FB_HEIGHT)

    # clear the destination
    gl.glClearColor(0.5, 0.6, 0.7, 1.0)
    gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

    # prepare the rendering
    gl.glUseProgram(render_program)

    # send the vertex data
    data = (COLOR_VERTEX * 3)(((-0.6, -0.5), (1.0, 0.0, 0.0, 1.0)),
                              ((0.6, -0.5), (0.0, 1.0, 0.0, 1.0)),
                              ((0.0, 0.5), (0.0, 0.0, 1.0, 1.0)))

    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, render_vertexbuffer)
    gl.glBufferData(gl.GL_ARRAY_BUFFER, ctypes.sizeof(data), data,
                    gl.GL_DYNAMIC_DRAW)

    # draw using the vertex array for vertex information
    gl.glBindVertexArray(render_vao)
    gl.glDrawArrays(gl.GL_TRIANGLES, 0, 3)
    gl.glBindVertexArray(0)
Esempio n. 13
0
    def draw(self, uniforms, text, quad, textures=(), *args, **kwargs):
        glUseProgram(self)
        glDisable(GL_DEPTH_TEST)


        quad.enable()

        glUniform3f(self.uniforms[b'color'], 0.3, 0.3, 0.5)

        glUniformMatrix3fv(
            self.uniforms[b'transformation'], 1, GL_TRUE,
            text.get_transformation_matrix_2D().ctypes.data_as(POINTER(GLfloat))
        )

        textures.enable(slot=0)
        glUniform1i(self.uniforms[b'font_atlas'], 0)

        quad.draw()

        glBindBuffer(GL_ARRAY_BUFFER, 0)
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)

        glBindTexture(GL_TEXTURE_2D, 0)

        glDisableVertexAttribArray(0)

        glEnable(GL_DEPTH_TEST)
Esempio n. 14
0
    def draw(self, uniforms, entities, models, textures=(), lights=(), *args, **kwargs):
        glUseProgram(self)

        # PREPARE SHADER
        glUniformMatrix4fv(  # ctypes.data_as must be here and not at initialization.
            self.uniforms[b'perspective'], 1, GL_TRUE, uniforms.get(b'perspective').ctypes.data_as(POINTER(GLfloat))
        )
        glUniformMatrix4fv(
            self.uniforms[b'view'], 1, GL_TRUE, uniforms.get(b'view').ctypes.data_as(POINTER(GLfloat))
        )

        for i, entity in enumerate(lights):
            glUniform3f(self.uniforms[b'light[' + bytes(str(i), 'utf-8') + b'].position'],  *entity.location)
            glUniform3f(self.uniforms[b'light[' + bytes(str(i), 'utf-8') + b'].color'],     *entity.color)
            glUniform1f(self.uniforms[b'light[' + bytes(str(i), 'utf-8') + b'].constant'],  entity.attenuation[0])
            glUniform1f(self.uniforms[b'light[' + bytes(str(i), 'utf-8') + b'].linear'],    entity.attenuation[1])
            glUniform1f(self.uniforms[b'light[' + bytes(str(i), 'utf-8') + b'].quadratic'], entity.attenuation[1])


        # PREPARE MODELS
        for model_index, texture_mapping in self.entities.items():

            model = models[model_index]
            model.enable()

            # PREPARE TEXTURES
            glActiveTexture(GL_TEXTURE0)
            glActiveTexture(GL_TEXTURE0 + 1)
            for texture_list, entity_list in texture_mapping.items():

                if hasattr(texture_list, '__iter__'):
                    glBindTexture(GL_TEXTURE_2D, textures[0])
                    glUniform1i(self.uniforms[b'diffuse_texture'], 0)
                    glBindTexture(GL_TEXTURE_2D, textures[1])
                    glUniform1i(self.uniforms[b'specular_texture'], 1)

                    # textures[0].enable(slot=0)
                    # textures[1].enable(slot=1)

                else:
                    textures[texture_list].enable(slot=0)
                    glUniform1i(self.uniforms[b'diffuse_texture'], 0)


                # PREPARE ENTITIES
                for entity in entity_list:
                    glUniformMatrix4fv(
                        self.uniforms[b'transformation'], 1, GL_TRUE,
                        entity.get_transformation_matrix().ctypes.data_as(POINTER(GLfloat))
                    )
                    model.draw()

        glBindBuffer(GL_ARRAY_BUFFER, 0)
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)

        glBindTexture(GL_TEXTURE_2D, 0)

        glDisableVertexAttribArray(0)
        glDisableVertexAttribArray(1)
        glDisableVertexAttribArray(2)
Esempio n. 15
0
 def render(self):
     gl.glUseProgram(self.programA)
     gl.glUniform1i(self.tex_pos_A, 0)
     for i in range(self.dimz):
         gl.glUniform1i(self.slice_pos_A, i)
         gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.framebufferA0[i])
         gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
         gl.glDrawArrays(gl.GL_TRIANGLES, 0, 6)
Esempio n. 16
0
    def __init__(self, ec, fill_color, line_color, line_width, line_loop):
        self._ec = ec
        self._line_width = line_width
        self._line_loop = line_loop  # whether or not lines drawn are looped

        # initialize program and shaders
        from pyglet import gl
        self._program = gl.glCreateProgram()

        vertex = gl.glCreateShader(gl.GL_VERTEX_SHADER)
        buf = create_string_buffer(tri_vert.encode('ASCII'))
        ptr = cast(pointer(pointer(buf)), POINTER(POINTER(c_char)))
        gl.glShaderSource(vertex, 1, ptr, None)
        gl.glCompileShader(vertex)
        _check_log(vertex, gl.glGetShaderInfoLog)

        fragment = gl.glCreateShader(gl.GL_FRAGMENT_SHADER)
        buf = create_string_buffer(tri_frag.encode('ASCII'))
        ptr = cast(pointer(pointer(buf)), POINTER(POINTER(c_char)))
        gl.glShaderSource(fragment, 1, ptr, None)
        gl.glCompileShader(fragment)
        _check_log(fragment, gl.glGetShaderInfoLog)

        gl.glAttachShader(self._program, vertex)
        gl.glAttachShader(self._program, fragment)
        gl.glLinkProgram(self._program)
        _check_log(self._program, gl.glGetProgramInfoLog)

        gl.glDetachShader(self._program, vertex)
        gl.glDetachShader(self._program, fragment)
        gl.glUseProgram(self._program)

        # Prepare buffers and bind attributes
        loc = gl.glGetUniformLocation(self._program, b'u_view')
        view = ec.window_size_pix
        view = np.diag([2. / view[0], 2. / view[1], 1., 1.])
        view[-1, :2] = -1
        view = view.astype(np.float32).ravel()
        gl.glUniformMatrix4fv(loc, 1, False, (c_float * 16)(*view))

        self._counts = dict()
        self._colors = dict()
        self._buffers = dict()
        self._points = dict()
        self._tris = dict()
        for kind in ('line', 'fill'):
            self._counts[kind] = 0
            self._colors[kind] = (0., 0., 0., 0.)
            self._buffers[kind] = dict(array=gl.GLuint())
            gl.glGenBuffers(1, pointer(self._buffers[kind]['array']))
        self._buffers['fill']['index'] = gl.GLuint()
        gl.glGenBuffers(1, pointer(self._buffers['fill']['index']))
        gl.glUseProgram(0)

        self.set_fill_color(fill_color)
        self.set_line_color(line_color)
Esempio n. 17
0
    def draw(self,
             uniforms,
             entity,
             models,
             textures=(),
             color=(1.0, 1.0, 1.0),
             *args,
             **kwargs):
        glUseProgram(self)
        glDisable(GL_DEPTH_TEST)

        # Draw objects once as invisible to set stencil values.
        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE,
                    GL_FALSE)  # Don't write any color values to color buffer.
        glStencilMask(0xFF)  # Enable writing.

        model = models[entity.model]

        model.positions.enable()
        model.indices.enable()

        self.uniforms[b'perspective'].load(
            uniforms.get(b'perspective').ctypes.data_as(POINTER(GLfloat)))
        self.uniforms[b'view'].load(
            uniforms.get(b'view').ctypes.data_as(POINTER(GLfloat)))
        self.uniforms[b'color'].load(*color)

        entity.get_transformation_matrix(
            location=self.uniforms[b'transformation'])

        model.draw()

        # Draw again with larger model.
        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE)

        glStencilFunc(GL_NOTEQUAL, 1,
                      0xFF)  # Update with 1's where the objects are rendered.
        glStencilMask(
            0x00
        )  # Value that AND's the value written to buffer. 0x00 basically disables writing to stencil.

        glUniformMatrix4fv(
            self.uniforms[b'transformation'], 1, GL_TRUE,
            create_transformation_matrix(
                *entity._location, *entity.rotation,
                *(entity.scale + 0.05)).ctypes.data_as(POINTER(GLfloat)))

        model.draw()

        glBindBuffer(GL_ARRAY_BUFFER, 0)
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)

        glDisableVertexAttribArray(0)

        glEnable(GL_DEPTH_TEST)
        glStencilMask(0xFF)
Esempio n. 18
0
    def __init__(self, ec, fill_color, line_color, line_width, line_loop):
        self._ec = ec
        self._line_width = line_width
        self._line_loop = line_loop  # whether or not lines drawn are looped

        # initialize program and shaders
        from pyglet import gl
        self._program = gl.glCreateProgram()

        vertex = gl.glCreateShader(gl.GL_VERTEX_SHADER)
        buf = create_string_buffer(tri_vert.encode('ASCII'))
        ptr = cast(pointer(pointer(buf)), POINTER(POINTER(c_char)))
        gl.glShaderSource(vertex, 1, ptr, None)
        gl.glCompileShader(vertex)
        _check_log(vertex, gl.glGetShaderInfoLog)

        fragment = gl.glCreateShader(gl.GL_FRAGMENT_SHADER)
        buf = create_string_buffer(tri_frag.encode('ASCII'))
        ptr = cast(pointer(pointer(buf)), POINTER(POINTER(c_char)))
        gl.glShaderSource(fragment, 1, ptr, None)
        gl.glCompileShader(fragment)
        _check_log(fragment, gl.glGetShaderInfoLog)

        gl.glAttachShader(self._program, vertex)
        gl.glAttachShader(self._program, fragment)
        gl.glLinkProgram(self._program)
        _check_log(self._program, gl.glGetProgramInfoLog)

        gl.glDetachShader(self._program, vertex)
        gl.glDetachShader(self._program, fragment)
        gl.glUseProgram(self._program)

        # Prepare buffers and bind attributes
        loc = gl.glGetUniformLocation(self._program, b'u_view')
        view = ec.window_size_pix
        view = np.diag([2. / view[0], 2. / view[1], 1., 1.])
        view[-1, :2] = -1
        view = view.astype(np.float32).ravel()
        gl.glUniformMatrix4fv(loc, 1, False, (c_float * 16)(*view))

        self._counts = dict()
        self._colors = dict()
        self._buffers = dict()
        self._points = dict()
        self._tris = dict()
        for kind in ('line', 'fill'):
            self._counts[kind] = 0
            self._colors[kind] = (0., 0., 0., 0.)
            self._buffers[kind] = dict(array=gl.GLuint())
            gl.glGenBuffers(1, pointer(self._buffers[kind]['array']))
        self._buffers['fill']['index'] = gl.GLuint()
        gl.glGenBuffers(1, pointer(self._buffers['fill']['index']))
        gl.glUseProgram(0)

        self.set_fill_color(fill_color)
        self.set_line_color(line_color)
Esempio n. 19
0
    def use(self):
        """Bind the program into the rendering pipeline.

        """
        if not self.linked:
            self._link()

        # bind the program
        gl.glUseProgram(self.handle)
        self.bound = True
Esempio n. 20
0
 def use(self):
     """
     Activates the shader.
     This is normally done for you automatically.
     """
     # IMPORTANT: This is the only place glUseProgram should be called
     #            so we can track active program.
     if self._ctx.active_program != self:
         gl.glUseProgram(self._glo)
         self._ctx.active_program = self
Esempio n. 21
0
    def init_ortho(self):
        # disable shaders
        gl.glUseProgram(0)
        gl.glDisable(gl.GL_LIGHTING)

        # store the projection matrix to restore later
        gl.glMatrixMode(gl.GL_PROJECTION)

        # load orthographic projection matrix
        gl.glLoadIdentity()
        gl.glOrtho(0, self.width, 0, self.height, -1, 500)

        # reset modelview
        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glLoadIdentity()
Esempio n. 22
0
    def use(self):
        self.id = gl.glCreateProgram()

        for shader in self.shaders:
            shader.compile()
            gl.glAttachShader(self.id, shader.id)

        gl.glLinkProgram(self.id)

        message = self._get_message()
        if not self.get_link_status():
            raise LinkError(message)

        gl.glUseProgram(self.id)
        return message
Esempio n. 23
0
    def use(self):
        self.id = gl.glCreateProgram()
        
        for shader in self.shaders:
            shader.compile()
            gl.glAttachShader(self.id, shader.id)

        gl.glLinkProgram(self.id)

        message = self._getMessage()
        if not self.getLinkStatus():
            raise LinkError(message)

        gl.glUseProgram(self.id)
        return message
Esempio n. 24
0
    def draw(self,
             uniforms,
             entities,
             models,
             textures=(),
             lights=(),
             *args,
             **kwargs):
        glUseProgram(self)

        # PREPARE SHADER
        self.uniforms[b'perspective'].load(
            uniforms.get(b'perspective').ctypes.data_as(POINTER(GLfloat)))
        self.uniforms[b'view'].load(
            uniforms.get(b'view').ctypes.data_as(POINTER(GLfloat)))

        for i, entity in enumerate(lights):
            self.uniforms[b'light[' + bytes(str(i), 'utf-8') +
                          b'].position'].load(*entity._location)
            self.uniforms[b'light[' + bytes(str(i), 'utf-8') +
                          b'].color'].load(*entity.color)
            self.uniforms[b'light[' + bytes(str(i), 'utf-8') +
                          b'].constant'].load(entity.attenuation[0])
            self.uniforms[b'light[' + bytes(str(i), 'utf-8') +
                          b'].linear'].load(entity.attenuation[1])
            self.uniforms[b'light[' + bytes(str(i), 'utf-8') +
                          b'].quadratic'].load(entity.attenuation[1])

        # PREPARE MODELS
        for model_index, texture_mapping in entities.items():

            model = models[model_index]
            model.enable()

            # PREPARE TEXTURES
            for texture_index, entity_list in texture_mapping.items():

                textures[texture_index].enable()

                # PREPARE ENTITIES
                for entity in entity_list:
                    entity.get_transformation_matrix(
                        self.uniforms[b'transformation'])
                    model.draw()
Esempio n. 25
0
def on_draw(dt):
    if slowmo:
        dt *= 1 / 3

    # Update graphical things
    for a in level.actors:
        a.update(dt)

    for w in Water.insts:
        w.update(dt)

    hud.update(dt)

    window.clear()

    with offscreen.bind_buffer() as fbuf:
        fbuf.clear(0.13, 0.1, 0.1)
        gl.glLoadIdentity()
        gl.glScalef(PIXEL_SCALE, PIXEL_SCALE, 1)
        level.background.draw()
        RockPoly.batch.draw()
        actor_sprites.draw()
        level.fg_batch.draw()

    mgl.screen.clear()
    offscreen.draw()

    mvp = Matrix44.orthogonal_projection(0,
                                         WIDTH * SPACE_SCALE,
                                         0,
                                         HEIGHT * SPACE_SCALE,
                                         -1,
                                         1,
                                         dtype='f4')

    with offscreen.bind_texture(location=0):
        water_batch.tex_uniform.value = 0
        water_batch.render(dt, mvp)
    gl.glUseProgram(0)
    gl.glBindVertexArray(0)

    hud.draw()
Esempio n. 26
0
    def draw_f3(self):
        """Draws the f3 debug screen. Current uses the fixed-function pipeline since pyglet labels uses it"""
        gl.glDisable(gl.GL_DEPTH_TEST)
        gl.glUseProgram(0)
        gl.glBindVertexArray(0)
        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glPushMatrix()
        gl.glLoadIdentity()

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

        self.f3.draw()

        gl.glPopMatrix()

        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glPopMatrix()
Esempio n. 27
0
    def draw(self, uniforms, text, quad, textures=(), *args, **kwargs):
        glUseProgram(self)
        glDisable(GL_DEPTH_TEST)

        quad.enable()

        self.uniforms[b'color'].load(0.3, 0.3, 0.5)

        text.get_transformation_matrix_2D(
            location=self.uniforms[b'transformation'])

        textures.enable()

        quad.draw()

        glBindBuffer(GL_ARRAY_BUFFER, 0)
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)

        glDisableVertexAttribArray(0)

        glEnable(GL_DEPTH_TEST)
Esempio n. 28
0
    def on_draw(self):
        self.init_perspective()
        # Redraw the scene
        gl.glClearColor(0.8, 0.8, 0.9, 0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

        self.camera.draw()
        self.setLights()

        self.drawGrid()

        # run shaders
        if self.default_shader:
            gl.glUseProgram(self.default_shader)

        for b in self.bodies:
            self.drawBody(b)

        self.init_ortho()
        self.help_label.draw()
        self.info_label.draw()
Esempio n. 29
0
  def __draw(self):
    gl.glClearColor(self.__bg_color[0],
        self.__bg_color[1],
        self.__bg_color[2],
        self.__bg_color[3])
    gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
    gl.glUseProgram(self.__prog.value)

    # update data buffer if necessary
    with self.__data_lock:
      if self.__data_altered:
        self.__setup_data_buffer()

    self.__set_uniforms()
    self.__set_attributes()

    gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE)
    gl.glEnable(gl.GL_BLEND)
    gl.glEnable(gl.GL_CULL_FACE)
    gl.glDrawArraysInstanced(gl.GL_TRIANGLES,
        0, 36, self.__data.size / (self.__downsample**3))
Esempio n. 30
0
 def _prepareFBOrender(self):
     if self.mode=='mono++':
         GL.glUseProgram(self._shaders['mono++'])
     elif self.mode=='color++':
         GL.glUseProgram(self._shaders['color++'])
     else:
         GL.glUseProgram(self.win._progFBOtoFrame)
Esempio n. 31
0
 def _prepareFBOrender(self):
     if self.mode == 'mono++':
         GL.glUseProgram(self._shaders['mono++'])
     elif self.mode == 'color++':
         GL.glUseProgram(self._shaders['color++'])
     else:
         GL.glUseProgram(self.win._progFBOtoFrame)
Esempio n. 32
0
def on_draw():
    global time
    time += 0.01
    game_window.clear()
    ctx.screen.use()

    trans = matrix44.create_from_translation(
        (math.cos(time), math.sin(time / 5) * 5 - 6, 0))
    rot = matrix44.create_from_y_rotation(math.pi / 2)
    mat = matrix44.multiply(trans, rot)

    ctx.enable(moderngl.DEPTH_TEST | moderngl.CULL_FACE)
    scene.draw(
        projection_matrix=projection,
        camera_matrix=mat,
    )

    fbo.use()
    fbo.clear()

    gl.glUseProgram(0)
    gl.glBindVertexArray(0)

    main_batch.draw()
    counter.draw()

    trans = matrix44.create_from_translation([0, 0, -1])
    rot = matrix44.create_from_axis_rotation(
        [math.sin(time) / 4,
         math.cos(time) / 4,
         math.sin(time) / 20],
        math.sin(time) / 5)
    mat = matrix44.multiply(trans, rot)

    ctx.screen.use()
    fbo.color_attachments[0].use(location=0)
    texture_program['scale'].value = (800 / window_x, 600 / window_y)
    texture_program['m_proj'].write(projection)
    texture_program['m_view'].write(mat.astype('f4').tobytes())
    quad.render(texture_program)
Esempio n. 33
0
 def _prepareFBOrender(self):
     if self.mode == "mono++":
         GL.glUseProgram(self._shaders["mono++"])
     elif self.mode == "color++":
         GL.glUseProgram(self._shaders["color++"])
     else:
         GL.glUseProgram(self.win._progFBOtoFrame)
Esempio n. 34
0
def render_to_texture(in_size, out_size, view_z=None):
    z0, z1 = (0, in_size[2]) if view_z == None else view_z
    vertices = (VERTEX * 6)(((-1, -1), (0, 0)), ((1, -1), (1, 0)),
                            ((1, 1), (1, 1)), ((1, 1), (1, 1)),
                            ((-1, 1), (0, 1)), ((-1, -1), (0, 0)))
    gl.glBindTexture(gl.GL_TEXTURE_3D, rendered_texture)
    gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, framebuffer)
    draw_buffers = (gl.GLenum * 1)(gl.GL_COLOR_ATTACHMENT0)
    gl.glDrawBuffers(1, draw_buffers)
    gl.glViewport(0, 0, out_size[0], out_size[1])
    gl.glUseProgram(render_program)
    loc_depth = gl.glGetUniformLocation(render_program,
                                        ctypes.create_string_buffer(b'depth'))
    loc_texelSize = gl.glGetUniformLocation(
        render_program, ctypes.create_string_buffer(b'texelSize'))
    gl.glUniform3f(loc_texelSize, 1 / in_size[0], 1 / in_size[1],
                   1 / in_size[2])
    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, render_vertexbuffer)
    gl.glBufferData(gl.GL_ARRAY_BUFFER, ctypes.sizeof(vertices), vertices,
                    gl.GL_DYNAMIC_DRAW)
    gl.glBindVertexArray(render_vao)
    gl.glClearColor(0.0, 0.0, 0.0, 0.0)
    for z in range(out_size[2]):
        gl.glFramebufferTexture3D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0,
                                  gl.GL_TEXTURE_3D, rendered_texture, 0, z)
        fbs = gl.glCheckFramebufferStatus(gl.GL_FRAMEBUFFER)
        assert fbs == gl.GL_FRAMEBUFFER_COMPLETE, 'FramebufferStatus is {}'.format(
            fbs)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
        gl.glUniform1f(loc_depth,
                       (z0 + z * (z1 - z0)) / in_size[2] / out_size[2])
        gl.glBindTexture(gl.GL_TEXTURE_3D, input_texture)
        gl.glDrawArrays(gl.GL_TRIANGLES, 0, 6)
        if z % 10 == 0:
            gl.glFinish()
            print('\033[K{}/{}'.format(z, out_size[2] - 1), end='\r')
    gl.glFinish()

    gl.glBindVertexArray(0)
Esempio n. 35
0
    def _set_points(self, points, kind, tris):
        """Helper to set fill and line points"""
        from pyglet import gl

        if points is None:
            self._counts[kind] = 0
        points = np.asarray(points, dtype=np.float32, order='C')
        assert points.ndim == 2 and points.shape[1] == 2
        array_count = points.size // 2 if kind == 'line' else points.size
        if kind == 'fill':
            assert tris is not None
            tris = np.asarray(tris, dtype=np.uint32, order='C')
            assert tris.ndim == 1 and tris.size % 3 == 0
            tris.shape = (-1, 3)
            assert (tris < len(points)).all()
            self._tris[kind] = tris
            del tris
        self._points[kind] = points
        del points

        gl.glUseProgram(self._program)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self._buffers[kind]['array'])
        gl.glBufferData(gl.GL_ARRAY_BUFFER, self._points[kind].size * 4,
                        self._points[kind].tostring(),
                        gl.GL_STATIC_DRAW)
        if kind == 'line':
            self._counts[kind] = array_count
        if kind == 'fill':
            self._counts[kind] = self._tris[kind].size
            gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER,
                            self._buffers[kind]['index'])
            gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER,
                            self._tris[kind].size * 4,
                            self._tris[kind].tostring(),
                            gl.GL_STATIC_DRAW)
        gl.glUseProgram(0)
Esempio n. 36
0
        def render(self):
            gl.glUseProgram(self.programA)
            gl.glUniform1i(self.tex_pos_A_A, 1)
            gl.glUniform1i(self.tex_pos_A_B, 3)
            gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.framebufferA0)

            gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

            gl.glDrawArrays(gl.GL_TRIANGLES, 0, 6)
            gl.glUseProgram(self.programB)

            gl.glUniform1i(self.tex_pos_B_A, 1)
            gl.glUniform1i(self.tex_pos_B_B, 3)
            gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.framebufferB0)

            gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

            gl.glDrawArrays(gl.GL_TRIANGLES, 0, 6)

            gl.glUseProgram(self.programA)
            gl.glUniform1i(self.tex_pos_A_A, 0)
            gl.glUniform1i(self.tex_pos_A_B, 2)
            gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.framebufferA1)

            gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

            gl.glDrawArrays(gl.GL_TRIANGLES, 0, 6)

            gl.glUseProgram(self.programB)
            gl.glUniform1i(self.tex_pos_B_A, 0)
            gl.glUniform1i(self.tex_pos_B_B, 2)
            gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.framebufferB1)

            gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

            gl.glDrawArrays(gl.GL_TRIANGLES, 0, 6)
Esempio n. 37
0
 def _finishFBOrender(self):
     if self.mode[:4] in ['mono','colo']:
         GL.glUseProgram(0)
     elif self.mode[:4]=='bits':
         self._drawLUTtoScreen()
Esempio n. 38
0
 def use(self):
     gl.glUseProgram(self.handle)
Esempio n. 39
0
 def _prepareFBOrender(self):
     if self.mode=='mono++':
         GL.glUseProgram(self._shaders['mono++'])
     if self.mode=='color++':
         GL.glUseProgram(self._shaders['color++'])
Esempio n. 40
0
 def end(self):
     gl.glUseProgram(0)
Esempio n. 41
0
 def begin(self):
     gl.glUseProgram(self.program_no)
Esempio n. 42
0
File: shader.py Progetto: Knio/miru
def disableShaders():
    """Disable shader programs.  Equivalent to gl.glUseProgram(0)
    """
    gl.glUseProgram(0)
Esempio n. 43
0
 def _finishFBOrender(self):
     GL.glUseProgram(0)
Esempio n. 44
0
 def use(self):
     return gl.glUseProgram(self.id)
Esempio n. 45
0
 def bind(self):
     ''' Bind the program, i.e. use it. '''
     gl.glUseProgram(self.handle)
Esempio n. 46
0
 def use(self):
     return gl.glUseProgram(self.id)
Esempio n. 47
0
 def stop(self):
     gl.glUseProgram(0)
Esempio n. 48
0
 def use(self):
     " Use the shader program "
     glUseProgram(self.pid)
Esempio n. 49
0
 def unbind(self):
     gl.glUseProgram(0)
Esempio n. 50
0
 def bind(self):
     gl.glUseProgram(self.program)
Esempio n. 51
0
        def __init__(self, frames):
            #consider bumping opengl version if apple supports it
            #amdgpu-mesa currently supports up to 4.5
            super(ControledRender,
                  self).__init__(512,
                                 512,
                                 fullscreen=False,
                                 config=gl.Config(major_version=4,
                                                  minor_version=1),
                                 visible=False)
            print(self.context.get_info().get_version())

            self.frames = frames
            self.vertex_buffer = gl.GLuint(0)
            self.vao = gl.GLuint(0)
            #self.prev_program = (gl.GLint * 1)()

            self.dimx = args["A"].shape[0]
            self.dimy = args["A"].shape[1]

            A = args["A"].astype(np.float32)
            #print("A shape " + str(A.shape))
            #print(str(A.dtype))
            #print(A)

            B = args["B"].astype(np.float32)

            #self.dp = self.tdata.ctypes.data_as(ctypes.POINTER(ctypes.c_void_p))
            self.Ap = A.ctypes.data_as(ctypes.POINTER(ctypes.c_void_p))
            self.Bp = B.ctypes.data_as(ctypes.POINTER(ctypes.c_void_p))

            self.setupFBOandTextures()

            self.setupShaders()

            data = [
                -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0,
                1.0
            ]

            dataGl = (gl.GLfloat * len(data))(*data)

            gl.glGenBuffers(1, ctypes.byref(self.vertex_buffer))
            gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertex_buffer)
            gl.glBufferData(gl.GL_ARRAY_BUFFER,
                            len(dataGl) * 4, dataGl, gl.GL_STATIC_DRAW)

            gl.glGenVertexArrays(1, ctypes.byref(self.vao))
            gl.glBindVertexArray(self.vao)
            gl.glUseProgram(self.programA)
            self.pos_posA = gl.glGetAttribLocation(
                self.programA, ctypes.create_string_buffer(b"a_position"))
            assert (self.pos_posA >= 0)
            gl.glEnableVertexAttribArray(self.pos_posA)
            gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertex_buffer)
            gl.glVertexAttribPointer(self.pos_posA, 2, gl.GL_FLOAT, False, 0,
                                     0)

            self.tex_pos_A_A = gl.glGetUniformLocation(self.programA, b"A")
            self.tex_pos_A_B = gl.glGetUniformLocation(self.programA, b"B")
            self.feed_pos_A = gl.glGetUniformLocation(self.programA, b"f")
            self.kill_pos_A = gl.glGetUniformLocation(self.programA, b"k")
            self.dA_pos_A = gl.glGetUniformLocation(self.programA, b"dA")
            self.dB_pos_A = gl.glGetUniformLocation(self.programA, b"dB")
            self.dt_pos_A = gl.glGetUniformLocation(self.programA, b"timestep")
            self.step_pos_A = gl.glGetUniformLocation(self.programA, b"step")
            gl.glUniform1f(self.feed_pos_A, args["feed"])
            gl.glUniform1f(self.kill_pos_A, args["kill"])
            gl.glUniform1f(self.dA_pos_A, args["dA"])
            gl.glUniform1f(self.dB_pos_A, args["dB"])
            gl.glUniform1f(self.dt_pos_A, args["dt"])
            #may need changed for nonsquare textures
            gl.glUniform1f(self.step_pos_A, 1 / self.dimx)

            gl.glUseProgram(self.programB)
            self.pos_posB = gl.glGetAttribLocation(
                self.programB, ctypes.create_string_buffer(b"a_position"))
            assert (self.pos_posB >= 0)
            gl.glEnableVertexAttribArray(self.pos_posB)
            gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertex_buffer)
            gl.glVertexAttribPointer(self.pos_posB, 2, gl.GL_FLOAT, False, 0,
                                     0)

            self.tex_pos_B_A = gl.glGetUniformLocation(self.programB, b"A")
            self.tex_pos_B_B = gl.glGetUniformLocation(self.programB, b"B")
            self.feed_pos_B = gl.glGetUniformLocation(self.programB, b"f")
            self.kill_pos_B = gl.glGetUniformLocation(self.programB, b"k")
            self.dA_pos_B = gl.glGetUniformLocation(self.programB, b"dA")
            self.dB_pos_B = gl.glGetUniformLocation(self.programB, b"dB")
            self.dt_pos_B = gl.glGetUniformLocation(self.programB, b"timestep")
            self.step_pos_B = gl.glGetUniformLocation(self.programB, b"step")
            gl.glUniform1f(self.feed_pos_B, args["feed"])
            gl.glUniform1f(self.kill_pos_B, args["kill"])
            gl.glUniform1f(self.dA_pos_B, args["dA"])
            gl.glUniform1f(self.dB_pos_B, args["dB"])
            gl.glUniform1f(self.dt_pos_B, args["dt"])
            #may need changed for nonsquare textures
            gl.glUniform1f(self.step_pos_B, 1 / self.dimx)

            gl.glViewport(0, 0, self.dimx, self.dimy)
Esempio n. 52
0
 def use(self):
     gl.glUseProgram(self.program)
Esempio n. 53
0
def main(level_file):
    clock = events.dispatcher('Clock')
    keyboard = events.dispatcher('Keyboard')
    pygame.init()
    pygame.display.gl_set_attribute(pygame.GL_ALPHA_SIZE, 8)

    pygame.display.set_mode((1000, 600), pygame.OPENGL | pygame.DOUBLEBUF | pygame.RESIZABLE)
    handle_resize(1000, 600)
    screen_center = (500, 300)
    camera_offset = 230
    gl.glEnable(gl.GL_TEXTURE_2D)

    gl.glEnable(gl.GL_BLEND)
    gl.glBlendEquation(gl.GL_FUNC_ADD)
    gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
    gl.glClearColor(0, 0, 0, 1)

    tick_event = pygame.event.Event(constants.TICK)
    datadir = find_datadir()
    loader = pyglet.resource.Loader(datadir)

    player1 = viking(datadir, clock, keyboard,
                     pygame.K_a, pygame.K_d, pygame.K_w, pygame.K_j)
    player2 = viking(datadir, clock, keyboard,
                     pygame.K_LEFT, pygame.K_RIGHT, pygame.K_UP, pygame.K_RETURN)
    player2.location[0] = 900

    entities = [player1, player2]
    scream = pygame.mixer.Sound(os.path.join(datadir, 'wilhelm.wav'))
    background = load_sprite(datadir, 'background')
    backgroundbuf = GLBuffer(4 * 4, numpy.float32, gl.GL_STATIC_DRAW)
    backgroundbuf[:] = background.xyuv
    if level_file is None:
        walls = [components.hitbox((-5, -5), (10, 610)),
                 components.hitbox((995, -5), (10, 610)),
                 components.hitbox((-5, 595), (1010, 5)), ]
    else:
        walls = level.load(level_file)
        for w in walls:
            numpy.round(w.point, out=w.point)
            numpy.round(w.size, out=w.size)
    walls_tlbr = numpy.empty((2, len(walls), 2))
    walls_tlbr[0] = [w.point for w in walls]
    walls_tlbr[1] = [w.point + w.size for w in walls]

    # vertex positions for walls
    quads = numpy.empty((len(walls), 4, 2), dtype=numpy.float32)
    quads[:, 0, :] = [w.point for w in walls]
    quads[:, 2, :] = [w.size for w in walls]
    quads[:, 2, :] += quads[:, 0, :]
    quads[:, 1, 0] = quads[:, 0, 0]
    quads[:, 1, 1] = quads[:, 2, 1]
    quads[:, 3, 0] = quads[:, 2, 0]
    quads[:, 3, 1] = quads[:, 0, 1]
    wallbuf = GLBuffer(quads.size, numpy.float32, gl.GL_STATIC_DRAW)
    wallbuf[:] = quads
    del quads

    # contains vertex and texture positions for sprites
    entitybuf = GLBuffer(dtype=numpy.float32)

    # walls program
    wallprog = shaders.wall()

    spriteprog = shaders.sprite()

    dragonprog = shaders.psycho()
    dragonpalette = load_texture(os.path.join(datadir, 'wallpalette.png'), dimensions=1)
    dragonsprite_scales = load_sprite(datadir, 'dragon_scales')
    dragonsprite_contours = load_sprite(datadir, 'dragon_contours')
    dragonbuf = GLBuffer(4 * 4, numpy.float32, gl.GL_STATIC_DRAW)
    dragonbuf[:] = dragonsprite_scales.xyuv + (-100, 145, 0, 0)
    contourbuf = GLBuffer(4 * 4, numpy.float32, gl.GL_STATIC_DRAW)
    contourbuf[:] = dragonsprite_contours.xyuv + (-100, 145, 0, 0)

    debug_draw = False
    pause = False
    do_frame = False
    ticks_done = 0
    while True:
        start = time.clock()

        key_events = []
        resize_event = None
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return 0
            elif event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
                key_events.append(event)
            elif event.type == pygame.VIDEORESIZE:
                resize_event = event

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    return 0
                if event.key == pygame.K_F2:
                    debug_draw = not debug_draw
                elif event.key == pygame.K_F3:
                    entities.append(sheep(datadir, clock))
                elif event.key == pygame.K_F4:
                    entities.append(drake(datadir, clock))
                elif event.key == pygame.K_F5:
                    entities.append(floaty_sheep(datadir, clock))
                elif event.key == pygame.K_p:
                    pause = not pause
                elif event.key == pygame.K_PERIOD and pause:
                    do_frame = True

        if resize_event:
            handle_resize(resize_event.w, resize_event.h)
            screen_center = (resize_event.w // 2, resize_event.h // 2)
            background.xyuv[:, :2] = [[0, 0], [0, resize_event.h],
                                      [resize_event.w, resize_event.h], [resize_event.w, 0]]
            backgroundbuf[:] = background.xyuv

        if (not pause) or do_frame:
            for event in key_events:
                keyboard.dispatch(event)

            location = components.entity.location
            delta = numpy.array(location)
            motion_a = components.entity.motion_a
            motion_v = components.entity.motion_v
            active_tl = components.entity.active_tl
            active_br = components.entity.active_br
            passive_tl = components.entity.passive_tl
            passive_br = components.entity.passive_br
            instances = components.entity._all[:components.entity._nentities]
            do_translate = components.entity.translate_all

            GROUNDED = intern('grounded')
            motion_a[:] = (0, constants.G)
            clock.dispatch(tick_event)
            for thing in entities:
                thing.tags.discard(GROUNDED)
            motion_v[:] += motion_a

            collisions.resolve_passive_active_collisions(instances, active_tl, active_br, passive_tl, passive_br)
            attempts = 0
            adjust_significant = True
            rppc = collisions.resolve_passive_passive_collisions
            rwc = collisions.resolve_wall_collisions
            grounded_mask = numpy.zeros((len(instances),), dtype=bool)
            stop = numpy.empty((len(instances),2), dtype=bool)
            adjust, sides = rwc(motion_v, passive_tl, passive_br, walls_tlbr[0], walls_tlbr[1])
            numpy.logical_or.reduce(sides.reshape(-1, 2, 2), out=stop, axis=2)
            motion_v[stop] = 0
            do_translate(motion_v[:])
            while attempts < 20 and adjust_significant:
                adjust, sides, done_impulse = rppc(motion_v, passive_tl, passive_br)
                grounded_mask |= sides[:,3]
                adjust *= 0.5
                do_translate(adjust)
                adjust_significant = not numpy.allclose(adjust, 0, atol=0.125)
                adjust_significant |= done_impulse > 0.125
                del adjust, sides
                adjust, sides = rwc(motion_v, passive_tl, passive_br, walls_tlbr[0], walls_tlbr[1])
                adjust_significant |= not numpy.allclose(adjust, 0, atol=0.5)
                do_translate(adjust)
                numpy.logical_or.reduce(sides.reshape(-1, 2, 2), out=stop, axis=2)
                motion_v[stop] = 0
                grounded_mask |= sides[:,3]

                attempts += 1

            for thing in numpy.compress(grounded_mask, instances):
                thing.tags.add(GROUNDED)

            do_frame = False
            ticks_done += 1

        dead = []

        gl.glLoadIdentity()
        gl.glEnableVertexAttribArray(0)
        gl.glUseProgram(spriteprog.id)
        gl.glBindTexture(gl.GL_TEXTURE_2D, background.texid)
        spriteprog['texture'] = 0

        with backgroundbuf.bound:
            gl.glVertexAttribPointer(0, 4, gl.GL_FLOAT, gl.GL_FALSE, 0, 0)
            gl.glDrawArrays(gl.GL_TRIANGLE_FAN, 0, 4)

        # Now move camera
        camera_location = (screen_center - numpy.round(entities[0].location)) + (0, camera_offset)
        gl.glTranslated(camera_location[0], camera_location[1], 0.0)

        for thing in entities:
            if thing.hitpoints <= 0 or thing.location[1] > 10000:
                dead.append(thing)
                continue

        for thing in dead:
            scream.play()
            if thing.name == 'Player':
                thing.hitpoints = 100
                thing.location[:] = (500, -10)
                thing.motion_v[:] = 0
                if thing.physics is not None:
                    thing.physics.last_position[:] = thing.location
            else:
                entities.remove(thing)
                thing.dispose()

        xyuv = numpy.empty((4, 4), dtype=numpy.float32)
        texid = [0] * len(entities)
        with entitybuf.bound:
            for n, thing in enumerate(entities):
                xyuv[:] = thing.graphics.sprite.xyuv
                xy = xyuv[:, 0:2]
                xy[:] += thing.graphics.anchor
                xy[:] += thing.location
                numpy.round(xy, out=xy)
                offset = n * 16
                entitybuf[offset:] = xyuv
                texid[n] = thing.graphics.sprite.texid
                #print('Loaded data for entity', n, xyuv, 'texid', texid[n])

            gl.glVertexAttribPointer(0, 4, gl.GL_FLOAT, gl.GL_FALSE, 0, 0)

            for n, t in enumerate(texid):
                gl.glBindTexture(gl.GL_TEXTURE_2D, t)
                gl.glDrawArrays(gl.GL_TRIANGLE_FAN, n * 4, 4)

        # draw walls
        gl.glUseProgram(wallprog.id)
        wallprog['color'] = (162.0/255.0, 153.0/255.0, 118.0/255.0, 1.0)
        with wallbuf.bound:
            gl.glVertexAttribPointer(0, 2, gl.GL_FLOAT, gl.GL_FALSE, 0, 0)
            gl.glDrawArrays(gl.GL_QUADS, 0, len(walls) * 8)

        # draw some shaders
        gl.glUseProgram(dragonprog.id)
        gl.glBindTexture(gl.GL_TEXTURE_2D, dragonsprite_scales.texid)
        gl.glActiveTexture(gl.GL_TEXTURE0 + 1)
        gl.glBindTexture(gl.GL_TEXTURE_1D, dragonpalette)
        gl.glActiveTexture(gl.GL_TEXTURE0)
        dragonprog['texture'] = 0
        dragonprog['palette'] = 1
        dragonprog['perturb'] = (ticks_done % 1024) / 128
        dragonprog['shift'] = ticks_done / 600
        with dragonbuf.bound:
            gl.glVertexAttribPointer(0, 4, gl.GL_FLOAT, gl.GL_FALSE, 0, 0)
            gl.glDrawArrays(gl.GL_TRIANGLE_FAN, 0, 4)

        # now draw the rest of the f****n' dragon
        gl.glUseProgram(spriteprog.id)
        gl.glBindTexture(gl.GL_TEXTURE_2D, dragonsprite_contours.texid)
        spriteprog['texture'] = 0
        with contourbuf.bound:
            gl.glVertexAttribPointer(0, 4, gl.GL_FLOAT, gl.GL_FALSE, 0, 0)
            gl.glDrawArrays(gl.GL_TRIANGLE_FAN, 0, 4)

        if debug_draw:
            gl.glUseProgram(wallprog.id)
            wallprog['color'] = (0.89, 0.89, 0.89, 1.0)
            quads = numpy.zeros((len(entities), 4, 2), dtype=numpy.float32)
            quads[:, 0, :] = components.entity.passive_tl
            quads[:, 2, :] = components.entity.passive_br
            quads[:, 1, 0] = quads[:, 0, 0]
            quads[:, 1, 1] = quads[:, 2, 1]
            quads[:, 3, 0] = quads[:, 2, 0]
            quads[:, 3, 1] = quads[:, 0, 1]
            gl.glVertexAttribPointer(0, 2, gl.GL_FLOAT, gl.GL_FALSE, 0, quads.ctypes.data)
            gl.glDrawArrays(gl.GL_QUADS, 0, quads.size // 2)

        gl.glColor3f(1, 1, 1)
        gl.glEnable(gl.GL_TEXTURE_2D)

        #screen.fill((120, 50, 50), pygame.Rect(0, 10, player1.hitpoints * 2, 10))
        #screen.fill((120, 50, 50), pygame.Rect(1000 - player2.hitpoints * 2, 10, player2.hitpoints * 2, 10))

        pygame.display.flip()

        delta = time.clock() - start
        if delta < constants.FRAME:
            time.sleep(constants.FRAME - delta)
Esempio n. 54
0
File: shader.py Progetto: Knio/miru
 def enable(self):
     gl.glUseProgram(self.program_no)
Esempio n. 55
0
 def clear():
     " Remove the current shader program "
     glUseProgram(0)
Esempio n. 56
0
    def disable(self):
        """Unbind all programs in use.

        """
        gl.glUseProgram(0)
        self.bound = False
	def use(self):
		gl.glUseProgram(self.program)
Esempio n. 58
0
 def bind(self):
     # bind the program
     GL.glUseProgram(self.handle)
Esempio n. 59
0
 def _finishFBOrender(self):
     GL.glUseProgram(0)
Esempio n. 60
0
 def unbind(self):
     # unbind whatever program is currently bound - not necessarily this program,
     # so this should probably be a class method instead
     GL.glUseProgram(0)