简体   繁体   中英

In openGL should model coordinates be calculated on my CPU or on the GPU with OpenGL calls?

I am currently trying to understand openGL. I have a good understanding of the math behind the matrices transformations. So I want to write a small 3D application where I could render many, many vertices. There would be different objects, with each there own set of vertices and world coordinates.

To get the actual coordinates of my vertices, I need to multiply them by the transformation matrix corresponding to the position/rotation of my object.

Here is my problem, I don't understand in OpenGL how to do these transformation for all these vertices by the GPU. From my understanding it would be much faster, but I don't seem to understand how to do it.

Or should I calculate each of those coordinates with the CPU and draw the transformed vertices with openGL?

There's a couple of different ways to solve this problem, depending on your circumstances.

The major draw model that people use looks like this: (I'm not going to check the exact syntax, but I'm pretty sure this is correct)

//Host Code, draw loop
for(Drawable_Object const& object : objects) {
    glm::mat4 mvp;
    glm::projection = /*...*/;
    glm::view = /*...*/;
    glm::model = glm::translate(glm::mat4(1), object.position);//position might be vec3 or vec4
    mvp = projection * view * model;
    glUniformMatrix1fv(glGetUniformLocation(program, "mvp"), 1, false, glm::value_ptr(mvp));
    object.draw();//glDrawArrays, glDrawElements, etc...
}

//GLSL Vertex Shader
layout(location=0) in vec3 vertex;
uniform mat4 mvp;
/*...*/

void main() {
    gl_Position = mvp * vec4(vertex, 1);
    /*...*/
}

In this model, the matrices are calculated on the host, and then applied on the GPU. This minimizes the amount of data that needs to be passed on the CPU<-->GPU bus (which, while not often a limitation in graphics, can be a consideration to keep in mind), and is generally the cleanest in terms of reading/parsing the code.

There's a variety of other techniques you can use (and, if you do instanced rendering, have to use ), but for most applications, it's not necessary to deviate from this model in any significant way.

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