Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pixel-Perfect 2D Rendering with OpenGL

Tags:

c

opengl

Is it possible to set up an OpenGL scene to allow for pixel-perfect rendering and pixel blitting? I noticed that setting up a scene by doing:

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, height, 0.0, 0.0, 1.0);

And then drawing a pixel using:

glBegin(GL_POINTS);
glVertex2i(0, 0);
glEnd();

Does not consistently draw it on the top-left pixel on every hardware configuration (sometimes it's one pixel to the left, or one below the top-left corner). I realize this is likely due to different implementations of OpenGL by the graphics drivers, but is there a way to make it so that the top-left pixel is (0,0) and the bottom right is (width-1, height-1) consistently? It seems strange that this is something that isn't standardized...

I've seen some 'hacks' that use a translation of (0.375, 0.375) or (0.5, 0.5), but that also seems to solve it for some configurations and not for others.

like image 239
Jengerer Avatar asked Feb 17 '23 16:02

Jengerer


1 Answers

edit: dang, it is a translation. Updated.

You've got to consider also that pixels have size too. This is what the "translation hacks" are getting at. If the leftmost pixel should have a center coordinate 0.0, then its left boundary is at -0.5 -- and that's where the clipping plane should be. Similarly, if the rightmost pixel should have a center coordinate width - 1, then its right boundary is at (width - 1) + 0.5 -- and that's where that clipping plane should be.

So try:

glOrtho(-0.5, (width - 1) + 0.5, (height - 1) + 0.5, -0.5, 0.0, 1.0);

So that's where the translation come from.

like image 158
sheu Avatar answered Feb 27 '23 08:02

sheu