Python OpenGL.GL.GL_FLOAT Examples

The following are 30 code examples of OpenGL.GL.GL_FLOAT(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module OpenGL.GL , or try the search function .
Example #1
Source File: test_opengl.py    From spimagine with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def paintGL(self):
        self.makeCurrent()
        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

        self.program.bind()

        self.program.enableAttributeArray("position")
        self.vbo.bind()
        gl.glVertexAttribPointer(self.program.attributeLocation("position"), 2, gl.GL_FLOAT, gl.GL_FALSE, 0, self.vbo)


        self.program.enableAttributeArray("normal")
        self.vbo_cols.bind()
        gl.glVertexAttribPointer(self.program.attributeLocation("normal"), 3, gl.GL_FLOAT, gl.GL_FALSE, 0, self.vbo_cols)


        gl.glDrawArrays(gl.GL_TRIANGLES, 0, len(self.data))



        print(self.context().format().majorVersion())
        print(self.context().format().minorVersion())


        print(gl.glGetString(gl.GL_VERSION)); 
Example #2
Source File: thumbview.py    From MCEdit-Unified with ISC License 6 votes vote down vote up
def gl_draw(self):
        if self.schematic.chunkCount > len(self.renderer.chunkRenderers):
            self.gl_draw_thumb()
        else:
            if self.fbo is None:
                w, h = self.fboSize
                self.fbo = FramebufferTexture(w, h, self.gl_draw_tex)
            GL.glMatrixMode(GL.GL_PROJECTION)
            GL.glLoadIdentity()
            GL.glMatrixMode(GL.GL_MODELVIEW)
            GL.glLoadIdentity()
            GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY)
            GL.glColor(1.0, 1.0, 1.0, 1.0)
            GL.glVertexPointer(2, GL.GL_FLOAT, 0, array([-1, -1,
                                                         - 1, 1,
                                                         1, 1,
                                                         1, -1, ], dtype='float32'))
            GL.glTexCoordPointer(2, GL.GL_FLOAT, 0, array([0, 0, 0, 256, 256, 256, 256, 0], dtype='float32'))
            e = (GL.GL_TEXTURE_2D,)
            if not self.drawBackground:
                e += (GL.GL_ALPHA_TEST,)
            with gl.glEnable(*e):
                self.fbo.bind()
                GL.glDrawArrays(GL.GL_QUADS, 0, 4)
            GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY) 
Example #3
Source File: compass.py    From GDMC with ISC License 6 votes vote down vote up
def drawSelf(self):
        if self._tex is None:
            filename = os.path.join("toolicons", "compass.png")

            self._tex = loadPNGTexture(filename)
            
        self._tex.bind()
        size = 0.001 * config.settings.compassSize.get()

        with gl.glPushMatrix(GL.GL_MODELVIEW):
            GL.glLoadIdentity()

            yaw, pitch = self.yawPitch
            if config.settings.viewMode.get() == "Chunk":
                yaw = -180
            GL.glTranslatef(1. - (size + self.x), size + self.y, 0.0)  # position on upper right corner
            GL.glRotatef(180 - yaw, 0., 0., 1.)  # adjust to north
            GL.glColor3f(1., 1., 1.)

            with gl.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY):
                GL.glVertexPointer(2, GL.GL_FLOAT, 0, makeQuad(-size, -size, 2 * size, 2 * size))
                GL.glTexCoordPointer(2, GL.GL_FLOAT, 0, makeQuad(0, 0, 256, 256))

                with gl.glEnable(GL.GL_BLEND, GL.GL_TEXTURE_2D):
                    GL.glDrawArrays(GL.GL_QUADS, 0, 4) 
Example #4
Source File: camera.py    From GDMC with ISC License 6 votes vote down vote up
def _drawCeiling():
        lines = []
        minz = minx = -256
        maxz = maxx = 256
        for x in range(minx, maxx + 1, 16):
            lines.append((x, 0, minz))
            lines.append((x, 0, maxz))
        for z in range(minz, maxz + 1, 16):
            lines.append((minx, 0, z))
            lines.append((maxx, 0, z))

        GL.glColor(0.3, 0.7, 0.9)
        GL.glVertexPointer(3, GL.GL_FLOAT, 0, numpy.array(lines, dtype='float32'))

        GL.glEnable(GL.GL_DEPTH_TEST)
        GL.glDepthMask(False)
        GL.glDrawArrays(GL.GL_LINES, 0, len(lines))
        GL.glDisable(GL.GL_DEPTH_TEST)
        GL.glDepthMask(True) 
