31

我正在研究二维引擎。它已经工作得很好,但我不断收到像素错误。

例如,我的窗口是 960x540 像素,我画了一条从 (0, 0) 到 (959, 0) 的线。我希望扫描线 0 上的每个像素都将设置为一种颜色,但不是:最右边的像素没有被绘制。当我垂直绘制到像素 539 时,同样的问题。我真的需要绘制到 (960, 0) 或 (0, 540) 来绘制它。

由于我出生在像素时代,我坚信这不是正确的结果。当我的屏幕为 320x200 像素大时,我可以从 0 到 319 以及从 0 到 199 进行绘制,我的屏幕将是满的。现在我最终得到了一个未绘制右/下像素的屏幕。

这可能是由于不同的原因:我期望opengl线原语从一个像素绘制到一个包含像素的像素,最后一个像素实际上是独占的?是这样吗?我的投影矩阵不正确?我有一个错误的假设,即当我有一个 960x540 的后备缓冲区时,实际上还有一个像素?还有什么?

有人可以帮帮我吗?我一直在研究这个问题很长时间,每次我认为没问题的时候,我发现它实际上不是。

这是我的一些代码,我试图尽可能地精简它。当我调用我的 line-function 时,每个坐标都添加了 0.375、0.375 以使其在 ATI 和 nvidia 适配器上都正确。

int width = resX();
int height = resY();

for (int i = 0; i < height; i += 2)
    rm->line(0, i, width - 1, i, vec4f(1, 0, 0, 1));
for (int i = 1; i < height; i += 2)
    rm->line(0, i, width - 1, i, vec4f(0, 1, 0, 1));

// when I do this, one pixel to the right remains undrawn

void rendermachine::line(int x1, int y1, int x2, int y2, const vec4f &color)
{
    ... some code to decide what std::vector the coordinates should be pushed into
    // m_z is a z-coordinate, I use z-buffering to preserve correct drawing orders
    // vec2f(0, 0) is a texture-coordinate, the line is drawn without texturing
    target->push_back(vertex(vec3f((float)x1 + 0.375f, (float)y1 + 0.375f, m_z), color, vec2f(0, 0)));
    target->push_back(vertex(vec3f((float)x2 + 0.375f, (float)y2 + 0.375f, m_z), color, vec2f(0, 0)));
}

void rendermachine::update(...)
{
    ... render target object is queried for width and height, in my test it is just the back buffer so the window client resolution is returned
    mat4f mP;
    mP.setOrthographic(0, (float)width, (float)height, 0, 0, 8000000);

    ... all vertices are copied to video memory

    ... drawing
    if (there are lines to draw)
        glDrawArrays(GL_LINES, (int)offset, (int)lines.size());

    ...
}

// And the (very simple) shader to draw these lines

// Vertex shader
    #version 120
    attribute vec3 aVertexPosition;
    attribute vec4 aVertexColor;
    uniform mat4 mP;
    varying vec4 vColor;
    void main(void) {
        gl_Position = mP * vec4(aVertexPosition, 1.0);
        vColor = aVertexColor;
    }

// Fragment shader
    #version 120
    #ifdef GL_ES
    precision highp float;
    #endif
    varying vec4 vColor;
    void main(void) {
        gl_FragColor = vColor.rgb;
    }
4

2 回答 2

17

在 OpenGL 中,使用“钻石出口”规则对线条进行光栅化。这和说结束坐标是独占的差不多,但不完全是……

这就是 OpenGL 规范必须说的: http ://www.opengl.org/documentation/specs/version1.1/glspec1.1/node47.html

还可以查看 OpenGL 常见问题解答,http://www.opengl.org/archives/resources/faq/technical/rasterization.htm,项目“14.090 如何获得线条的精确像素化?”。它说“OpenGL 规范允许使用广泛的线渲染硬件,因此可能根本无法实现精确的像素化。”

许多人会争辩说你根本不应该在 OpenGL 中使用线条。他们的行为是基于古代 SGI 硬件的工作方式,而不是基于什么是有意义的。(宽度 >1 的线条几乎不可能以看起来不错的方式使用!)

于 2012-04-06T09:29:50.060 回答
7

请注意,OpenGL 坐标空间没有整数的概念,一切都是浮点数,OpenGL 像素的“中心”实际上是在 0.5,0.5 而不是左上角。因此,如果你想要一条从 0,0 到 10,10 的 1px 宽的线,你真的必须画一条从 0.5,0.5 到 10.5,10.5 的线。

如果您打开抗锯齿,这一点尤其明显,如果您有抗锯齿并且您尝试从 50,0 到 50,100 绘制,您可能会看到一条模糊的 2px 宽线,因为该线位于两个像素之间。

于 2012-04-06T08:35:00.467 回答