Sign in to follow this  
Guy Joel McLean

OpenGL glDeleteTextures does not delete pixel data

Recommended Posts

Afternoon all,

 

I have a class called Texture, that I need to be able to initialize once on my programs startup with a texture, and then at runtime replace the texture with one of the users choosing from their HDD. Initializing the Texture works fine, and the initial texture displays as it should, being given a name by glGenTextures, and then binding the pixel data under that name. That is done in the following functions:

Texture::Texture(string filename)
{
//textureID[0]=0;


const char* fnPtr = filename.c_str(); //our image loader accepts a ptr to a char, not a string
//printf(fnPtr);


lodepng::load_file(buffer, fnPtr);//load the file into a buffer


unsigned error = lodepng::decode(image,w,h,buffer);//lodepng's decode function will load the pixel data into image vector from the buffer
//display any errors with the texture
if(error)
{
cout << "\ndecoder error " << error << ": " << lodepng_error_text(error) <<endl;
}
//execute the code that'll throw exceptions to do with the images size
checkPOT(w);
checkPOT(h);




//loop through and //printf our pixel data
/*for(GLuint i = 0; i<image.size(); i+=4)
{
//printf("\n%i,%i,%i,%i,", image.at(i),image.at(i+1),image.at(i+2),image.at(i+3));


}*/


////printf("\nImage size is %i", image.size());


//image now contains our pixeldata. All ready for OpenGL to do its thing


//let's get this texture up in the video memory
texGLInit();


Draw_From_Corner = CENTER; 
}

void Texture::texGLInit()
{
glGenTextures(1, &textureID[0]);
////printf("\ntextureID = %u", textureID[0]);

glBindTexture(GL_TEXTURE_2D, textureID[0]);//evrything we're about to do is about this texture
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8,w,h,0, GL_RGBA, GL_UNSIGNED_BYTE, &image[0]);
//we COULD free the image vectors memory right about now.
image.clear();
}
 

Upon calling my draw function this texture displays just fine. However, upon clicking "import new spritesheet", an openFileDialogue appears and the user selects a new file. The following code executes, which should (in theory) delete the texture name (stored in the GLUint 'TextureID' array), and make it available for use again, allowing us to bind new texture data under that name. 

void Texture::reloadTexture(string filename)
{
	//first and foremost clear the image and buffer vectors back down to nothing so we can start afresh 
	buffer.clear();
	image.clear();
	w = 0;
	h = 0;
	//also delete the texture name we were using before
	glDeleteTextures(1, &textureID[0]);

	const char* fnPtr = filename.c_str(); //our image loader accepts a ptr to a char, not a string
	//printf(fnPtr);

	lodepng::load_file(buffer, fnPtr);//load the file into a buffer

	unsigned error = lodepng::decode(image,w,h,buffer);//lodepng's decode function will load the pixel data into image vector from the buffer
	//display any errors with the texture
	if(error)
	{
		cout << "\ndecoder error " << error << ": " << lodepng_error_text(error) <<endl;
	}
	//execute the code that'll throw exceptions to do with the images size
	checkPOT(w);
	checkPOT(h);
	


	//loop through and //printf our pixel data
	/*for(GLuint i = 0; i<image.size(); i+=4)
	{
	//printf("\n%i,%i,%i,%i,", image.at(i),image.at(i+1),image.at(i+2),image.at(i+3));

	}*/

	////printf("\nImage size is %i", image.size());

	//image vector now contains our pixeldata. All ready for OGL to do its thing

	//let's get this texture up in the video memory OpenGL
	texGLSecondaryInit();

	Draw_From_Corner = CENTER;
}

