I am currently trying to take snapshots of an OpenGL rendered 3D world at various camera positions and varying image resolution using glReadPixels. I have two choices for th
Doing high resolution renderings with OpenGL is a bit tricky. One problem is, that pixel ownership tests get in the way. The other are the maximum size for a framebuffer (object). The first problem can be overcome by using a framebuffer object or a PBuffer.
The second requires some trickery: Let's say we want to render an image of size W×H, where W and H exceed the maximum framebuffer size; glGetInteger
of the tokens GL_MAX_VIEWPORT_SIZE, GL_MAX_TEXTURE_SIZE, GL_MAX_RENDERBUFFER_SIZE gives you those limits. So what you have to do is split up the target image into tiles smaller than those limits, render those tiles and then recombine them. Let's say W_t and H_t are the tile sizes, W_t := W / N
, H_t := H / M
and we have an accordingly sized PBuffer or Framebuffer object. Then we can render those tiles with a 2-loop:
for m in 0 to M: for n in 0 to N:
render_tile(n, m)
So how does render_tile(n,m)
look like?
render_tile(n,m):
Apparently we're using the whole tile as renderbuffer so
glViewport(0, 0, W_t, H_t)
so what changes is the projection. Somehow we've to shift the projection along with the tile in the projection plane. The projection plane is also known as the 'near' plane. The extents of the near plane are right - left
and top - bottom
, so we're splitting the near plane into tiles of size (right - left) / N
×(top - bottom) / M
so that's what we need to use as shift step size:
shift_X = (right - left) / N
shift_Y = (top - bottom) / M
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
switch Projection:
case Ortho:
glOrtho( left + shift_X * n, left + shift_X * (n+1),
bottom + shift_Y * m, bottom + shift_Y * (n+1),
near, far)
case Perspective:
glFrustum( left + shift_X * n, left + shift_X * (n+1),
bottom + shift_Y * m, bottom + shift_Y * (n+1),
near, far)
render_scene()
And just in case how we get left, right, top, bottom
for perspective:
right = -0.5 * tan(fov) * near
left = -right;
top = aspect * right
bottom = -top