glDepthTest 问题(alpha 重叠)

glDepthTest troubles (alpha overlapping)

我正在尝试应用此 post 中描述的解决方案(实际上不是解决方案而是第一个答案):How to avoid transparency overlap using OpenGL? 同样的问题。

我尝试了一个最小的项目,但我不知道为什么它不起作用,这是我的渲染循环代码:

private void render() {
    glClear(GL_DEPTH_BITS);
    glClear(GL_COLOR_BUFFER_BIT);

    glDepthFunc(GL_ALWAYS);
    glColorMask(false, false, false, false);
    renderBlocks(GL_QUADS);

    glDepthFunc(GL_LEQUAL);
    glColorMask(true, true, true, true);
    renderBlocks(GL_QUADS);
}

渲染块函数:

public void renderBlocks(int type) {
    glBegin(type);
    glColor4f(0.5f, 1f, 0f, 0.5f);
    glTexCoord2d(0, 0); glVertex2f(50, 50);
    glTexCoord2d(1, 0); glVertex2f(100, 50);
    glTexCoord2d(1, 1); glVertex2f(100, 100);
    glTexCoord2d(0, 1); glVertex2f(50, 100);
    glEnd();
    glBegin(type);
    glColor4f(0.5f, 1f, 0f, 0.5f);
    glTexCoord2d(0, 0); glVertex2f(75, 75);
    glTexCoord2d(1, 0); glVertex2f(150, 75);
    glTexCoord2d(1, 1); glVertex2f(150, 150);
    glTexCoord2d(0, 1); glVertex2f(75, 150);
    glEnd();
}

还有我的openGL初始化

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    GLU.gluOrtho2D(0, width, height, 0);
    glMatrixMode(GL_MODELVIEW);

    glClearColor(0, 0, 0, 0);
    glEnable(GL_TEXTURE_2D);
    glEnable(GL_BLEND);
    glEnable(GL_DEPTH_TEST);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glClearColor (0.0f, 0.0f, 0.0f, 0.0f);

我得到的结果: Squares are overlapping

我想要的结果: Squares (with alpha 0.5) not overlapping

有人知道我做错了什么吗? 谢谢!

您的解决方案将不起作用,因为所有四边形都具有相同的深度 (z=0.0) 并且深度测试函数是 GL_LEQUAL。链接问题的答案中明确提到 (How to avoid transparency overlap using OpenGL?):

You are going to need to assign to each circle a different z value. [...].

如果混合函数是glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA),它在alpha = 0.5的情况下有效,因为x * 0.5 + x * 0.5 = x.

渲染具有不同 z 坐标的块以解决问题:

public void renderBlocks(int type) {

    float z = 0.0;

    glBegin(type);
    glColor4f(0.5f, 1f, 0f, 0.5f);
    glTexCoord2d(0, 0); glVertex3f(50, 50, z);
    glTexCoord2d(1, 0); glVertex3f(100, 50, z);
    glTexCoord2d(1, 1); glVertex3f(100, 100, z);
    glTexCoord2d(0, 1); glVertex3f(50, 100, z);
    glEnd();

    z -= 0.1f;

    glBegin(type);
    glColor4f(0.5f, 1f, 0f, 0.5f);
    glTexCoord2d(0, 0); glVertex3f(75, 75, z);
    glTexCoord2d(1, 0); glVertex3f(150, 75, z);
    glTexCoord2d(1, 1); glVertex3f(150, 150, z);
    glTexCoord2d(0, 1); glVertex3f(75, 150, z);
    glEnd();
}