void Texture::texGLSecondaryInit()
{
	//PFNGLBINDBUFFERARBPROC glBindBuffer = NULL;                  // VBO Bind Procedure
	

	glGenTextures(1, &textureID[0]);
	////printf("\ntextureID = %u", textureID[0]);

	glBindTexture(GL_TEXTURE_2D, textureID[0]);//evrything we're about to do is about this texture
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
	//glBindBuffer(GL_PIXEL_UNPACK_BUFFER,0);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8,w,h,0, GL_RGBA, GL_UNSIGNED_BYTE, &image[0]);
	
	//we COULD free the image vectors memory right about now.
	image.clear();
}

*Note the call to 'glDeleteTextures' close to the start of 'reloadTexture()'.*

What should happen at this point is that the user now sees their selected texture being displayed. But what actually happens is that the user sees the old texture (the one that loads at startup), with the new texture's (the one they selected) dimensions. Meaning that despite my call to glDeleteTextures, the deleted texture's pixel data still exists in one of openGL's buffers somewhereangry.png  I can't figure out where, nor why it would still be there after i have not only deleted it, but also attempted to bind a different files data over the top of it.

 

Thanks for reading, and I'd appreciate any light that could be shed on why openGL would hang-on to the old data.

 

P.S. In the function 'texGLSecondaryInit()' , you may notice commented out calls to glBindBuffer(). This was suggested to me as a way to purge the pixel buffer on another board. It caused Access Violation Errors all over the shop. However, I've left it on display here, in case it helps you understand what I'm trying and failing to do.

 

Share this post


Link to post
Share on other sites
BornToCode    1185

Are you use the that the pixel alignment is 1 in the texture you are trying to load. Also another thing you can do is put glGetError() between your call and see where it is failing.

Share this post


Link to post
Share on other sites
mhagain    13430

The only thing that glDeleteTextures promises is that the tetxure name will be available for reuse (via a subsequent call to glGenTextures); it doesn't promise that it will delete the pixel data, and the driver is perfectly free to keep that data hanging around for subsequent reuse.  This can be a good thing as the driver may be able to get away without having to allocate a new block of storage - "here's a block that's no longer being used, just hand it back".

 

