views:

6074

answers:

2

I have been having trouble finding straightforward code to render a scene to a texture in OpenGL ES (specifically for the iPhone, if that matters). I am interested in knowing the following:

  1. How do you render a scene to a texture in OpenGL ES?
  2. What parameters must you use to create a texture that is capable of being a render target in OpenGL ES?
  3. Are there any implications with applying this rendered texture to other primitives?
+13  A: 

This is how I'm doing it.

I define a texture variable (I use Apple's Texture2D class, but you can use an OpenGL texture id if you want), and a frame buffer:

Texture2d * texture;
GLuint textureFrameBuffer;

Then at some point, I create the texture, frame buffer and attach the renderbuffer. This you only need to do it once:

texture = [[Texture2D alloc] initWithData:0 
                             pixelFormat:kTexture2DPixelFormat_RGB888
                             pixelsWide:32
                             pixelsHigh:32
                             contentSize:CGSizeMake(width, height)];

// create framebuffer
glGenFramebuffersOES(1, &textureFrameBuffer);
glBindFramebufferOES(GL_FRAMEBUFFER_OES, textureFrameBuffer);

// attach renderbuffer
glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, texture.name, 0);

// unbind frame buffer
glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);

Every time I want to render to the texture, I do:

glBindFramebufferOES(GL_FRAMEBUFFER_OES, textureFrameBuffer);

...
// GL commands
...

glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);

About your question 3, that's it, you can use the texture as if it is any other texture.

Marco Mustapic
Marco, do you know how much overhead is involved in keeping a framebuffer and renderbuffer for each texture you need to render into? I have several large textures my app needs to draw into, and I'm currnetly attaching different ones to a single "extra" framebuffer using glFramebufferTexture2DOES. Would keeping a separate framebuffer for each be better?
Ben Gotow
Could you please edit your code so that initWithData:... call fits in without scrolling?
nornagon
Ok, edited, looks better now.
Marco Mustapic
A: 

Changing initWithData to initWithString will it work to draw text?

António
is this a new question? (btw, nice profile pic!)
Andrew Garrison
Yes... I cant put Texture2D working right... A do all step and all a got is a blank square....
António