quaternion.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // SPDX-FileCopyrightText: 2016 Citra Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #pragma once
  4. #include "common/vector_math.h"
  5. namespace Common {
  6. template <typename T>
  7. class Quaternion {
  8. public:
  9. Vec3<T> xyz;
  10. T w{};
  11. [[nodiscard]] Quaternion<decltype(-T{})> Inverse() const {
  12. return {-xyz, w};
  13. }
  14. [[nodiscard]] Quaternion<decltype(T{} + T{})> operator+(const Quaternion& other) const {
  15. return {xyz + other.xyz, w + other.w};
  16. }
  17. [[nodiscard]] Quaternion<decltype(T{} - T{})> operator-(const Quaternion& other) const {
  18. return {xyz - other.xyz, w - other.w};
  19. }
  20. [[nodiscard]] Quaternion<decltype(T{} * T{} - T{} * T{})> operator*(
  21. 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. [[nodiscard]] Quaternion<T> Normalized() const {
  26. T length = std::sqrt(xyz.Length2() + w * w);
  27. return {xyz / length, w / length};
  28. }
  29. [[nodiscard]] std::array<decltype(-T{}), 16> ToMatrix() const {
  30. const T x2 = xyz[0] * xyz[0];
  31. const T y2 = xyz[1] * xyz[1];
  32. const T z2 = xyz[2] * xyz[2];
  33. const T xy = xyz[0] * xyz[1];
  34. const T wz = w * xyz[2];
  35. const T xz = xyz[0] * xyz[2];
  36. const T wy = w * xyz[1];
  37. const T yz = xyz[1] * xyz[2];
  38. const T wx = w * xyz[0];
  39. return {1.0f - 2.0f * (y2 + z2),
  40. 2.0f * (xy + wz),
  41. 2.0f * (xz - wy),
  42. 0.0f,
  43. 2.0f * (xy - wz),
  44. 1.0f - 2.0f * (x2 + z2),
  45. 2.0f * (yz + wx),
  46. 0.0f,
  47. 2.0f * (xz + wy),
  48. 2.0f * (yz - wx),
  49. 1.0f - 2.0f * (x2 + y2),
  50. 0.0f,
  51. 0.0f,
  52. 0.0f,
  53. 0.0f,
  54. 1.0f};
  55. }
  56. };
  57. template <typename T>
  58. [[nodiscard]] auto QuaternionRotate(const Quaternion<T>& q, const Vec3<T>& v) {
  59. return v + 2 * Cross(q.xyz, Cross(q.xyz, v) + v * q.w);
  60. }
  61. [[nodiscard]] inline Quaternion<float> MakeQuaternion(const Vec3<float>& axis, float angle) {
  62. return {axis * std::sin(angle / 2), std::cos(angle / 2)};
  63. }
  64. } // namespace Common