Reputation: 3267
I am trying to draw an L shaped polygon using OpenGL in C. According to me this code should do it but instead it doesn't give me the expected result. The shape I am trying to draw is something similar to below. The point where the error occurs is at point 2 in function polygon1.
Is there some mistake that I seem to be making here or is it a bug in OpenGL. The pic shown below is the error-red output and the diagram drawn below that, is the expected output from the code.
----
| |
| |
--- |
| |
------
void polygon1(float x,float y)
{
glColor3f(0,1,0);
glBegin(GL_POLYGON);
glVertex2f(x,y);
glVertex2f(x,y+25);
glVertex2f(x+25,y+25);
glVertex2f(x+25,y+75);
glVertex2f(x+50,y+75);
glVertex2f(x+50,y);
glEnd();
glFlush();
}
void mydisplay()
{
polygon1(200.0,25.0);
}
void main(int argc,char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA);
glutInitWindowSize(400,400);
glutInitWindowPosition(540,320);
glutCreateWindow("my first attempt");
glClearColor(0.0f,0.0f,0.0,0.0f);
glClear(GL_COLOR_BUFFER_BIT);
glutDisplayFunc(mydisplay);
gluOrtho2D(0.0,400.0,0.0,400.0);
glutMainLoop();
}
Upvotes: 0
Views: 1165
Reputation: 47968
As has been mentioned, OpenGL can't do this on its own (unless you store the triangles beforehand)
OpenGL doesn't provide a tessellator, but GLU does, as has been mentioned.
If libGLU isnt an option there are a few tessellators out there - libGDX has quite a simple implementation (in Java - but easy to port).
Blender has a C port of this code with optimizations (using 2D kd-tree)
Upvotes: 0
Reputation: 54572
As Drew Hall pointed out in a previous answer, GL_POLYGON cannot draw concave polygons. You can draw this shape with single triangle fan, though. Try this:
glBegin(GL_TRIANGLE_FAN);
glVertex2f(x+25,y+25);
glVertex2f(x,y+25);
glVertex2f(x,y);
glVertex2f(x+50,y);
glVertex2f(x+50,y+75);
glVertex2f(x+25,y+75);
glEnd();
Upvotes: 1
Reputation: 29047
OpenGL only renders convex polygons properly. Your "L" needs to be broken into a triangle strip. You can do this manually or via GLU tesselators (I'm assuming GLU is an option for you as you're rendering in immediate mode anyways).
Upvotes: 2