PDA

View Full Version : 2D drawing: line one pixel too high



Aardwolf
03-09-2008, 03:56 PM
I'm using OpenGL for a 2D application. I use the "official" code for setting up a 2D view in OpenGL. (see source below, it comes from http://www.opengl.org/resources/features/KilgardTechniques/oglpitfall)

I think that should mean that the top row of pixels has y-coordinate 0. However, when it comes to drawing lines, it has coordinate 1.

The annoying thing is that quads are correct, and only lines are 1 pixel too high.

#include <GL/gl.h>
#include <SDL/SDL.h>


int main()
{
int w = 800; //width of the screen
int h = 600; //height of the screen

SDL_Init(SDL_INIT_VIDEO);

SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

SDL_Surface* scr = SDL_SetVideoMode(w, h, 32, SDL_OPENGL);

//the official code for "Setting Your Raster Position to a Pixel Location" (i.e. set up an oldskool 2D screen)
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, w, h, 0, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

glColor4ub(255, 255, 0, 255);

//this yellow line should be on the top row (y coordinate 0), but it's invisible because it's 1 higher
glBegin(GL_LINES);
glVertex2d(0, 0);
glVertex2d(100, 0);
glEnd();

glColor4ub(255, 0, 0, 255);

//this line is on the top row, even though it should be the second row (y coordinate 1)
glBegin(GL_LINES);
glVertex2d(0, 1);
glVertex2d(100, 1);
glEnd();

//2x2 pixel square ---> this one is correct!! it includes pixels from the top row and the row below that, a 2x2 pixel square
glBegin(GL_QUADS);
glVertex3d(300, 0, 1);
glVertex3d(302, 0, 1);
glVertex3d(302, 2, 1);
glVertex3d(300, 2, 1);
glEnd();

SDL_Event event = {0};
int done = 0;
while(done == 0)
{
while(SDL_PollEvent(&amp;event))
{
if(event.type == SDL_QUIT) done = 1;
if(event.type == SDL_KEYDOWN) done = 1;
SDL_GL_SwapBuffers();
}
SDL_Delay(5); //so it consumes less processing power
}
}

Why are the lines 1 pixel higher while rectangles are correct? Is this platform dependent? Let's hope not because then OpenGL would be less useful for 2D drawing!

If it's not platform dependent: is there a reasoning behind it, and is the solution simply to draw my lines one pixel lower and it'll work pixel-correct on all possible platforms?

-NiCo-
03-09-2008, 04:05 PM
By setting up your projection like this

(0,0) is the upper left corner of the upper left pixel.
(1,1) is the lower right corner of the upper left pixel.

So if you want to draw a line at the first row, you need to draw it at y = 0.5

dletozeun
03-10-2008, 01:11 PM
give us a screenshot to clearly see your problem.
Maybe it is because of lines width...