Example #5
Source File: thumbview.py    From GDMC with ISC License 6 votes vote down vote up
def gl_draw(self):
        if self.schematic.chunkCount > len(self.renderer.chunkRenderers):
            self.gl_draw_thumb()
        else:
            if self.fbo is None:
                w, h = self.fboSize
                self.fbo = FramebufferTexture(w, h, self.gl_draw_tex)
            GL.glMatrixMode(GL.GL_PROJECTION)
            GL.glLoadIdentity()
            GL.glMatrixMode(GL.GL_MODELVIEW)
            GL.glLoadIdentity()
            GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY)
            GL.glColor(1.0, 1.0, 1.0, 1.0)
            GL.glVertexPointer(2, GL.GL_FLOAT, 0, array([-1, -1,
                                                         - 1, 1,
                                                         1, 1,
                                                         1, -1, ], dtype='float32'))
            GL.glTexCoordPointer(2, GL.GL_FLOAT, 0, array([0, 0, 0, 256, 256, 256, 256, 0], dtype='float32'))
            e = (GL.GL_TEXTURE_2D,)
            if not self.drawBackground:
                e += (GL.GL_ALPHA_TEST,)
            with gl.glEnable(*e):
                self.fbo.bind()
                GL.glDrawArrays(GL.GL_QUADS, 0, 4)
            GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY) 
Example #6
Source File: renderer.py    From MCEdit-Unified with ISC License 6 votes vote down vote up
def drawFaceVertices(self, buf):
        if not len(buf):
            return
        stride = elementByteLength

        GL.glVertexPointer(3, GL.GL_FLOAT, stride, (buf.ravel()))
        GL.glTexCoordPointer(2, GL.GL_FLOAT, stride, (buf.ravel()[3:]))
        GL.glColorPointer(4, GL.GL_UNSIGNED_BYTE, stride, (buf.view(dtype=numpy.uint8).ravel()[20:]))

        GL.glDepthMask(False)

        GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_LINE)

        GL.glLineWidth(2.0)
        GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4)

        GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_FILL)

        GL.glPolygonOffset(DepthOffset.TerrainWire, DepthOffset.TerrainWire)
        with gl.glEnable(GL.GL_POLYGON_OFFSET_FILL, GL.GL_DEPTH_TEST):
            GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4)
        GL.glDepthMask(True) 
Example #7
Source File: renderer.py    From MCEdit-Unified with ISC License 6 votes vote down vote up
def drawFaceVertices(self, buf):
        if not len(buf):
            return
        stride = elementByteLength
  
        GL.glVertexPointer(3, GL.GL_FLOAT, stride, (buf.ravel()))
        GL.glTexCoordPointer(2, GL.GL_FLOAT, stride, (buf.ravel()[3:]))
        GL.glColorPointer(4, GL.GL_UNSIGNED_BYTE, stride, (buf.view(dtype=numpy.uint8).ravel()[20:]))
  
        GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_LINE)
  
        GL.glLineWidth(1)
        with gl.glEnable(GL.GL_DEPTH_TEST):
            GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4)
        GL.glLineWidth(2.0)
        with gl.glEnable(GL.GL_DEPTH_TEST):
            GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4)
        GL.glLineWidth(1.0)
  
        GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_FILL) 
