I'm a bit new to opengl and graphics programming in general. My question I think is quite simple. How could I write a function that takes screen coordinates (x, y) and creates 2d geometry that gets displayed on screen?
-
There is a long way to go between the « idea » of a drawing and actually obtaining this drawing in an OpenGL framebuffer. The few first steps of this tutorial could help understand the main elements: https://www.enib.fr/~harrouet/Data/Courses/OpenGlCoreTutorial/OpenGlCoreTutorial.html – prog-fh Aug 07 '20 at 19:46
-
I said I was new to opengl not completely clueless. I know how to draw to the screen by binding a vertex buffer object and a call to glDrawElements, all I need is what are the mathematical steps necessary to go from screen space to world space. – Aug 07 '20 at 19:56
-
Then maybe steps 04 (transformation), 05 (homogeneous coordinate matrices), 06 (projection) and 07 (viewpoint) of this tutorial could bring something you will find useful. – prog-fh Aug 07 '20 at 20:02
-
I'll try and see if this works. Thanks a lot ! – Aug 07 '20 at 20:11
1 Answers
For people who come across this question in the future. This stackoverflow thread helped a lot. Transformations from pixels to NDC. The basic gist of it is that you should create something called an orthographic projection matrix by specifying the top, bottom, left, right, near and far of the view frustum the orthographic matrix represents. If you're not sure about projection matrices I also found this helpful https://learnopengl.com/Getting-started/Coordinate-Systems. You upload the ortho matrix to your GPU using glUniformMatrix (at least that's how I did it) and multiply this matrix by each vertex you assign to glPosition built in variable in the vertex shader. I.e
precision mediump float;
attribute vec2 a_square;
uniform mat4 projectionMatrix;
void main() {
gl_Position = projectionMatrix * vec4(a_square, 0.0, 1.0);
}
If you generate your ortho matrix by using bottom as your maximum screen height, top as 0, left as 0 and right as your maximum screen width, what you'll be able to do is specify the coordinates for your geometry in pixels and it will be rendered with a call to glDrawElements/glDrawArrays.