Hossein Narimani Rad
Hossein Narimani Rad

Reputation: 32481

How correctly draw a polygon with OpenTK

I'm new to OpenTK and I'm using the following code to draw large number of polygons using OpenTK

public static void DrawPolygon(Point[] points)
{
    GL.Begin(BeginMode.Polygon); //IF I Change this to LineStrip every things will be OK
    int numberOfPoints = points.Length;
    for (int i = 0; i < numberOfPoints; i++)
    {
        GL.Vertex2(points[i].X, points[i].Y);
    }
    GL.End();
}

And this is the configuration code which executes before calling the DrawPolygon

GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

GL.MatrixMode(MatrixMode.Projection);
GL.LoadIdentity();
GL.Ortho(0, width, 0, height, -1, 1); // Bottom-left corner pixel has coordinate (0, 0)
GL.Viewport(0, 0, (int)width, (int)height); 

GL.ClearColor(drawing.Color.Transparent);

GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

GL.MatrixMode(MatrixMode.Modelview);
GL.LoadIdentity();
GL.Color3(pen.Color);
GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Line);
GL.PointSize(5f);
GL.LineWidth(2f);

Using this code when I save the rendered image to disk as png, the result will be like this

enter image description here

result for:GL.Begin(BeginMode.Polygon);

However If I change the first line of the DrawPolygon to GL.Begin(BeginMode.LineStrip); the polygon would be rendered as expected like this:

enter image description here

result for : GL.Begin(BeginMode.LineStrip);

Anyone knows why those two extra lines appears when using BeginMode.Polygon?

Upvotes: 1

Views: 3644

Answers (1)

Chris Mantle
Chris Mantle

Reputation: 6683

I believe it's because GL_POLYGON/BeginMode.Polygon only renders convex polygons. I think that if you attempt render a concave polygon, as you're doing, the driver will try split up the geometry that you give it to render it as convex polygons, hence the unexpected lines in your example.

It's inadvisable to use the polygon rendering mode in OpenGL. The rendering of line strips and triangles is much more highly optimized, and therefore much, much quicker. I'd advise staying with line strips.

Upvotes: 2

Related Questions