How to render to a Texture

Hi,

I want to create a Texture at runtime. I found
some good examples for that, if you want to
render 3D stuff.

I just want to draw some 2D polygons to a texture
and than use it in 3D to texture a quad.

I tried something the following, but there’s
no texture displayed only a black quad.

CreateRenderTexture is called once at programmstart and display is my paint-func.

void CreateRenderTexture(void)
{
unsigned int *pTexture = NULL;

pTexture = new unsigned int [256 * 256 * 3];

memset(pTexture, 0, 256 * 256 * 3 *
sizeof(unsigned int));

glGenTextures(1, &TextureID);
glBindTexture(GL_TEXTURE_2D, TextureID);
glTexImage2D(GL_TEXTURE_2D, 0, 3, 256, 256, 0,
GL_RGB, GL_UNSIGNED_INT, pTexture);
glTexParameteri(GL_TEXTURE_2D,
GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,
GL_TEXTURE_MAG_FILTER,GL_LINEAR);

delete [] pTexture;
}

void display (void)
{
/*
render texture
*/
glDisable (GL_DEPTH_TEST);
glEnable(GL_TEXTURE_2D);

glViewport (0, 0, 256, 256);

glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);

glBegin(GL_POLYGON);
glColor3f(0, 0, 0);

// draw stuff with glVertex2f

glEnd ();

glBindTexture(GL_TEXTURE_2D,TextureID);
glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 0, 0, 256, 256, 0);

/*
render scene
*/
glViewport (0, 0, width, height);

glEnable (GL_DEPTH_TEST);
glDepthFunc(GL_LESS);

glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glBindTexture(GL_TEXTURE_2D, TextureID);

glBegin(GL_QUADS);
glTexCoord2f( 1, 0.0f);
glVertex3f(20, 20, 0);

glTexCoord2f( 1, 1);
glVertex3f(20, height - 20, 0);

glTexCoord2f(0.0f, 1);
glVertex3f(width - 20, height - 20, 0);

glTexCoord2f(0.0f, 0.0f);
glVertex3f(width - 20, 20, 0);
glEnd();

glutSwapBuffers ();
}

Any ideas ?

Andre

did you create the texture after opengl has been initialized? you have to.

also, did you enable GL_TEXTURE_2D before you create the render texture? check the gl error strings to see if they report any errors…

Take a look at section 3.8.13 of the opengl reference manual.

The initial state of the texture environments are set to GL_MODULATE. This means that the resulting color is a componentwise multiplication of the texture color and the specified glColor(). Because you set the color3f(0,0,0) the resulting color will always be black.

PS: in case of multitexturing it’s a little more complicated

You can resolve the problem in 2 ways:

  • Set color4f(1.0,1.0,1.0,1.0)
  • Set the texture environment mode to GL_REPLACE

N.