【问题标题】:glDepthTest troubles (alpha overlapping)glDepthTest 问题(alpha 重叠)
【发布时间】:2020-11-04 18:05:51
【问题描述】:

我正在尝试应用这篇文章中描述的解决方案(实际上不是解决方案,而是第一个答案):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。在链接问题的答案中明确提到:“您将需要为每个圆圈分配不同的 z 值。[...]”
  • @Rabbid76 openGL不会自动分配z值吗?在我的主要项目中,我有很多对象而不是 2 个立方体,我需要指定每个 z 值吗?
  • 是的,默认情况下 z 为 0.0。然而,对于解决方案,每个四边形的 z 必须不同。
  • 好的,非常感谢!我不清楚!

标签: opengl lwjgl opengl-compat


【解决方案1】:

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

您需要为每个圆圈分配不同的 z 值。 [...]。

如果混合函数为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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 1970-01-01
    相关资源
    最近更新 更多