Search code examples
pythonopenglpyopengl

glBufferData seperates data with 0


I tried loading my indices into an GL_ELEMENT_ARRAY_BUFFER, but when when I try this it separates my data with 0's.

So for instance I loaded this data:

[0 1 3 3 1 2]

with the function glBufferData (look at code sample below). When I ask for the data in the buffer with glGenBufferSubData, this function returns the following:

[0 0 1 0 3 0 3 0 1 0 2 0]. 
def __bindIndicesBuffer__(self, indices):
        vboID = glGenBuffers(1)
        self.vbos.append(vboID)
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vboID)
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, 12, numpy.array(indices, dtype = numpy.int16), GL_STATIC_DRAW)
        print(glGetBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, 12))

In the function glBufferData I have to reserve 12 bytes of data, which is weird because I only have 6 numbers. Anybody has a clue what is going on?


Solution

  • In the function glBufferData I have to reserve 12 bytes of data, which is weird because I only have 6 numbers [...]

    Of course, each of you your numbers is of type int16, this means each number has 16 bits respectively 2 bytes (1 byte has 8 bits). 6 numbers with 2 bytes need 12 bytes of memory. Since the size parameter in glBufferData is the size in bytes, the parameter has to be 12.


    [...] when I try this it separates my data with 0's [...]

    glGetBufferSubData reads the byte values of the buffer and returns a array of uint8 values. So each of the 12 bytes is treated as a separate 8 bit (unit8) value, that is what is printed.

    If you want to get the "orginal" int16 values, then you've to reinterpret the array by numpy.frombuffer

    uint8_data = glGetBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, 12)
    int16_data = numpy.frombuffer(uint8_data, dtype=numpy.int16)
    print(int16_data)
    

    Alternatively you can treat the data pointer to a int16 array as a unit8 data pointer (see numpy.ndarray.ctypes):

    int16_data = numpy.empty([6], dtype=numpy.int16)
    unit8_ptr  = int16_data.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8))
    glGetBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, 12, unit8_ptr)
    print(int16_data)