Read me About Demoscene? Links Contact

Render to texture

Hi folks,

this is the first posting in a series of visual coding tricks. The first one is a primitive render to texture function that I often use. Rendering to textures can be used in a multitude of post processing effects - e.g. blur, radial blur, zoom blur, glow, etc. 

Rendering to a texture is done as follows for each frame:

  1. Set up view port to fit the dimensions of the texture (Prepare)
  2. Render your frame
  3. Copy the data in to the texture (Finish)
  4. Reset the view port to its original dimensions

Please note that this method requires that all render to texture passes are done on a blank screen before anything else is processed. This is due to the fact that we simply render the frame in a small corner of the actual screen before copying it to the texture. There are other ways of doing this which are faster, however they all requires extensions beyond OpenGL 1.1.

Below is the source code for render to texture functionality:



#define XX 512

unsigned int texture_id;

static unsigned char texture[3 * XX * XX];

void Init()

{

glEnable(GL_TEXTURE_2D);

glGenTextures(1, &texture_id);

glBindTexture(GL_TEXTURE_2D, texture_id);

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, XX, XX, 0, GL_RGB, GL_UNSIGNED_BYTE, texture);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

}



void Prepare()

{

glMatrixMode(GL_PROJECTION);

glViewport(0, 0, XX, XX);

glMatrixMode(GL_MODELVIEW);

}



void Finish()

{

glBindTexture(GL_TEXTURE_2D, texture_id);

glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, XX, XX);

}