Example #8
Source File: renderer.py    From GDMC with ISC License 6 votes vote down vote up
def drawFaceVertices(self, buf):
        if 0 == len(buf):
            return
        stride = elementByteLength

        GL.glVertexPointer(3, GL.GL_FLOAT, stride, (buf.ravel()))
        GL.glTexCoordPointer(2, GL.GL_FLOAT, stride, (buf.ravel()[3:]))
        GL.glColorPointer(4, GL.GL_UNSIGNED_BYTE, stride, (buf.view(dtype=numpy.uint8).ravel()[20:]))

        GL.glDepthMask(False)

        GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_LINE)

        GL.glLineWidth(2.0)
        GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4)

        GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_FILL)

        GL.glPolygonOffset(DepthOffset.TerrainWire, DepthOffset.TerrainWire)
        with gl.glEnable(GL.GL_POLYGON_OFFSET_FILL, GL.GL_DEPTH_TEST):
            GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4)
        GL.glDepthMask(True) 
Example #9
Source File: fullscreen_quad.py    From dm_control with Apache License 2.0 6 votes vote down vote up
def _init_shaders(self):
    """Initializes the shaders used to render the textures fullscreen quad."""
    vs = shaders.compileShader(_VERTEX_SHADER, GL.GL_VERTEX_SHADER)
    fs = shaders.compileShader(_FRAGMENT_SHADER, GL.GL_FRAGMENT_SHADER)
    self._shader = shaders.compileProgram(vs, fs)

    stride = _FLOATS_PER_VERTEX * _SIZE_OF_FLOAT
    var_position = GL.glGetAttribLocation(self._shader, _VAR_POSITION)
    GL.glVertexAttribPointer(
        var_position, 2, GL.GL_FLOAT, GL.GL_FALSE, stride, None)
    GL.glEnableVertexAttribArray(var_position)

    var_uv = GL.glGetAttribLocation(self._shader, _VAR_UV)
    uv_offset = ctypes.c_void_p(_FLOATS_PER_XY * _SIZE_OF_FLOAT)
    GL.glVertexAttribPointer(
        var_uv, 2, GL.GL_FLOAT, GL.GL_FALSE, stride, uv_offset)
    GL.glEnableVertexAttribArray(var_uv)

    self._var_texture_sampler = GL.glGetUniformLocation(
        self._shader, _VAR_TEXTURE_SAMPLER) 
Example #10
Source File: compass.py    From MCEdit-Unified with ISC License 6 votes vote down vote up
def drawSelf(self):
        if self._tex is None:
            filename = os.path.join("toolicons", "compass.png")

            self._tex = loadPNGTexture(filename)
            
        self._tex.bind()
        size = 0.001 * config.settings.compassSize.get()

        with gl.glPushMatrix(GL.GL_MODELVIEW):
            GL.glLoadIdentity()

            yaw, pitch = self.yawPitch
            if config.settings.viewMode.get() == "Chunk":
                yaw = -180
            GL.glTranslatef(1. - (size + self.x), size + self.y, 0.0)  # position on upper right corner
            GL.glRotatef(180 - yaw, 0., 0., 1.)  # adjust to north
            GL.glColor3f(1., 1., 1.)

            with gl.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY):
                GL.glVertexPointer(2, GL.GL_FLOAT, 0, makeQuad(-size, -size, 2 * size, 2 * size))
                GL.glTexCoordPointer(2, GL.GL_FLOAT, 0, makeQuad(0, 0, 256, 256))

                with gl.glEnable(GL.GL_BLEND, GL.GL_TEXTURE_2D):
                    GL.glDrawArrays(GL.GL_QUADS, 0, 4) 
Example #11
Source File: renderer.py    From patch_linemod with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def read_fbo_color_rgba32f(fbo):
        """
        Read the color attachment from a FBO, assuming it is GL_RGBA_32F.
        # Ref: https://github.com/julienr/vertex_visibility/blob/master/depth.py
        """
        h, w = fbo.color_buffer.shape[:2]
        x, y = 0, 0
        im = gl.glReadPixels(x, y, w, h, gl.GL_RGBA, gl.GL_FLOAT)
        im = np.frombuffer(im, np.float32)
        im.shape = h, w, 4
        im = im[::-1, :]

        return im

