OpenGL渲染到纹理坐标

时间:2012-05-07 17:53:22

标签: java opengl render-to-texture projection-matrix

我希望能够渲染到纹理(对于着色器,字体),但是我有一个问题是正确定位四边形(帧缓冲本身会做它应该做的事情)。生成的(复制的)纹理在大多数情况下显示左上角,其余的被裁剪。这对于矩形纹理来说更糟糕,对方形纹理几乎没有影响(所以我好几天都没有认识到这种行为)

示例代码:

    public Texture copy(final Texture tex) {
    final int tempTex = glGenTextures();
    Draw.bindTexture(tempTex);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex.getImageWidth(), tex.getImageHeight(), 0, GL_RGB, GL_UNSIGNED_BYTE, (ByteBuffer)null);

    // Adjust projection matrix
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    glViewport(0, 0, tex.getImageWidth(), tex.getImageHeight());

    // Change blendmode to ignore the transparent background
    Draw.blendingMode(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

    // Prepare fbo, add the texture as backend and clear it
    final int fbo = glGenFramebuffers();
    glBindFramebuffer(GL_FRAMEBUFFER, fbo);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tempTex, 0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // Finally draw
    Draw.bindTexture(tex.getId());
    glBegin(GL_QUADS);
    {
        glTexCoord2f(0, 0);
        glVertex2f(-1, -1);
        glTexCoord2f(1, 0);
        glVertex2f(1, -1);
        glTexCoord2f(1, 1);
        glVertex2f(1, 1);
        glTexCoord2f(0, 1);
        glVertex2f(-1, 1);
    }
    glEnd();

    // Unbind framebuffer
    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    // Reset projection matrix
    glViewport(0, 0, 1920, 1080); // TODO Don't hardcode
    glPopMatrix();

    return new Texture(tempTex, tex.getImageWidth(), tex.getImageHeight());
}

示例图片:

enter image description here

鞋面是渲染的原始图像,低于复制版本

我做错了什么?


更新:现在看起来纹理被下采样

enter image description here

2 个答案:

答案 0 :(得分:1)

您不应将实际纹理宽度和高度传递到texcoords中。纹理坐标范围从0(底部和左侧)到1(顶部和右侧)。您不会将实际纹理尺寸硬编码到纹理坐标中。

尝试用“1”

替换texcoord函数中的getWidth / getHeight

答案 1 :(得分:0)

最好的方法是,使用尺寸与显示器相同的正投影矩阵(1920x1080)。你的纹理必须是2 pow大小的纹理,所以你必须使它2048x2048。如果现在将结果渲染到纹理的矩形(不适合整个纹理),则可以在屏幕上使用相同的矩阵渲染它。 (像素正确)