简体   繁体   中英

How to draw OpenGL primitives (GL_POINT, GL_LINE, etc) using screen coordinates?

I'm writing an OpenGL library that can draw points, lines, and rectangles using the screen coordinates. However, I do not know how to convert the screen coordinates to clip or camera coordinates. I am using modern OpenGL (vertex arrays and vertex buffers, as well as shaders).

This is basically what I'm working towards:

DrawPoint(10, 10, 5); // draws a point at pixel 10, 10 with a radius of 5

The same concept for drawing lines and rectangles.

Also, I'm not providing code because that isn't what I'm looking for, I'm looking for concepts and math.

What you probably want is an Orthogonal Projection Matrix. This code will go in your draw loop:

int width = getFramebufferWidth();
int height = getFramebufferHeight();
glm::mat4 mvp = glm::ortho(0, width, 0, height);

glUniformMatrix4fv(glGetUniformLocation(program, "mvp"), 1, false, glm::value_ptr(mvp));

glViewport(0, width, 0, height);
//Draw the Objects, clear the screen, whatever it is you need to do.

Then, in your Vertex Shader, you'll have something like this:

#version 330

layout(location = 0) in vec2 position;

uniform mat4 mvp;

void main() {
    gl_Position = mvp * vec4(position, 0, 1);
}

Then, when you specify something to be drawn at position <10, 10> , it'll be drawn at exactly that position.

This code uses GLM to build the matrix in question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM