Getting the value of buffers in Python wrapper of OpenGL

449 Views Asked by At

Is it possible to get the buffer to readable array? i.e. When I call them or print them, only are shown. How can I get the value of buffer object to python array?

1

There are 1 best solutions below

0
On BEST ANSWER

There are different possibilities. One possibility is to use glGetBufferSubData. The data of a Framebuffer Object can be read by glReadPixels, if the buffer is bound for reading (GL_READ_FRAMEBUFFER). A texture can be read by glGetTexImage. In general a buffer can be accessed by Buffer Mapping (glMapBuffer / glMapBufferRange).

For instance you can use glGetBufferSubData to read floating point values to read the data of a GL_ARRAY_BUFFER. In the following example vbo is a vertex buffer object and no_of_floats is the number of floats you want to read.

glGetBufferSubData returns an array of bytes. You can use numpy to convert the array of bytes to an array of floats:

import numpy as np
glBindBuffer(GL_ARRAY_BUFFER, vbo)
uint8_data = glGetBufferSubData(GL_ARRAY_BUFFER, 0, no_of_floats * 4)
float32_data = np.frombuffer(uint8_data, dtype=np.float32)

Another option is to generate a ctypes array and to read the data directly into the array:

import ctypes
float32_data = (ctypes.c_float * no_of_floats)() # or (GLfloat * no_of_floats)()
void_ptr = ctypes.c_void_p(ctypes.addressof(float32_data))

glBindBuffer(GL_ARRAY_BUFFER, vbo)
glGetBufferSubData(GL_ARRAY_BUFFER, 0, no_of_floats * 4, void_ptr)