Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to pixels after passing them into glTexImage2D()?

If for example I create an array of pixels, like so:

int *getPixels()
{
    int *pixels = new int[10];
    pixels[0] = 1;
    pixels[1] = 0;
    pixels[1] = 1;
    // etc...
}

glTexImage2D(..., getPixels());

Does glTexImage2D use that reference or copy the pixels into it's own memory?

If the answer is the former, then should I do the following?

int *p = getPixels();
glTexImage2D(..., p);

/* Just changed to delete[], because delete
 * would only delete the first element! */
delete[] p;
like image 831
Nick Bolton Avatar asked Apr 19 '09 21:04

Nick Bolton


Video Answer


2 Answers

From this quote in the man page, it sounds like glTexImage2D allocates its own memory. This would make sense, ideally the OpenGL API would send data to be stored on the graphics card itself (if drivers/implementation/etc permitted).

In GL version 1.1 or greater, pixels may be a null pointer. In this case texture memory is allocated to accommodate a texture of width width and height height. You can then download subtextures to initialize this texture memory. The image is undefined if the user tries to apply an uninitialized portion of the texture image to a primitive.

So yea, I'd imagine there is no harm in freeing the memory once you've generated your texture.

like image 151
Brian Gianforcaro Avatar answered Oct 11 '22 01:10

Brian Gianforcaro


Yes, after the call to geTexImage2D() returns it is safe to discard the data you passed to it. infact, if you don't do that you'll have a memory leak, like in this code:

int *getPixels()
{
    int *pixels = new int[10];
    pixels[0] = 1;
    pixels[1] = 0;
    pixels[1] = 1;
    // etc...
}

glTexImage2D(..., getPixels());

You pass the pointer to the buffer to the call but then the pointer is lost and most likely leaks. What you should do is store it and delete it aftet the call retuns:

int *pbuf = getPixels();
glTexImage2D(..., pbuf);
delete[] pbuf;

alternativly, if the texture is of a constant size, you can pass a pointer to an array that is on the stack:

{
    int buf[10];
    ...
    glTexImage2D(..., pbuf);
}

Finally, if you don't want to worry about pointers and arrays, you can use STL:

vector<int> buf;
fillPixels(buf);
getTexImage2D(..., buf.begin());
like image 28
shoosh Avatar answered Oct 11 '22 01:10

shoosh