Reputation: 1
I have written code for drawing a polygon using the GL_POLYGON
primitive mode of OpenGL. I am providing input points as an array. Here is my code:
#include <GL/freeglut.h>
#include <GL/gl.h>
#include <iostream>
using namespace std;
int Np;
double X[1000];
double Y[1000];
void init1()
{
glOrtho(-250.0, 250.0, -250.0, 250.0, -250.0, 250.0);
}
void func4()
{
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POLYGON);
for (int i = 0; i < Np; i++) {
glVertex2f(X[i], Y[i]);
}
glEnd();
glFlush();
}
int main(int argc, char ** argv)
{
cin >> Np;
for (int i = 0; i < Np; i++) {
cin >> X[i] >> Y[i];
}
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE);
glutInitWindowSize(500, 500);
glutInitWindowPosition(50, 50);
glutCreateWindow("Polygon");
glutDisplayFunc(func4);
glutMainLoop();
return 0;
}
The above code does not give the desired output for almost every input. What is wrong in the code?
For example, I used the following input for testing:
4
-100 -100
-100 0
100 100
100 -100
I expect this to draw a white polygon with 4 vertices around the center of the window, on black background.
Upvotes: 0
Views: 742
Reputation: 54562
The posted code never calls the init1()
function, which is where the projection is set up. It works fine after adding a call to init1()
before the call to glutMainLoop()
.
The default coordinate system in OpenGL has a range of -1 to 1 for x and y. So without any calls to apply a transformation, the polygon with the coordinates entered in the sample input will cover the whole window, which results in a completely white window.
Note that glOrtho()
is typically called in projection matrix mode. It will not make a difference in this small example, but it matters once you use more advanced functionality, like lighting. The init1()
function should look like this:
glMatrixMode(GL_PROJECTION);
glOrtho(-250.0, 250.0, -250.0, 250.0, -250.0, 250.0);
glMatrixMode(GL_MODELVIEW);
Also, I hope you're aware that the OpenGL features you are using here are deprecated, and not available anymore in the latest versions of OpenGL. If you just start learning, you may want to look into going for a more modern version instead, which means the Core Profile of OpenGL 3.2 on desktop systems, or OpenGL ES 2.0 or later on mobile devices.
Upvotes: 2