Search code examples
openglrendering

Should every object have its own shader?


Imagine I have 4 identical objects - (meshes or sprites), they all (could) have the same shader/program, because they are identical.

Each one has its own position and it's rendered in a separate render-call.

Positions of these objects change every once in a while, but not every frame.

I don't know what is the fastest way to handle this:

  1. Each object has its own shader, transforms are stored in the shaders (GPU side)? I need to rebind 4 shaders per frame. When I want to move a certain object I just bind the correct shader and send the new transformation matrix to it.

  2. There is only one shader/program bound for all of these objects? Transformations are stored in a class (CPU side). Every time I render one of these objects I must send its tranforms to the shader, so I send 4 matrices per frame. When I want to move a certain object I just change the value in it's class, but don't need to send anything to the GPU.

  3. Is there any other, better solution?


Solution

  • Option 2 is how you would want to handle this. Binding new shader programs is fairly expensive, ideally you would like to render as much as possible with one shader before moving to the next one.

    As for sending 4 matrices per frame, I'm assuming that 3 of those matrices are your MVP ones - Model, View, Projection. If you think about it, the view and projection matrices are going to be the same for a single batch of render calls, so those should be set only once in your render function, then you could loop through your meshes, and only update the model matrix before drawing. This way you limit the number of OpenGL state changes, which will result in better performance.