LWJGL - 渲染到帧缓冲区显示错误的结果

时间:2014-08-21 21:55:33

标签: java opengl lwjgl framebuffer render-to-texture

我正在尝试将所有渲染渲染到帧缓冲区而不是后缓冲区,同时使用LWJGL。
我为图形做了以下事情 设置显示并设置OpenGL:

    try {
        Display.setDisplayMode(new DisplayMode(1024, 768));
        Display.create();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(0);
    }
    Display.setTitle(WINDOW_NAME);

    GL11.glMatrixMode(GL11.GL_PROJECTION);
    GL11.glLoadIdentity();
    GL11.glOrtho(0, 1024, 0, 768, 1, -1);
    GL11.glMatrixMode(GL11.GL_MODELVIEW);

然后我创建一个framebuffer对象:

    m_width = p_width;
    m_height = p_height;


    m_frameBufferObject = glGenFramebuffersEXT();
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_frameBufferObject);
    m_depthBuffer = glGenRenderbuffersEXT();
    glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, m_depthBuffer);
    glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, p_width, p_height);

    glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_depthBuffer);
    m_frameBufferTexture = glGenTextures();
    glBindTexture(GL_TEXTURE_2D, m_frameBufferTexture);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, p_width, p_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, (java.nio.ByteBuffer)null);
    glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, m_frameBufferTexture, 0);

然后像这样完成渲染(目前我只尝试绘制一个像素):

    // Bind the framebuffer object.
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_frameBufferObject);
    glPushAttrib(GL_VIEWPORT_BIT);
    glViewport(0, 0, m_width, m_height);
    GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);  

    // Clear with black
    GL11.glColor3f(0.0f, 0.0f, 0.0f);

    GL11.glBegin(GL11.GL_POINTS);
    setOpenGLColour(new Colour(Colour.RED));
    GL11.glVertex2f(100, 100);
    GL11.glEnd();

    //Deactivate the framebuffer object
    glPopAttrib();
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);

    //Render the framebuffer object to the screen
    GL11.glBegin(GL11.GL_QUADS);
    GL11.glTexCoord2f(0f, 0f);
    GL11.glVertex2f(0, 0);
    GL11.glTexCoord2f(1f, 0f);
    GL11.glVertex2f(1024, 0); 
    GL11.glTexCoord2f(1f, 1f);
    GL11.glVertex2f(1024, 768);
    GL11.glTexCoord2f(0f, 1f);
    GL11.glVertex2f(0, 768);
    GL11.glEnd();

问题是:现在整个屏幕都是红色的。不仅仅是一个红色像素,而是整个屏幕都是红色的。如果我不绘制像素,那么屏幕就是黑色 有人可以告诉我我可能做错了什么,或者这样做是怎么回事?

1 个答案:

答案 0 :(得分:1)

当您尝试将FBO渲染结果复制到屏幕时,您似乎没有获得纹理。由于您将当前绘制颜色设置为红色,因此只需将屏幕尺寸四边形绘制为红色。

我看到的一件事是从未启用纹理。在开始最终绘制命令之前添加它:

glEnable(GL_TEXTURE_2D);

纹理也需要绑定,这通常会在绘制函数期间发生。但是,由于您在设置过程中绑定了纹理,并且从未对其进行解除绑定,因此该部分很可能不会导致问题。