问题描述
我正在尝试应用本文中描述的解决方案(实际上不是解决方案,而是第一个答案):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);
renderBlocks(GL_QUADS);
glDepthFunc(GL_LEQUAL);
glColorMask(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,1); glVertex2f(100,100);
glTexCoord2d(0,1); glVertex2f(50,100);
glEnd();
glBegin(type);
glColor4f(0.5f,0); glVertex2f(75,75);
glTexCoord2d(1,0); glVertex2f(150,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);
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);
我得到的结果是: Squares are overlapping
我想要的结果: Squares (with alpha 0.5) not overlapping
有人知道我在做什么错吗? 谢谢!
解决方法
您的解决方案将不起作用,因为所有四边形都具有相同的深度(z = 0.0),并且深度测试功能为GL_LEQUAL
。链接问题的答案中明确提到(How to avoid transparency overlap using OpenGL?):
您将需要为每个圆分配不同的z值。 [...]。
如果blend函数为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,1); glVertex3f(100,100,z);
glTexCoord2d(0,1); glVertex3f(50,z);
glEnd();
z -= 0.1f;
glBegin(type);
glColor4f(0.5f,0); glVertex3f(75,75,0); glVertex3f(150,1); glVertex3f(150,150,1); glVertex3f(75,z);
glEnd();
}