#-------------------------------------------------------------------------------
# Ref: https://github.com/vispy/vispy/blob/master/examples/demo/gloo/offscreen.py 
Example #12
Source File: osmesa_renderer.py    From dm_control with Apache License 2.0 5 votes vote down vote up
def _platform_make_current(self):
    if self._context:
      success = osmesa.OSMesaMakeCurrent(
          self._context,
          self._buffer,
          GL.GL_FLOAT,
          self._width,
          self._height)
      if not success:
        raise RuntimeError('Failed to make OSMesa context current.') 
Example #13
Source File: osmesa_renderer_test.py    From dm_control with Apache License 2.0 5 votes vote down vote up
def test_make_current(self):
    mock_context = mock.MagicMock()
    mock_buffer = mock.MagicMock()
    with mock.patch(CONTEXT_PATH) as mock_osmesa:
      with mock.patch(GL_ARRAYS_PATH) as mock_glarrays:
        mock_osmesa.OSMesaCreateContextExt.return_value = mock_context
        mock_glarrays.GLfloatArray.zeros.return_value = mock_buffer
        renderer = _render.Renderer(MAX_WIDTH, MAX_HEIGHT)
        with renderer.make_current():
          pass
        mock_osmesa.OSMesaMakeCurrent.assert_called_once_with(
            mock_context, mock_buffer, GL.GL_FLOAT, MAX_WIDTH, MAX_HEIGHT)
        renderer.free() 
Example #14
Source File: osmesa_renderer.py    From dm_control with Apache License 2.0 5 votes vote down vote up
def _platform_free(self):
    """Frees resources associated with this context."""
    if self._context and self._context == osmesa.OSMesaGetCurrentContext():
      osmesa.OSMesaMakeCurrent(None, None, GL.GL_FLOAT, 0, 0)
    osmesa.OSMesaDestroyContext(self._context)
    self._buffer = None
    self._context = None 
Example #15
Source File: hellovr_glfw.py    From pyopenvr with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_up_scene(self):
        self.vertex_data = []
        v = self.scene_volume_init
        s = self.scale_spacing
        scale = 0.3
        mat_scale = numpy.diag(numpy.array([scale, scale, scale, 1], dtype=numpy.float32))
        t = -0.5 * v * s
        mat_translate = translate(t, t, t)
        mat = mat_translate @ mat_scale
        for z in range(v):
            for y in range(v):
                for x in range(v):
                    self.add_cube_to_scene(mat)
                    mat = translate(s, 0, 0) @ mat
                mat = translate(-v * s, s, 0) @ mat
            mat = translate(0, -v * s, s) @ mat
        vertex_data = numpy.array(self.vertex_data, dtype=numpy.float32).flatten()
        self.vert_count = len(vertex_data) / 5
        self.scene_vao = GL.glGenVertexArrays(1)
        GL.glBindVertexArray(self.scene_vao)
        self.scene_vert_buffer = GL.glGenBuffers(1)
        GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.scene_vert_buffer)
        GL.glBufferData(GL.GL_ARRAY_BUFFER, vertex_data, GL.GL_STATIC_DRAW)
        f_size = sizeof(c_float)
        stride = 5 * f_size
        GL.glEnableVertexAttribArray(0)
        GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, False, stride, cast(0 * f_size, c_void_p))
        GL.glEnableVertexAttribArray(1)
        GL.glVertexAttribPointer(1, 2, GL.GL_FLOAT, False, stride, cast(3 * f_size, c_void_p))
        GL.glBindVertexArray(0)
        GL.glDisableVertexAttribArray(0)
        GL.glDisableVertexAttribArray(1) 
