Quaternion.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #include "core/Quaternion.hpp"
  2. #include <cmath>
  3. Core::Quaternion::Quaternion() : v(0.0f, 0.0f, 0.0f, 1.0f) {
  4. }
  5. Core::Quaternion::Quaternion(const Vector3& axis, float angle) :
  6. v(axis[0], axis[1], axis[2], 1.0f) {
  7. v.xyz().normalize();
  8. float factor = 0.0f;
  9. sincosf(angle * 0.5f, &factor, &v[3]);
  10. v.xyz() *= factor;
  11. }
  12. Core::Quaternion Core::Quaternion::lerp(
  13. float f, const Quaternion& other) const {
  14. Quaternion q;
  15. q.v = interpolate(v, other.v, f);
  16. q.v.normalize();
  17. return q;
  18. }
  19. Core::Quaternion& Core::Quaternion::operator*=(const Quaternion& other) {
  20. float dot = v.xyz().dot(other.v.xyz());
  21. v.xyz() = other.v.xyz() * v[3] + v.xyz() * other.v[3] +
  22. cross(v.xyz(), other.v.xyz());
  23. v[3] = v[3] * other.v[3] - dot;
  24. return *this;
  25. }
  26. Core::Quaternion Core::Quaternion::operator*(const Quaternion& other) const {
  27. Quaternion q(*this);
  28. q *= other;
  29. return q;
  30. }
  31. Core::Vector3 Core::Quaternion::operator*(const Vector3& v3) const {
  32. Vector3 qv = v3 * v[3] + cross(v.xyz(), v3);
  33. return v.xyz() * v.xyz().dot(v3) + qv * v[3] - cross(qv, v.xyz());
  34. }
  35. size_t Core::Quaternion::toString(char* s, size_t n) const {
  36. int w = snprintf(
  37. s, n, "(%.3f i + %.3f j + %.3f k + %.3f)", static_cast<double>(v[0]),
  38. static_cast<double>(v[1]), static_cast<double>(v[2]),
  39. static_cast<double>(v[3]));
  40. return w >= 0 ? static_cast<size_t>(w) : 0;
  41. }