1

In GLM we have a overloaded '*' operator for multiplying matrices.

We can do matrix multiplication like this with using this operator in GLM:

glm::mat4 MVP = Projection * View * Model;
//after that pass MVP to uniform 'MVP'

But in other way, we can pass Projection, View and Model to three different uniforms and do multiplication in shader program.

GLM runs on CPU but shader programs run on GPU. Because of architecture of GPU, we can do matrix operations more faster than CPU in shader programs.

But i can't be sure. Which way is faster?

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
Ibrahim Ipek
  • 479
  • 4
  • 13

1 Answers1

3

Ideally one would pass them separately if you need them separately in your shader for other purposes. If all you need is MVP, its best to multiply and pass an MVP as a single matrix to your shader.

What is best, depends a lot on the number of vertices you render as well as whether your rendering has multiple draw calls with few vertices or few draw calls with many vertices.

Always multiplication on CPU would be better since its once per draw call, instead of once per vertex. If the values need to vary between shaders, then one has to perform the multiplication in the shader.

I think I was too quick to answer, but this might be very similar to the question Should I calculate matrices on the GPU or on the CPU?

Community
  • 1
  • 1
Harish
  • 964
  • 6
  • 17
  • Most cases? What is the exceptions? – Ibrahim Ipek Aug 15 '16 at 00:37
  • If you have a lot of matrix multiplications and are rendering just points with different matrices for each point and each point is a single draw call, multiplication in the GPU method may be faster if CPU is already performing other physics computations making it the bottleneck for rendering each frame. – Harish Aug 15 '16 at 00:53
  • Like particle effects? – Ibrahim Ipek Aug 15 '16 at 02:05
  • 1
    What your answer implies but does not spell out is to (almost) never do a matrix multiply in a vertex shader. A matrix multiply is 16 dot products. A vector matrix product is 4. So unless you end up transforming a vector by 4 different matrices it is always more efficient to transform it a matrix at a time. – starmole Aug 15 '16 at 06:25
  • Agreed. There may be situations where the matrices might not be constant for each vertex in a draw call. In those situations where values vary between shaders, it makes sense to have matrix multiplications in the shader itself. Otherwise, its always better to have them on CPU. I cant think of other kind of exceptions. I just found out there is a very similar question already asked. This might be a duplicate, I was too quick to answer. http://stackoverflow.com/questions/16620013/should-i-calculate-matrices-on-the-gpu-or-on-the-cpu – Harish Aug 15 '16 at 12:08