Example #16
Source File: glhelpers.py    From bluesky with GNU General Public License v3.0 5 votes vote down vote up
def bind_attrib(self, attrib_id, size, data, storagetype=gl.GL_STATIC_DRAW, instance_divisor=0, datatype=gl.GL_FLOAT, stride=0, offset=None, normalize=False):
        if RenderObject.bound_vao is not self.vao_id:
            gl.glBindVertexArray(self.vao_id)
            RenderObject.bound_vao = self.vao_id

        # Keep track of max instance divisor
        self.max_instance_divisor = max(instance_divisor, self.max_instance_divisor)

        # If the input is an array create a new GL buffer, otherwise assume the buffer already exists and a buffer ID is passed
        if type(data) is np.ndarray:
            # Get an index to one new buffer in GPU mem, bind it, and copy the array data to it
            buf_id = gl.glGenBuffers(1)
            gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buf_id)
            gl.glBufferData(gl.GL_ARRAY_BUFFER, data.nbytes, data, storagetype)
        else:
            # Assume that a GLuint is passed which means that the buffer is already in GPU memory
            buf_id = data
            gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buf_id)

        # Assign this buffer to one of the attributes in the shader
        gl.glEnableVertexAttribArray(attrib_id)
        gl.glVertexAttribPointer(attrib_id, size, datatype, normalize, stride, offset)
        # For instanced data, indicate per how many instances we move a step in the buffer (1=per instance)
        if instance_divisor > 0:
            gl.glVertexAttribDivisor(attrib_id, instance_divisor)
        # Clean up
        gl.glDisableVertexAttribArray(attrib_id)

        self.enabled_attributes[attrib_id] = [size, buf_id, instance_divisor, datatype]

        return buf_id 
Example #17
Source File: renderer.py    From eccv18-rgb_pose_refinement with MIT License 5 votes vote down vote up
def finish(self):

        im = gl.glReadPixels(0, 0, self.size[0], self.size[1], gl.GL_RGB, gl.GL_FLOAT)
        rgb = np.copy(np.frombuffer(im, np.float32)).reshape(self.shape+(3,))[::-1, :]  # Read buffer and flip Y
        im = gl.glReadPixels(0, 0, self.size[0], self.size[1], gl.GL_DEPTH_COMPONENT, gl.GL_FLOAT)
        dep = np.copy(np.frombuffer(im, np.float32)).reshape(self.shape+(1,))[::-1, :]  # Read buffer and flip Y

        # Convert z-buffer to depth map
        mult = (self.clip_near*self.clip_far)/(self.clip_near-self.clip_far)
        addi = self.clip_far/(self.clip_near-self.clip_far)
        bg = dep == 1
        dep = mult/(dep + addi)
        dep[bg] = 0
        return rgb, np.squeeze(dep) 
Example #18
Source File: hellovr_glfw.py    From pyopenvr with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_up_companion_window(self):
        if not self.hmd:
            return
        verts = list()
        # left eye verts
        verts.append(((-1, -1), (0, 0)))
        verts.append(((0, -1), (1, 0)))
        verts.append(((-1, 1), (0, 1)))
        verts.append(((0, 1), (1, 1)))
        # right eye verts
        verts.append(((0, -1), (0, 0)))
        verts.append(((1, -1), (1, 0)))
        verts.append(((0, 1), (0, 1)))
        verts.append(((1, 1), (1, 1)))
        vIndices = numpy.array([0, 1, 3, 0, 3, 2, 4, 5, 7, 4, 7, 6], dtype=numpy.uint16)
        self.companion_window_index_size = len(vIndices)
        self.companion_window_vao = GL.glGenVertexArrays(1)
        GL.glBindVertexArray(self.companion_window_vao)
        #
        self.companion_window_id_vert_buffer = GL.glGenBuffers(1)
        GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.companion_window_id_vert_buffer)
        vVerts = numpy.array(verts, dtype=numpy.float32).flatten()
        GL.glBufferData(GL.GL_ARRAY_BUFFER, vVerts, GL.GL_STATIC_DRAW)
        #
        self.companion_window_id_index_buffer = GL.glGenBuffers(1)
        GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, self.companion_window_id_index_buffer)
        GL.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER, vIndices, GL.GL_STATIC_DRAW)
        #
        f_size = sizeof(c_float)
        GL.glEnableVertexAttribArray(0)
        GL.glVertexAttribPointer(0, 2, GL.GL_FLOAT, False, 4 * f_size, cast(0 * f_size, c_void_p))
        #
        GL.glEnableVertexAttribArray(1)
        GL.glVertexAttribPointer(1, 2, GL.GL_FLOAT, False, 4 * f_size, cast(2 * f_size, c_void_p))
        #
        GL.glBindVertexArray(0)
        GL.glDisableVertexAttribArray(0)
        GL.glDisableVertexAttribArray(1)
        GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
        GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0) 
