opengl-esglslshaderopengl-es-2.0glreadpixels

How to draw the data (from gleReadPixels) onto the default (display) farmebuffer in OpenGLES 2.0


Sorry if I am asking something which is already available. So far I could not trace. I read details about FBO and got a fair idea about off-screen buffering. http://mattfife.com/?p=2813 is a nice little article on FBOs. In all the examples, including this one, I don't see details on how to write the data, retrieved through glReadPixels call, onto default display framebuffer. Sorry if I am missing anything silly. I did my due diligence but could not get any example.

Note: I am using OpenGLES 2.0, hence I cannot use calls such as glDrawPixels, etc.

Basically my requirement is to have off-screen buffering. Because I am working on subtitle/captions wherein scrolling of the caption will have to repeat the rendering of lines till those go out of caption-display area.

I got a suggestion to use FBO and bind the texture created to the main default framebuffer.

My actual need is caption/ subtitle (which can be in scrolling mode) Suppose the first time I had below on display, This is Line Number - 1 This is Line Number - 2 This is Line Number - 3

After scrolling, then I want to have, This is Line Number - 2 This is Line Number - 3 This is Line Number - 4

In the second time when I want to render, I will have to update the content in offscreen FBO? That would be re-writing line-2 and line-3 at a new position, removing line-1 and adding line-4.


Solution

  • Create a framebuffer with an texture attachment (see Attaching Images). Note glFramebufferTexture2D is supported by OpenGL ES 2.0.
    The color plane of the framebuffer can be loaded to the CPU by glReadPixels, the same way as when you use a Renderbuffer. But the rendering is stored in a 2D Texture.
    Bind the texture and the default framebuffer and render a screen space quad with the texture on it.

    Render a quad (GL_TRIANLGE_FAN) with the vertex coordinates (-1, -1), (1, -1), (1, 1), (-1, 1) and use the following simple OpenGL ES 2.0 shader:

    Vertex shader

    attribute vec2 pos;
    varying vec2 uv;
    
    void main()
    {
        uv = pos * 0.5 + 0.5;
        gl_Position = vec4(pos, 0.0, 1.0);
    }
    

    Fragment shader

    precision mediump float;
    
    varying vec2 uv;
    uniform sampler2D u_texture;
    
    void main()
    {
        gl_FragColor = texture2D(u_texture, uv);
    }