7Bpencil

glsl_quaternions_instead_MVP

Nov 22nd, 2020 (edited)
958
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #version 330 core
  2.  
  3. layout (location = 0) in vec3 vertex_position;
  4. layout (location = 1) in vec3 vertex_normal;
  5. layout (location = 2) in vec2 vertex_texture;
  6.  
  7. uniform mat4 view_projection;
  8. uniform vec3 scale;
  9. uniform vec4 orientation;
  10. uniform vec3 translation;
  11.  
  12. out vec3 FragPosition;
  13. out vec2 TexCoords;
  14. out vec3 NormalWorldSpace;
  15.  
  16. vec3 transform_vertex(vec4 rotation, vec3 vertex);
  17.  
  18. void main() {
  19.     FragPosition = transform_vertex(orientation, scale * vertex_position) + translation;
  20.     NormalWorldSpace = transform_vertex(orientation, (vec3(1.0) / scale) * vertex_normal); // doesn't take translation into account
  21.     TexCoords = vertex_texture;
  22.     gl_Position = view_projection * vec4(FragPosition, 1.0);
  23. }
  24.  
  25. // Transforms the vector using a quaternion, assuming that the output does not alias with the input.
  26. vec3 transform_vertex(vec4 rotation, vec3 v) {
  27.     float x2 = rotation.x + rotation.x;
  28.     float y2 = rotation.y + rotation.y;
  29.     float z2 = rotation.z + rotation.z;
  30.     float xx2 = rotation.x * x2;
  31.     float xy2 = rotation.x * y2;
  32.     float xz2 = rotation.x * z2;
  33.     float yy2 = rotation.y * y2;
  34.     float yz2 = rotation.y * z2;
  35.     float zz2 = rotation.z * z2;
  36.     float wx2 = rotation.w * x2;
  37.     float wy2 = rotation.w * y2;
  38.     float wz2 = rotation.w * z2;
  39.     // Defer the component setting since they're used in computation.
  40.     vec3 result;
  41.     result.x = v.x * (1f - yy2 - zz2) + v.y * (xy2 - wz2) + v.z * (xz2 + wy2);
  42.     result.y = v.x * (xy2 + wz2) + v.y * (1f - xx2 - zz2) + v.z * (yz2 - wx2);
  43.     result.z = v.x * (xz2 - wy2) + v.y * (yz2 + wx2) + v.z * (1f - xx2 - yy2);
  44.  
  45.     return result;
  46. }
  47.  
RAW Paste Data