Example #19
Source File: leveleditor.py    From MCEdit-Unified with ISC License 5 votes vote down vote up
def drawStars(self):
        pos = self.mainViewport.cameraPosition
        self.mainViewport.cameraPosition = [x / 128.0 for x in pos]
        self.mainViewport.setModelview()

        GL.glColor(.5, .5, .5, 1.)

        GL.glVertexPointer(3, GL.GL_FLOAT, 0, self.starVertices)
        GL.glDrawArrays(GL.GL_QUADS, 0, len(self.starVertices) / 3)

        self.mainViewport.cameraPosition = pos
        self.mainViewport.setModelview() 
Example #20
Source File: renderer.py    From MCEdit-Unified with ISC License 5 votes vote down vote up
def drawFaceVertices(self, buf):
        if not len(buf):
            return
        stride = elementByteLength
        
        GL.glVertexPointer(3, GL.GL_FLOAT, stride, (buf.ravel()))
        GL.glTexCoordPointer(2, GL.GL_FLOAT, stride, (buf.ravel()[3:]))
        GL.glColorPointer(4, GL.GL_UNSIGNED_BYTE, stride, (buf.view(dtype=numpy.uint8).ravel()[20:]))

        GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4) 
Example #21
Source File: renderer.py    From MCEdit-Unified with ISC License 5 votes vote down vote up
def drawFaceVertices(self, buf):
        if not len(buf):
            return
        stride = 16

        GL.glVertexPointer(3, GL.GL_FLOAT, stride, numpy.ravel(buf.ravel()))
        GL.glColorPointer(4, GL.GL_UNSIGNED_BYTE, stride, (buf.view(dtype='uint8').ravel()[12:]))

        GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY)
        GL.glDrawArrays(GL.GL_QUADS, 0, len(buf) * 4)
        GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY) 
Example #22
Source File: renderer.py    From MCEdit-Unified with ISC License 5 votes vote down vote up
def _drawLoadableChunkMarkers(self):
        if self.level.chunkCount:
            chunkSet = set(self.level.allChunks)

            sizedChunks = chunkMarkers(chunkSet)

            GL.glPushAttrib(GL.GL_FOG_BIT)
            GL.glDisable(GL.GL_FOG)

            GL.glEnable(GL.GL_BLEND)
            GL.glEnable(GL.GL_POLYGON_OFFSET_FILL)
            GL.glPolygonOffset(DepthOffset.ChunkMarkers, DepthOffset.ChunkMarkers)
            GL.glEnable(GL.GL_DEPTH_TEST)

            GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY)
            GL.glEnable(GL.GL_TEXTURE_2D)
            GL.glColor(1.0, 1.0, 1.0, 1.0)

            self.floorTexture.bind()
            for size, chunks in sizedChunks.iteritems():
                if not len(chunks):
                    continue
                chunks = numpy.array(chunks, dtype='float32')

                chunkPosition = numpy.zeros(shape=(chunks.shape[0], 4, 3), dtype='float32')
                chunkPosition[:, :, (0, 2)] = numpy.array(((0, 0), (0, 1), (1, 1), (1, 0)), dtype='float32')
                chunkPosition[:, :, (0, 2)] *= size
                chunkPosition[:, :, (0, 2)] += chunks[:, numpy.newaxis, :]
                chunkPosition *= 16
                GL.glVertexPointer(3, GL.GL_FLOAT, 0, chunkPosition.ravel())
                GL.glTexCoordPointer(2, GL.GL_FLOAT, 0, (chunkPosition[..., (0, 2)] * 16).ravel())
                GL.glDrawArrays(GL.GL_QUADS, 0, len(chunkPosition) * 4)

            GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY)
            GL.glDisable(GL.GL_TEXTURE_2D)
            GL.glDisable(GL.GL_BLEND)
            GL.glDisable(GL.GL_DEPTH_TEST)
            GL.glDisable(GL.GL_POLYGON_OFFSET_FILL)
            GL.glPopAttrib() 
