SteinSOFT.net
  Drawing to a texture

I am using OpenGL - like many other - because it is very straight forward and easy to use. Even complex operations can be done very easily and the code will never become really messy. And once again this can be proved when drawing a scene to an OpenGL texture. So why actually want to do something like that? There is one situation where this technique is very important. I assume everyone knows the "traditional" method of drawing reflections - flip matrix around reflection surface and draw object again. But what if the reflection surface is curved or simply not a normal plane. The answer: draw the scene to a texture and map it onto the curved surface. Easy, eh?

So let's quickly jump into the code. First we have to create an empty texture. Do this somewhere in your initialization code. The texture will be created using an empty colour array:

int xSize = 256, ySize = 256; //size of texture
//our OpenGL texture handle
unsigned int texture;
//new array
char* colorBits = new char[ xSize * ySize * 3 ];

//texture creation..
glGenTextures(1,&texture);
glBindTexture(GL_TEXTURE_2D,texture);

glTexImage2D(GL_TEXTURE_2D,0 ,3 , xSize,
	ySize, 0 , GL_RGB, 
	GL_UNSIGNED_BYTE, colorBits);

//you can set other texture parameters if you want
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER, GL_LINEAR);

//clean up
delete[] colorBits;

Our texture is now created and ready to use. Note that the initial colour array isn't initialized because it doesn't matter as it will be overwritten later on. Now comes the interesting part. Before drawing to the texture, we will save the current viewport and change it to the size of the texture. Then we'll draw the scene that should fill the texture and we'll copy the scene colour data to the texture using glCopyTexImage2D(..). Last but not least we'll restore the old viewport. The code:

//save viewport and set up new one
int viewport[4];
glGetIntegerv(GL_VIEWPORT,(int*)viewport);
glViewport(0,0,xSize,ySize);

//draw a misc scene
DrawScene();

//save data to texture using glCopyTexImage2D
glBindTexture(GL_TEXTURE_2D,texture);

glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
   0,0, xSize, ySize, 0);

//restore viewport
glViewport(viewport[0],viewport[1],viewport[2],viewport[3]);

Now we'll have our scene stored exactely in our texture. This texture can be used like any other texture loaded from file. glBindTexture(GL_TEXTURE, texture) will do the thing. If you want it even easier, try SRenderTexture from the code section. If you have questions, ask them in message board. Happy Coding!

Copyright © by SteinSOFT