Sterling
Sterling

Reputation: 4203

OpenGL Window size for drawing grid

I am trying to draw a 50x50 grid in an OpenGL window. My code for drawing the grid is

void GLGrid::draw() {

int y=-width;
int yIncrement = width / 50;
int x=-length;
int xIncrement = length / 50;


glColor3f(0.0f,0.0f,0.0f);
for(y = -width; y < width; y+=yIncrement) {
    glBegin(GL_LINES);
        glVertex3f(-width,y,0);
        glVertex3f(width,y,0);
    glEnd();
}

for(x = -length; x < length; x+=xIncrement) {
    glBegin(GL_LINES);
        glVertex3f(-length,x,0);
        glVertex3f(length,x,0);
    glEnd();
}
}

Note that before I was doing x=0;x < length etc but that was making the line (the only one I see) start in the middle of the screen, rather than the very left. Also, when I draw a rectangle over the whole window, I have to start that at negative 300x300, rather than 0,0.

The only thing I see is one horizontal line across the middle of the screen. I think the problem is I don't know what my window size actually is. Whenever I print out wherever I click with

static void mouseEvent(int button, int state, int x, int y) {
cout<<"\nMouse Event!";
cout<<"\n\tbutton:"<<button;
cout<<"\n\tstate:"<<state;
cout<<"\n\tx:"<<x;
cout<<"\n\ty:"<<y<<"\n";
}

It prints out that the upper left corner is 0,0 and the bottom right corner is 300,300. So I set my GLGrid length and width to be 300 each. Should I be setting the window length and width to something else? And if so, what? I am very new to OpenGL so please forgive my ignorance. To be thorough and because I don't know if something else subtle may be the issue, I will include more code

static void initOpenGL() {
//set clear color to white
glClearColor(0.0f,0.0f,0.0f,1.0f);

glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
}


/*OpenGL calls*/
static void display(void)
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

if (!init)
{
    initOpenGL();
}

renderScene();

//...more code below in this function but pretty positive its irrelevant



static void renderScene() {

    drawBackground();

    drawGrid();

}


static void drawBackground() {
//draw a white rectangle for background
    glColor3f(1.0f,1.0f,1.0f);
    glBegin(GL_QUADS);
        glVertex3f(-windowMaxX, -windowMaxY, 0);
        glVertex3f(windowMaxX, -windowMaxY, 0);
        glVertex3f(windowMaxX, windowMaxY, 0);
        glVertex3f(-windowMaxX, windowMaxY, 0);
    glEnd();
}


static void drawGrid() {
    GLGrid.draw();
}

Upvotes: 0

Views: 1721

Answers (1)

Xymostech
Xymostech

Reputation: 9850

When you are drawing your vertical lines you need to change your x value, not your y value:

glBegin(GL_LINES);
    glVertex3f(x,-length,0);
    glVertex3f(x,length,0);
glEnd();

There's probably more wrong, but this is one thing to change.

Upvotes: 1

Related Questions