How to avoid Z-fighting

Suppose that you have two overlapped regions and you want to avoid Z-fighting.

Capture.PNG

 

If you want to prevent Z-fighting, you can follow the approach reported below.

First of all, you should decide which entity you prefer to display on top (in this case I choose CircularRegion).

Next, you should create a new class "MyRegion" that derives from CircularRegion, and override Draw() and Render() methods.

class MyRegion : CircularRegion 
{ 
        public MyRegion(double x, double y, double radius) 
            : base(x,y,radius) 
        { 

        } 
         
        protected override void Draw(DrawParams data) 
        { 
            gl.PushAttrib(gl.ENABLE_BIT | gl.POLYGON_BIT); 
            gl.Enable(gl.POLYGON_OFFSET_FILL); 
            gl.PolygonOffset(-3, -2); 

            base.Draw(data); 

            gl.PopAttrib(); 
        } 

        protected override void Render(RenderParams data) 
        { 
            gl.PushAttrib(gl.ENABLE_BIT | gl.POLYGON_BIT); 
            gl.Enable(gl.POLYGON_OFFSET_FILL); 
            gl.PolygonOffset(-3, -2); 

            base.Render(data); 

            gl.PopAttrib(); 
        } 
}

 

It is possible that you need to tune properly parameters of gl.PolygonOffset(), because they depends from entities you are displaying (for your reference, OpenGL documentation: http://www.opengl.org/sdk/docs/man/html/glPolygonOffset.xhtml )

Finally, when you draw the two entities:

MyRegion circ = new MyRegion(80, 80, 30); 
circ.ColorMethod = colorMethodType.byEntity; 
circ.Color = Color.Red; 
viewportLayout1.Entities.Add(circ); 

RectangularRegion rect = new RectangularRegion(200, 200); 
rect.Color = Color.Gray; 
rect.ColorMethod = colorMethodType.byEntity; 
viewportLayout1.Entities.Add(rect);

 

you will obtain the following result:

Capture1.PNG

Have more questions? Submit a request

2 Comments

  • 0
    Avatar
    James Trounson

    I tried this with LinearPath & Solid3D. I derive "MyLinearPath" & override the Render & Draw functions, but get the same results. The LinePath and Solid3D are Z fighting.

    I assume since LinearPath is not a true polygon (although I think all lines are implemented as degenerate polygons in the graphics card), this concept may not apply.

    Or it's possible I'm doing something wrong.

    Any advice? Thanks

  • 0
    Avatar
    James Trounson

    I figured it out. Looks like replacing the "gl.POLYGON_OFFSET_FILL" with "gl.POLYGON_OFFSET_LINE" solves the problem when drawing lines.

Please sign in to leave a comment.