Quaternion.cpp 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #include <cmath>
  2. #include "math/Quaternion.h"
  3. Quaternion::Quaternion() : w(1.0f) {
  4. }
  5. Quaternion::Quaternion(const Vector3& axis, float angle) : xyz(axis) {
  6. xyz.normalize();
  7. float sin;
  8. sincosf(angle * (M_PI / 360.0f), &sin, &w);
  9. xyz *= sin;
  10. }
  11. Quaternion Quaternion::lerp(float f, const Quaternion& other) const {
  12. Quaternion q;
  13. q.xyz = xyz * (1.0f - f) + other.xyz * f;
  14. q.w = w * (1.0f - f) + other.w * f;
  15. float iLength = 1.0f / sqrtf(q.xyz.squareLength() + q.w * q.w);
  16. q.xyz *= iLength;
  17. q.w *= iLength;
  18. return q;
  19. }
  20. Quaternion& Quaternion::operator*=(const Quaternion& other) {
  21. float dot = xyz.dot(other.xyz);
  22. xyz = other.xyz * w + xyz * other.w + xyz.cross(other.xyz);
  23. w = w * other.w - dot;
  24. return *this;
  25. }
  26. Quaternion Quaternion::operator*(const Quaternion& other) const {
  27. Quaternion q(*this);
  28. q *= other;
  29. return q;
  30. }
  31. Vector3 Quaternion::operator*(const Vector3& v) const {
  32. Vector3 qv = v * w + xyz.cross(v);
  33. Vector3 qvq = xyz * xyz.dot(v) + qv * w - qv.cross(xyz);
  34. return qvq;
  35. }