So not deleting the pixel data is expected behaviour, but when you make the next call to glTexImage (assuming that you've bound the correct texture, of course) then the texture should be completely respecified.

 

The only sensible explanation here is that your glTexImage call is somehow failing.  As suggested, try a few glGetError calls and double-check your parameters.

 

Are you use the that the pixel alignment is 1 in the texture you are trying to load. Also another thing you can do is put glGetError() between your call and see where it is failing.

 

Check the glPixelStore call in the OP's code...

Share this post


Link to post
Share on other sites

I can't see why they wouldn't be. They're both .png files, loaded into openGL using the same image loader. They also both worked on a previous project using the virtually same setup. However in that old project, they were both created at the startup of my program as separate instances of my 'Texture' class. The reason I can't do that here, is because i wish for the user to be able to select a new texture at runtime from a file. 

 

Also placing glGetError after my glDeleteTextures call, returns no errors.  Like so.

void Texture::reloadTexture(string filename)
{
	//first and foremost clear the image and buffer vectors back down to nothing so we can start afresh 
	buffer.clear();
	image.clear();
	w = 0;
	h = 0;
	//also delete the texture name we were using before
	glDeleteTextures(1, &textureID[0]);

	GLenum err;
	while ((err = glGetError()) != GL_NO_ERROR) {
		printf("OpenGL error: %u", err);
	}


	const char* fnPtr = filename.c_str(); //our image loader accepts a ptr to a char, not a string
	//printf(fnPtr);

	lodepng::load_file(buffer, fnPtr);//load the file into a buffer

	unsigned error = lodepng::decode(image,w,h,buffer);//lodepng's decode function will load the pixel data into image vector from the buffer
	//display any errors with the texture
	if(error)
	{
		cout << "\ndecoder error " << error << ": " << lodepng_error_text(error) <<endl;
	}
	//execute the code that'll throw exceptions to do with the images size
	checkPOT(w);
	checkPOT(h);
	


	//loop through and //printf our pixel data
	/*for(GLuint i = 0; i<image.size(); i+=4)
	{
	//printf("\n%i,%i,%i,%i,", image.at(i),image.at(i+1),image.at(i+2),image.at(i+3));

	}*/

	////printf("\nImage size is %i", image.size());

	//image now contains our pixeldata. All ready for  to do its thing

	//let's get this texture up in the video memoryOpenGL
	texGLSecondaryInit();

	Draw_From_Corner = CENTER;
}

The same goes for after the call to glGenTextures in texGLSecondaryInit(). No errors to report.sad.png

Share this post


Link to post
Share on other sites

The only thing that glDeleteTextures promises is that the tetxure name will be available for reuse (via a subsequent call to glGenTextures); it doesn't promise that it will delete the pixel data, and the driver is perfectly free to keep that data hanging around for subsequent reuse.  This can be a good thing as the driver may be able to get away without having to allocate a new block of storage - "here's a block that's no longer being used, just hand it back".
 
So not deleting the pixel data is expected behaviour, but when you make the next call to glTexImage (assuming that you've bound the correct texture, of course) then the texture should be completely respecified.
 
The only sensible explanation here is that your glTexImage call is somehow failing.  As suggested, try a few glGetError calls and double-check your parameters.
 

Are you use the that the pixel alignment is 1 in the texture you are trying to load. Also another thing you can do is put glGetError() between your call and see where it is failing.

 
Check the glPixelStore call in the OP's code...

Ok, thanks v. Much. I wil try more and post results :)

Share this post


Link to post
Share on other sites

Ok I've done some further testing on this matter today. glGetErrors after my glTexImage2d call returns no errors. 

 

Even if, rather than changing the Texture via a call to:

myTex->reloadTexture("filename");

I just create a brand new one like so:

mytex = new Texture("filename");

 It still simply resizes the texture. 

 

Note: that this new method that I've tried means that glDeleteTextures would never even be called. Meaning that OGL would not free the TextureID (or Texture Name) in use for the first texture for re use, therefore openGL would give a unique name to the new Texture when the constructor was called.

 

Knowing this, I have observed the TextureID variable.

 

After the very first call to glGenTextures, textureID[0] = 1    |---->Seems normal.

 

After the myTex = new texture("filename"); call (which calls glGenTextures again), textureID[0] = 1    |----> Woah! hold it!!

 

At this point '1' should no longer be available as a unique texture name, as it was previously created for the first texture and glDeleteTextures was never called.

 

Can anybody tell me why glGenTextures would refuse to give me a unique name? Usually this problem comes because glGenTextures is called before a context is established, and glGenTextures gives you '0' as a name. But we know i have a legit context, as I draw to it!

 

Also, I have put glGetErrors as I have above after glGenTextures. No errors dry.png

Share this post


Link to post
Share on other sites

GOT IT! You see above, where i wrote:

 

"But we know i have a legit context, as I draw to it!"

 

Turns out I didn't. Let me explain.

 

In my program, I have TWO OpenGL views. Running on TWO OpenGL contexts. Which i must switch between using WGLMakeCurrent(), in order to make them both flush, swapbuffers individually.

 

The OpenGL view i refer to in this question, is the first to be made current. It has the first texture bound and then it is drawn. At this point the second OGL view is made current, has some stuff happen to it (not important), and then is drawn. 

 

So when I attempt to load and bind a second texture to my first openGL view, I've pulled the "old switcheroo" on myself and am trying to bind it to my second view's context (because it is current at this point). Which explains  why the first context still had the old pixel data in it. As I'd technically never called glDeletetextures on ittongue.png biggrin.png 

A quick call to wglMakeCurrent(handleInHere, parentwindowhere), before myTex->reloadTexture("filename") call, and my textures are loading and replacing themselves at my beckoned call.

 

Thanks for your previous help guys.  

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Similar Content

    • By pseudomarvin
      I assumed that if a shader is computationally expensive then the execution is just slower. But running the following GLSL FS instead just crashes
      void main() { float x = 0; float y = 0; int sum = 0; for (float x = 0; x < 10; x += 0.00005) { for (float y = 0; y < 10; y += 0.00005) { sum++; } } fragColor = vec4(1, 1, 1 , 1.0); } with unhandled exception in nvoglv32.dll. Are there any hard limits on the number of steps/time that a shader can take before it is shut down? I was thinking about implementing some time intensive computation in shaders where it would take on the order of seconds to compute a frame, is that possible? Thanks.
    • By Arulbabu Donbosco
      There are studios selling applications which is just copying any 3Dgraphic content and regenerating into another new window. especially for CAVE Virtual reality experience. so that the user opens REvite or CAD or any other 3D applications and opens a model. then when the user selects the rendered window the VR application copies the 3D model information from the OpenGL window. 
      I got the clue that the VR application replaces the windows opengl32.dll file. how this is possible ... how can we copy the 3d content from the current OpenGL window.
      anyone, please help me .. how to go further... to create an application like VR CAVE. 
       
      Thanks
    • By cebugdev
      hi all,

      i am trying to build an OpenGL 2D GUI system, (yeah yeah, i know i should not be re inventing the wheel, but this is for educational and some other purpose only),
      i have built GUI system before using 2D systems such as that of HTML/JS canvas, but in 2D system, i can directly match a mouse coordinates to the actual graphic coordinates with additional computation for screen size/ratio/scale ofcourse.
      now i want to port it to OpenGL, i know that to render a 2D object in OpenGL we specify coordiantes in Clip space or use the orthographic projection, now heres what i need help about.
      1. what is the right way of rendering the GUI? is it thru drawing in clip space or switching to ortho projection?
      2. from screen coordinates (top left is 0,0 nd bottom right is width height), how can i map the mouse coordinates to OpenGL 2D so that mouse events such as button click works? In consideration ofcourse to the current screen/size dimension.
      3. when let say if the screen size/dimension is different, how to handle this? in my previous javascript 2D engine using canvas, i just have my working coordinates and then just perform the bitblk or copying my working canvas to screen canvas and scale the mouse coordinates from there, in OpenGL how to work on a multiple screen sizes (more like an OpenGL ES question).
      lastly, if you guys know any books, resources, links or tutorials that handle or discuss this, i found one with marekknows opengl game engine website but its not free,
      Just let me know. Did not have any luck finding resource in google for writing our own OpenGL GUI framework.
      IF there are no any available online, just let me know, what things do i need to look into for OpenGL and i will study them one by one to make it work.
      thank you, and looking forward to positive replies.
    • By fllwr0491
      I have a few beginner questions about tesselation that I really have no clue.
      The opengl wiki doesn't seem to talk anything about the details.
       
      What is the relationship between TCS layout out and TES layout in?
      How does the tesselator know how control points are organized?
          e.g. If TES input requests triangles, but TCS can output N vertices.
             What happens in this case?
      In this article,
      http://www.informit.com/articles/article.aspx?p=2120983
      the isoline example TCS out=4, but TES in=isoline.
      And gl_TessCoord is only a single one.
      So which ones are the control points?
      How are tesselator building primitives?
    • By Orella
      I've been developing a 2D Engine using SFML + ImGui.
      Here you can see an image
      The editor is rendered using ImGui and the scene window is a sf::RenderTexture where I draw the GameObjects and then is converted to ImGui::Image to render it in the editor.
      Now I need to create a 3D Engine during this year in my Bachelor Degree but using SDL2 + ImGui and I want to recreate what I did with the 2D Engine. 
      I've managed to render the editor like I did in the 2D Engine using this example that comes with ImGui. 
      3D Editor preview
      But I don't know how to create an equivalent of sf::RenderTexture in SDL2, so I can draw the 3D scene there and convert it to ImGui::Image to show it in the editor.
      If you can provide code will be better. And if you want me to provide any specific code tell me.
      Thanks!
  • Popular Now