5

I'm generating a texture on the GPU and rendering it to my own framebuffer object. It works fine and the texture is rendered to a WebGLTexture that I can pass to other shaders. However I want to access the WebGLTexture pixels in javascript. Is there a way to accomplish that?

At the moment I'm using gl.ReadPixels to read the pixels after I've drawn the texture to my framebuffer. That works fine but wouldn't it be better if I could directly access the pixels in the WebGLTextureObject?

What I'm trying to accomplish is this: I have GLSL perlin noise shader that can render high def heightmap and normal map on the GPU. I want to pass the heightmap to the CPU so that I can generate the vertices for the mesh. I could of course just position the vertices in the vertex shader but I need it in the CPU for collision detection.

I hope my question is clear. Any feedback is welcome!

Thanks!

Jón Trausti Arason
  • 4,548
  • 1
  • 39
  • 46
  • i think this is the only solution because `glGetTexImage`does not exist. but anyway, i don't think that this is a bad solution. Probably you should think of, if it is possible to do the collision detection on GPU. – t.niese Feb 24 '13 at 23:34

1 Answers1

12

You can read the pixels out of most textures by attaching them to a framebuffer.

var fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) == gl.FRAMEBUFFER_COMPLETE) {
  var pixels = new Uint8Array(width * height * 4);
  gl.readPixels(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
}
gman
  • 100,619
  • 31
  • 269
  • 393
  • 1
    That's what I'm currently doing as I described in my question. I'm wondering if there's alternative way, such as reading straight from the WebGLTexture. Thanks. – Jón Trausti Arason Feb 25 '13 at 19:10
  • Okay, that wasn't clear from your description. "I've drawn the texture to my framebuffer". You don't have to draw the texture. You only have to attach the texture to a framebuffer and then call readPixels. Sorry for the mis-understanding. There is no other direct way in WebGL. – gman Feb 26 '13 at 05:04
  • 1
    Ok thanks a lot! :-) You might want to update your answer and state that there's no other direct way available in WebGL (for others). – Jón Trausti Arason Feb 26 '13 at 21:09