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

半腔热情 提交于 2020-01-02 01:13:11

问题


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;

回答1:


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.




回答2:


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());



回答3:


I think you would need to call glDeleteTextures() after you have finished drawing your pixels, to free the memory.



来源:https://stackoverflow.com/questions/766167/what-happens-to-pixels-after-passing-them-into-glteximage2d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!