I'm trying to create a 2D hollow grid on top of a purple background; however, what's being displayed whenever I create the grid is a white window.
I created the 2D grid using GL_Lines, as I only wanted the borders to be colored white and not the inside of the grid, which is not what happens.
#include <stdio.h>
#include <stdlib.h>
#include <ctime>
#include <cmath>
#include <string.h>
#include<GL/glut.h>
int gridX = 1000;
int gridY = 600;
void drawGrid();
void drawUnit(int, int);
void drawGrid() {
for (int x = 0; x < gridX; x++) {
for (int y = 0; y < gridY; y++) {
drawUnit(x, y);
}
}
}
void drawUnit(int x, int y) {
glLineWidth(1.0);
glColor3f(1.0,1.0,1.0);
glBegin(GL_LINE);//(x,y)(x+1,y)(x+1,y+1)(x,y+1)
glVertex2f(x,y);
glVertex2f(x+1, y);
glVertex2f(x + 1, y);
glVertex2f(x+1, y+1);
glVertex2f(x + 1, y + 1);
glVertex2f(x, y+1);
glVertex2f(x, y + 1);
glVertex2f(x, y);
glEnd();
}
void Display() {
glClear(GL_COLOR_BUFFER_BIT);
drawGrid();
glFlush();
}
void main(int argc, char** argr) {
glutInit(&argc, argr);
glutInitWindowSize(gridX, gridY);
drawGrid();
glutCreateWindow("OpenGL - 2D Template");
glutDisplayFunc(Display);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glClearColor(120.0f / 255.0f, 92.0f / 255.0f, 166.0f / 255.0f, 0.0f);
gluOrtho2D(0.0, gridX, 0.0, gridY);
glutMainLoop();
}
GL_LINE
is not an OpenGL primitive type. But GL_LINES
is a line primitive type (see Line primitives):
glBegin(GL_LINE);
glBegin(GL_LINES);
GL_LINE
is a polygon rasterization mode (see glPolygonMode
).
One cell in your grid is only 1 pixel in size. This results in the entire screen being filled in white. Use a different size for the cells. For instance:
void drawGrid()
{
int size = 10;
for (int x = 0; x < gridX; x += 10)
{
for (int y = 0; y < gridY; y += 10)
{
drawUnit(x, y, size);
}
}
}
void drawUnit(int x, int y, int size)
{
glLineWidth(1.0);
glColor3f(1.0,1.0,1.0);
glBegin(GL_LINES);
glVertex2f(x,y);
glVertex2f(x+size, y);
glVertex2f(x + size, y);
glVertex2f(x+size, y+size);
glVertex2f(x + size, y + size);
glVertex2f(x, y+size);
glVertex2f(x, y + size);
glVertex2f(x, y);
glEnd();
}