title: Better to multiply matrices in javascript or a shader?
body: <p>I've been looking at several webgl examples.  Consider <a href="https://developer.mozilla.org/en-US/docs/Web/WebGL" rel="noreferrer">MDN's tutorial</a>.  Their vertex shader multiplies the vertex by a perspective matrix and a world position matrix:</p>
  
  <p><code>
  gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
  </code></p>
  
  <p>But the <code>uMVMatrix</code> is itself the product of several transforms (translation, rotation, etc) calculated in javascript with the help of some matrix libraries.</p>
  
  <p>It seems like it would be faster to calculate their products directly in the shader; surely that's faster than doing it in .js.  Is there some reason why they choose this approach?  </p>
  
  <p>Now, I guess you can stack an arbitrary number of transforms in an arbitrary order this way, which is more flexible.  But say that flexibility isn't needed, is there any reason to avoid doing transforms directly in the shaders?   Something like</p>
  
  <p><code>
  gl_Position = uPMatrix * uRotationMatrix * uScaleMatrix * uTranslationMatrix * vec4(aVertexPosition, 1.0);
  </code></p>
  
  <p><em>e:</em> To add some context, in my particular case I'll only be rendering 2D rectangular entities (mostly sprites), so the number of vertices will always just be 4.  </p>
  
  <p>Given the overhead of bringing in a library to do fast .js matrix multiplication, seems like pushing these calculations into the shader is definitely the way to go for my personal case.</p>
  
  <p>(Plus, even if it were slower in the balance than doing it in javascript, shunting the calculations into the GPU is probably worth something in and of itself!)</p>