3

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();
   }
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
HR1
  • 487
  • 4
  • 14
  • If you're just drawing a grid, don't make individual squares. You're doing a lot of unnecessary overdraw. You can also get rid of the nested loop in `drawGrid` pretty easily. – 3Dave Nov 11 '20 at 19:27

1 Answers1

1

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();
}
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • I fixed it, but for some reason the whole unit square grid is white, and I only want the borders – HR1 Nov 11 '20 at 17:56