quaternion.h 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Copyright 2016 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include "common/vector_math.h"
  6. namespace Math {
  7. template <typename T>
  8. class Quaternion {
  9. public:
  10. Math::Vec3<T> xyz;
  11. T w;
  12. Quaternion<decltype(-T{})> Inverse() const {
  13. return {-xyz, w};
  14. }
  15. Quaternion<decltype(T{} + T{})> operator+(const Quaternion& other) const {
  16. return {xyz + other.xyz, w + other.w};
  17. }
  18. Quaternion<decltype(T{} - T{})> operator-(const Quaternion& other) const {
  19. return {xyz - other.xyz, w - other.w};
  20. }
  21. Quaternion<decltype(T{} * T{} - T{} * T{})> operator*(const Quaternion& other) const {
  22. return {xyz * other.w + other.xyz * w + Cross(xyz, other.xyz),
  23. w * other.w - Dot(xyz, other.xyz)};
  24. }
  25. Quaternion<T> Normalized() const {
  26. T length = std::sqrt(xyz.Length2() + w * w);
  27. return {xyz / length, w / length};
  28. }
  29. };
  30. template <typename T>
  31. auto QuaternionRotate(const Quaternion<T>& q, const Math::Vec3<T>& v) {
  32. return v + 2 * Cross(q.xyz, Cross(q.xyz, v) + v * q.w);
  33. }
  34. inline Quaternion<float> MakeQuaternion(const Math::Vec3<float>& axis, float angle) {
  35. return {axis * std::sin(angle / 2), std::cos(angle / 2)};
  36. }
  37. } // namespace Math