Home > Software engineering >  How to create a 2d grid in OpenGl windows?
How to create a 2d grid in OpenGl windows?

Time:02-25

I am trying to print a 2d grid on my entire window.

code:

float slices(15);
std::vector<glm::vec3> vert;
std::vector<glm::uvec3> ind;

for (int j = 0; j <= slices; j  ) {
    for (int i = 0; i <= slices; i  ) {

        GLfloat x = (float)i / (float)slices;
        GLfloat y = (float)j / (float)slices;
        GLfloat z = 0;
        vert.push_back(glm::vec3(x, y, z));
        
    }
}
for (int j = 0; j < slices; j  ) {
    for (int i = 0; i < slices; i  ) {

        int row1 = j * (slices   1);
        int row2 = (j   1) * (slices   1);

        ind.push_back(glm::uvec3(row1   i, row1   i   1, row2   i));
        ind.push_back(glm::uvec3(row1   i, row2   i   1, row2   i));

    }
}
{//generate vao and bind bufffer objects}
GLuint lenght = (GLuint)ind.size() * 3;

glBindVertexArray(vao);

glDrawElements(GL_LINES, lenght, GL_UNSIGNED_INT, NULL);

This only prints a grid on a fourth of my window (the postivive x,y plane).

window output

when I put a negative in front of the i or j in the for loop like so:

(GLfloat x = (float)-i/(float)slices;  

I get a grid in one of the other quadrants of my window. I've tried rendering the gird multiple times by erasing the vector and repopulating it with coordinates for each quadrant but this doesn't seem to work and seems highly inefficient.

CodePudding user response:

Normalized device coordinates are in range [-1.0, 1.0]. Map the coordinates from [0.0,1.0] to [-1.0, 1.0]:

vert.push_back(glm::vec3(x, y, z));

vert.push_back(glm::vec3(x * 2.0f - 1.0f, y * 2.0f - 1.0f, z));
  • Related