#include <GL/glut.h>

/* Vertices of the polygon in anti-clockwise direction. */
GLfloat p1[] = {40.0, 0.0};
GLfloat p2[] = {50.0, 50.0};
GLfloat p3[] = {30.0, 200.0};
GLfloat p4[] = {0.0, 0.0};

GLfloat leftExtremes[410];
GLfloat rightExtremes[410];

void myInit () {
	
	int i;
	
	glClearColor (1.0, 1.0, 1.0, 1.0);
	
	glMatrixMode (GL_PROJECTION);
	glLoadIdentity();
	glOrtho (0.0, 400.0, 0.0, 400.0, 0.0, 400.0);
	glMatrixMode (GL_MODELVIEW);
	
	for (i = 0; i < 400; i++)
		leftExtremes[i] = 400, rightExtremes[i] = 0;
}

void findExtremes (float x1, float y1, float x2, float y2) {
	
	int i;
	float m, c, x, y;
	
	if (y1 > y2) {
		int temp;
		temp = y1;
		y1 = y2;
		y2 = temp;
		temp = x1;
		x1 = x2;
		x2 = temp;
	}
	/* scan from bottom */
	for (i = (int)y1; i < (int)y2; i++) {
		if (x2 != x1) {
			m = (y2-y1)/(x2-x1);
			c = y1 - (m*x1);
			x = (i-c)/m;
			if (x < leftExtremes[i])
				leftExtremes[i] = x;
			if (x > rightExtremes[i])
				rightExtremes[i] = x;
		}
		else {
			x = x1;
			if (x < leftExtremes[i])
				leftExtremes[i] = x;
			if (x > rightExtremes[i])
				rightExtremes[i] = x;
		}
	}
}

void display () {
	
	int i, j;
	
	glClear (GL_COLOR_BUFFER_BIT);

	findExtremes (p1[0], p1[1], p2[0], p2[1]);
	findExtremes (p2[0], p2[1], p3[0], p3[1]);
	findExtremes (p3[0], p3[1], p4[0], p4[1]);
	findExtremes (p4[0], p4[1], p1[0], p1[1]);
	
	glBegin (GL_LINE_LOOP);
		glVertex2fv (p1);
		glVertex2fv (p2);
		glVertex2fv (p3);
		glVertex2fv (p4);
	glEnd();
	glColor3f (1.0, 0.0, 0.0);
	
	for (i = 0; i < 400; i++) {
		if (leftExtremes[i] < rightExtremes[i])
			for (j = (int)leftExtremes[i]; j < (int)rightExtremes[i]; j++)
			{ glBegin (GL_POINTS);glVertex2i (j, i);glEnd();glFlush();}
	}
	
	
	glFlush();
}

int main (int argc, char *argv[]) {
	
	glutInit (&argc, argv);
	glutInitDisplayMode (GLUT_RGB | GLUT_SINGLE);
	glutCreateWindow ("Filling");
	glutReshapeWindow (400, 400);
	glutDisplayFunc (display);
	myInit();
	glutMainLoop();
	
	return 0;
}

