How does one convert pixel length (i.e an image with 512 pixel width and height) to accurate OpenGL coordinates?
All I can do now is try to guess the size manually between -1 and 1.
If you want to address pixels precisely, the previously posted answer is not sufficient. It calculates the lower left corner of pixels. But to place a vertex exactly on a pixel, you need to use the coordinates of the pixel center.
In your example with a width of 512 pixels, without any transformations applied, these pixels span the NDC coordinate range of [-1.0, 1.0]. This means that the width of each pixel is 2.0 / 512 in NDC space.
For example, for the very first pixel, if you look at it as a small square, its coordinate range is from -1.0 to -1.0 + 2.0 / 512. It's center is therefore at -1.0 + 1.0 / 512 in NDC space.
Generalizing this for a general window width w and height h, the coordinates of pixel with index i in horizontal direction and index k in vertical direction (bottom to top) are:
x = -1.0 + i * (2.0 / w) + (1.0 / w) = (2.0 * i + 1.0) / w - 1.0
y = -1.0 + k * (2.0 / h) + (1.0 / h) = (2.0 * k + 1.0) / h - 1.0
The question is quite vague, but as I see it the problem is that the window coordinates are ranging, as you say, between -1 to 1; and since the screen is a rectangle, quads will be drawn as a rectangle rather than a square.
It is not recommended to draw in "pixel coordinates" since all monitors don't have the same resolution nor the same aspect ratio. However, if your are certain that this is what you want to do, then this is how you'd do it:
If you are using shaders with OpenGL 3+:
Just divide the x coordinate by half of the width of the window and subtract 1.
Do the same for the the y coordinate but divide by half the height instead of half the width.
If you are using the old immediate mode OpenGL (which by the way is not recommended and outdated since long ago) then you should look into glOrtho
Note that all the above is just for orthographic projection (2D).
If you want to draw in 3D you should not draw in "pixel coordinates" by any means. Instead, multiply either the width or height by the relevant aspect ratio (i.e width/height or height/width) or integrate the aspect ratio into your perspective projection if creating your own shader.
Generally, OpenGL does not draw by pixels. You draw into OpenGL's own coordinate system and OpenGL will then convert it to pixels. This is what makes it so powerful for 3D rendering. This approach is much more convenient because of the differing monitor resolutions and aspect ratios.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With