Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly render coincident polygons in OpenGL (ES)

I understand that by setting the depth function in OpenGL ES one can control how overlapping geometries are rendered in a 3D scene. I use gl.depthFunc(gl.LEQUAL) (webgl) in my code.

However when two sets of polygons are coincident and are of different color, the resulting surface turns out to be an arbitrary mixed pattern of the two colors (which changes as the camera location changes, hence leads to flickering). Take a look at this image:

enter image description here

How can I fix this? I have tried different depthFunc values, but none of them solves this problem. I would like the coincident polygons to have single color, it doesn't matter which one.

like image 527
Jayesh Avatar asked Oct 20 '11 12:10

Jayesh


2 Answers

This is called z-fighting, and is related to two objects being rendered at the same depth, but rounding errors (and depth buffer precision) occasionally popping one in front of the other. One solution available to you is to use the glPolygonOffset function:

http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPolygonOffset.xml

You can see an example of it in use at the bottom of this page:

http://www.glprogramming.com/red/chapter06.html

like image 196
River Avatar answered Sep 22 '22 20:09

River


What you experience is called Z fighting and unfortunately there's not definitive solution against it. What happens is, that due to the limited precision of the depth buffer, rounding errors occur and either one of the primitives "win" the depth test operation. Changing the depth function will just toggle the colours in the fighting pattern, but not remove it.

One method to get rid of the Z fighting is using polygon offset http://www.opengl.org/wiki/Basics_Of_Polygon_Offset

Unfortunately polygon offset introduces its own share of problems.

like image 38
datenwolf Avatar answered Sep 21 '22 20:09

datenwolf