Example #23
Source File: glbackground.py    From MCEdit-Unified with ISC License 5 votes vote down vote up
def gl_draw(self):
        #if hasattr(self, 'highlight_bg_color') and self in self.get_root().find_widget(mouse.get_pos()).all_parents():
        #    color = self.highlight_bg_color
        #else:
        color = tuple(self.bg_color) + (1.0,)

        glEnable(GL_BLEND)
        glColor(color[0], color[1], color[2], color[3])
        glVertexPointer(2, GL_FLOAT, 0, array([-1, -1, -1, 1, 1, 1, 1, -1], dtype='float32'))
        glDrawArrays(GL_QUADS, 0, 4)
        glDisable(GL_BLEND) 
Example #24
Source File: camera.py    From MCEdit-Unified with ISC License 5 votes vote down vote up
def _blockUnderCursor(self, center=False):
        """
            returns a point in 3d space that was determined by
         reading the depth buffer value
        """
        try:
            GL.glReadBuffer(GL.GL_BACK)
        except Exception:
            logging.exception('Exception during glReadBuffer')
        ws = self.root.size
        if center:
            x, y = ws
            x //= 2
            y //= 2
        else:
            x, y = mouse.get_pos()
        if (x < 0 or y < 0 or x >= ws[0] or
                    y >= ws[1]):
            return 0, 0, 0

        y = ws[1] - y

        try:
            pixel = GL.glReadPixels(x, y, 1, 1, GL.GL_DEPTH_COMPONENT, GL.GL_FLOAT)
            newpoint = unproject(x, y, pixel[0])
        except Exception:
            return 0, 0, 0

        return newpoint 
Example #25
Source File: camera.py    From MCEdit-Unified with ISC License 5 votes vote down vote up
def _drawFloorQuad(self):
        GL.glDepthMask(True)
        GL.glPolygonOffset(DepthOffset.ChunkMarkers + 2, DepthOffset.ChunkMarkers + 2)
        GL.glVertexPointer(3, GL.GL_FLOAT, 0, self.floorQuad)
        GL.glColor(*self.floorColor)
        with gl.glEnable(GL.GL_BLEND, GL.GL_DEPTH_TEST, GL.GL_POLYGON_OFFSET_FILL):
            GL.glDrawArrays(GL.GL_QUADS, 0, 4) 
Example #26
Source File: blockview.py    From MCEdit-Unified with ISC License 5 votes vote down vote up
def _gl_draw(self):
        blockInfo = self.blockInfo
        if blockInfo.ID is 0:
            return

        GL.glColor(1.0, 1.0, 1.0, 1.0)
        GL.glEnable(GL.GL_TEXTURE_2D)
        GL.glEnable(GL.GL_ALPHA_TEST)
        self.materials.terrainTexture.bind()
        pixelScale = 0.5 if self.materials.name in ("Pocket", "Alpha") else 1.0
        texSize = 16 * pixelScale

        GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY)
        GL.glVertexPointer(2, GL.GL_FLOAT, 0, array([-1, -1,
                                                     - 1, 1,
                                                     1, 1,
                                                     1, -1, ], dtype='float32'))
        # hack to get end rod to render properly
        # we really should use json models?
        if blockInfo.ID == 198:
            texOrigin = array([17*16, 20*16])
        else:
            texOrigin = array(self.materials.blockTextures[blockInfo.ID, blockInfo.blockData, 0])
        texOrigin = texOrigin.astype(float) * pixelScale

        GL.glTexCoordPointer(2, GL.GL_FLOAT, 0, array([texOrigin[0], texOrigin[1] + texSize,
                                                       texOrigin[0], texOrigin[1],
                                                       texOrigin[0] + texSize, texOrigin[1],
                                                       texOrigin[0] + texSize, texOrigin[1] + texSize],
                                                      dtype='float32'))

        GL.glDrawArrays(GL.GL_QUADS, 0, 4)

        GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY)
        GL.glDisable(GL.GL_ALPHA_TEST)
        GL.glDisable(GL.GL_TEXTURE_2D) 
