Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

ios - OpenGL ES 2.0 render to texture

I'm trying to render to a texture using OpenGL ES 2.0, but I can't seem to make it work.

This is how I proceed:

    struct RenderTexture
    {
        GLuint framebuffer;
        GLuint tex;
        GLint old_fbo;


        RenderTexture(GLuint width, GLuint height)
        {
            glGetIntegerv(GL_FRAMEBUFFER_BINDING, &old_fbo);

            glGenFramebuffers(1, &framebuffer);
            glGenTextures(1, &tex);

            glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
            glBindTexture(GL_TEXTURE_2D, tex);
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 
                         width, height, 0, GL_RGBA, 
                         GL_UNSIGNED_BYTE, NULL);
            glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 
                                   tex, 0);

            glClearColor(1, 0, 0, 1);
            glClear(GL_COLOR_BUFFER_BIT);

            GLuint status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
            if (status != GL_FRAMEBUFFER_COMPLETE) {
                cout << status << endl; // this is not called
            }

            glBindFramebuffer(GL_FRAMEBUFFER, old_fbo);
        }

        void begin()
        {
            glGetIntegerv(GL_FRAMEBUFFER_BINDING, &old_fbo);
            glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
        }

        void end()
        {
            glBindFramebuffer(GL_FRAMEBUFFER, old_fbo);
        }
    };

But when I try drawing on it and using the resulting texture, the texture is drawn as totally black.

If I just don't wrap the drawing code in render_tex->begin(); and render_tex->end();, everything draws correctly, leading me to believe that the problem is isolated to the code above.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Make sure the texture is not bound before trying to render into it. Even if not using texturing at all, trying to render into a currently bound texture may invoke undefined behaviour and just not work.

You should actually call glBindTexture(GL_TEXTURE_2D, 0) after the glTexImage2D in your RenderTexture constructor, or maybe restore the previously bound texture, like you do with the FBO. Just make sure the tex is not bound when you render into the FBO.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...