Source: math/Quaternion.js

  1. /**
  2. * @fileOverview
  3. * @author David Gossow - dgossow@willowgarage.com
  4. */
  5. /**
  6. * A Quaternion.
  7. *
  8. * @constructor
  9. * @param {Object} options
  10. * @param {number} [options.x=0] - The x value.
  11. * @param {number} [options.y=0] - The y value.
  12. * @param {number} [options.z=0] - The z value.
  13. * @param {number} [options.w=1] - The w value.
  14. */
  15. function Quaternion(options) {
  16. options = options || {};
  17. this.x = options.x || 0;
  18. this.y = options.y || 0;
  19. this.z = options.z || 0;
  20. this.w = (typeof options.w === 'number') ? options.w : 1;
  21. }
  22. /**
  23. * Perform a conjugation on this quaternion.
  24. */
  25. Quaternion.prototype.conjugate = function() {
  26. this.x *= -1;
  27. this.y *= -1;
  28. this.z *= -1;
  29. };
  30. /**
  31. * Return the norm of this quaternion.
  32. */
  33. Quaternion.prototype.norm = function() {
  34. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  35. };
  36. /**
  37. * Perform a normalization on this quaternion.
  38. */
  39. Quaternion.prototype.normalize = function() {
  40. var l = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  41. if (l === 0) {
  42. this.x = 0;
  43. this.y = 0;
  44. this.z = 0;
  45. this.w = 1;
  46. } else {
  47. l = 1 / l;
  48. this.x = this.x * l;
  49. this.y = this.y * l;
  50. this.z = this.z * l;
  51. this.w = this.w * l;
  52. }
  53. };
  54. /**
  55. * Convert this quaternion into its inverse.
  56. */
  57. Quaternion.prototype.invert = function() {
  58. this.conjugate();
  59. this.normalize();
  60. };
  61. /**
  62. * Set the values of this quaternion to the product of itself and the given quaternion.
  63. *
  64. * @param {Quaternion} q - The quaternion to multiply with.
  65. */
  66. Quaternion.prototype.multiply = function(q) {
  67. var newX = this.x * q.w + this.y * q.z - this.z * q.y + this.w * q.x;
  68. var newY = -this.x * q.z + this.y * q.w + this.z * q.x + this.w * q.y;
  69. var newZ = this.x * q.y - this.y * q.x + this.z * q.w + this.w * q.z;
  70. var newW = -this.x * q.x - this.y * q.y - this.z * q.z + this.w * q.w;
  71. this.x = newX;
  72. this.y = newY;
  73. this.z = newZ;
  74. this.w = newW;
  75. };
  76. /**
  77. * Clone a copy of this quaternion.
  78. *
  79. * @returns {Quaternion} The cloned quaternion.
  80. */
  81. Quaternion.prototype.clone = function() {
  82. return new Quaternion(this);
  83. };
  84. module.exports = Quaternion;