Example #27
Source File: glhelpers.py    From bluesky with GNU General Public License v3.0 5 votes vote down vote up
def bind_attrib(self, attrib_id, size, data, storagetype=gl.GL_STATIC_DRAW, instance_divisor=0, datatype=gl.GL_FLOAT, stride=0, offset=None, normalize=False):
        if RenderObject.bound_vao is not self.vao_id:
            gl.glBindVertexArray(self.vao_id)
            RenderObject.bound_vao = self.vao_id

        # Keep track of max instance divisor
        self.max_instance_divisor = max(instance_divisor, self.max_instance_divisor)

        # If the input is an array create a new GL buffer, otherwise assume the buffer already exists and a buffer ID is passed
        if type(data) is np.ndarray:
            # Get an index to one new buffer in GPU mem, bind it, and copy the array data to it
            buf_id = gl.glGenBuffers(1)
            gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buf_id)
            gl.glBufferData(gl.GL_ARRAY_BUFFER, data.nbytes, data, storagetype)
        else:
            # Assume that a GLuint is passed which means that the buffer is already in GPU memory
            buf_id = data
            gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buf_id)

        # Assign this buffer to one of the attributes in the shader
        gl.glEnableVertexAttribArray(attrib_id)
        gl.glVertexAttribPointer(attrib_id, size, datatype, normalize, stride, offset)
        # For instanced data, indicate per how many instances we move a step in the buffer (1=per instance)
        if instance_divisor > 0:
            gl.glVertexAttribDivisor(attrib_id, instance_divisor)
        # Clean up
        gl.glDisableVertexAttribArray(attrib_id)

        self.enabled_attributes[attrib_id] = [size, buf_id, instance_divisor, datatype]

        return buf_id 
Example #28
Source File: renderer_xyz.py    From Pix2Pose with MIT License 5 votes vote down vote up
def finish(self):

        im = gl.glReadPixels(0, 0, self.size[0], self.size[1], gl.GL_RGB, gl.GL_FLOAT)
        rgb = np.copy(np.frombuffer(im, np.float32)).reshape(self.shape+(3,))[::-1, :]  # Read buffer and flip Y
        im = gl.glReadPixels(0, 0, self.size[0], self.size[1], gl.GL_DEPTH_COMPONENT, gl.GL_FLOAT)
        dep = np.copy(np.frombuffer(im, np.float32)).reshape(self.shape+(1,))[::-1, :]  # Read buffer and flip Y

        # Convert z-buffer to depth map
        mult = (self.clip_near*self.clip_far)/(self.clip_near-self.clip_far)
        addi = self.clip_far/(self.clip_near-self.clip_far)
        bg = dep == 1
        dep = mult/(dep + addi)
        dep[bg] = 0
        return rgb, np.squeeze(dep) 
Example #29
Source File: rendering.py    From renpy-shader with MIT License 5 votes vote down vote up
def bindAttributeArray(self, shader, name, data, count):
        location = gl.glGetAttribLocation(shader.handle, name)
        if location != -1:
            gl.glVertexAttribPointer(location, count, gl.GL_FLOAT, False, 0, data)
            gl.glEnableVertexAttribArray(location) 
Example #30
Source File: renderer.py    From ssd-6d with MIT License 5 votes vote down vote up
def finish(self):

        im = gl.glReadPixels(0, 0, self.size[0], self.size[1], gl.GL_RGB, gl.GL_FLOAT)
        rgb = np.copy(np.frombuffer(im, np.float32)).reshape(self.shape+(3,))[::-1, :]  # Read buffer and flip Y
        im = gl.glReadPixels(0, 0, self.size[0], self.size[1], gl.GL_DEPTH_COMPONENT, gl.GL_FLOAT)
        dep = np.copy(np.frombuffer(im, np.float32)).reshape(self.shape+(1,))[::-1, :]  # Read buffer and flip Y

        # Convert z-buffer to depth map
        mult = (self.clip_near*self.clip_far)/(self.clip_near-self.clip_far)
        addi = self.clip_far/(self.clip_near-self.clip_far)
        bg = dep == 1
        dep = mult/(dep + addi)
        dep[bg] = 0
        return rgb, np.squeeze(dep)