Search code examples
c++opengltexturestexture2d

OpenGL PBO and texture objects: Do I need to allocate memory for both


I am using a pixel buffer object and texture as follows:

// Initialize PBO
Gluint _buffer;
Glenum target = GL_PIXEL_UNPACK_BUFFER
glGenBuffers(1, &_buffer);
if (_buffer) {
    glBindBuffer(target, _buffer);
    glBufferData(target, rows * cols * 4, NULL, GL_DYNAMIC_COPY);
    glBindBuffer(target, 0);
}

Now I load the data into the PBO as follows:

glBindBuffer(target, _buffer);
GLubyte * data = (GLubyte *)glMapBuffer(target, GL_READ_WRITE);
memcpy(data, my_image_data, rows * cols * 4);
glUnmapBuffer(target);
glBindBuffer(target, 0);

My question is when I map this PBO to a texture, do I need to allocate memory for the texture as well (essentially doing a copy). Or can I simply map it without any allocation of memory.

// Without allocation of texture memory
GLuint t;
glBindBuffer(target, t);
glGenTextures(1, &t);
glBindTexture(GL_TEXTURE_2D, t);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, _cols, _rows,
                    GL_BGRA, GL_UNSIGNED_BYTE, NULL);
glBindTexture(GL_TEXTURE_2D, 0);
glBindBuffer(target, 0);

Or should I also have the memory allocation of the texture. So a call like:

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, cols, rows, 0, GL_BGRA, 
             GL_UNSIGNED_BYTE, (GLvoid *)NULL);

after glBindTexture().


Solution

  • Yes, you must allocate storage (via glTexStorage or glTexImage or glCopyTexImage etc.) before being able to upload texture data into an image.

    If you attempt to use glTexSubImage2D on a texture without allocated storage it will fail.