Appleshell
Appleshell

Reputation: 7388

How to apply position transformation

How do I apply the drawing position in the world via shaders?

My vertex shader looks like this:

in vec2 position;

uniform mat4x4 model;
uniform mat4x4 view;
uniform mat4x4 projection;

void main() {
    gl_Position = projection * view * model * vec4(position, 0.0, 1.0);
}

Where position is the positions of the vertexes of the triangles.

I'm binding the matrices as follows.

view:

glm::mat4x4 view = glm::lookAt(
                    glm::vec3(0.0f, 1.2f, 1.2f),    // camera position
                    glm::vec3(0.0f, 0.0f, 0.0f),    // camera target
                    glm::vec3(0.0f, 0.0f, 1.0f));   // camera up axis
GLint view_uniform = glGetUniformLocation(shader, "view");
glUniformMatrix4fv(view_uniform, 1, GL_FALSE, glm::value_ptr(view));

projection:

glm::mat4x4 projection = glm::perspective(80.0f, 640.0f/480.0f, 0.1f, 100.0f);
GLint projection_uniform = glGetUniformLocation(shader, "projection");
glUniformMatrix4fv(projection_uniform, 1, GL_FALSE, glm::value_ptr(projection));

model transformation:

glm::mat4x4 model;
model = glm::translate(model, glm::vec3(1.0f, 0.0f, 0.0f));
model = glm::rotate(model, static_cast<float>((glm::sin(currenttime)) * 360.0), glm::vec3(0.0, 0.0, 1.0));
GLint trans_uniform = glGetUniformLocation(shader, "model");
glUniformMatrix4fv(trans_uniform, 1, GL_FALSE, glm::value_ptr(model));

So this way I have to compute the position transformation each frame on the CPU. Is this the recommended way or is there a better one?

Upvotes: 4

Views: 1346

Answers (2)

fen
fen

Reputation: 10115

In the render() method you usually do the following things

  • create matrix for camera (once per frame usually)
  • for each object in the scene:
    • create transformation (position) matrix
    • draw object

projection matrix can be created once per windowResize, or when creating matrix for camera.

Answer: Your code is good, it is a basic way to draw/update objects.

You could go into some framework/system that manages it automatically. You should not care (right now) about the performance of those matrix creation procedures... it is very fast. Drawing is more problematic.

as jozxyqk wrote in one comment, you can create ModelViewProjMatrix and send one combined matrix instead of three different one.

Upvotes: 2

Blarglenarf
Blarglenarf

Reputation: 318

So this way I have to compute the position transformation each frame on the CPU. Is this the recommended way or is there a better one?

Yes. Calculating a new transform once for a mesh on the CPU and then applying it to all vertices inside the mesh inside the vertex shader is not going to be a very slow operation and needs to be done every frame.

Upvotes: 2

Related Questions