forked from processing/p5.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
p5.Quat.js
71 lines (65 loc) · 2.32 KB
/
p5.Quat.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import p5 from '../core/main';
/**
* A class to describe a Quaternion
* for vector rotations in the p5js webgl renderer.
* @class p5.Quat
* @constructor
* @param {Number} [w] Scalar part of the quaternion
* @param {Number} [x] x component of imaginary part of quaternion
* @param {Number} [y] y component of imaginary part of quaternion
* @param {Number} [z] z component of imaginary part of quaternion
*/
p5.Quat = class {
constructor(w, x, y, z) {
this.w = w;
this.vec = new p5.Vector(x, y, z);
}
/**
* Returns a Quaternion for the
* axis angle representation of the rotation
*
* @method fromAxisAngle
* @param {Number} [angle] Angle with which the points needs to be rotated
* @param {Number} [x] x component of the axis vector
* @param {Number} [y] y component of the axis vector
* @param {Number} [z] z component of the axis vector
* @chainable
*/
static fromAxisAngle(angle, x, y, z) {
const w = Math.cos(angle/2);
const vec = new p5.Vector(x, y, z).normalize().mult(Math.sin(angle/2));
return new p5.Quat(w, vec.x, vec.y, vec.z);
}
conjugate() {
return new p5.Quat(this.w, -this.vec.x, -this.vec.y, -this.vec.z);
}
/**
* Multiplies a quaternion with other quaternion.
* @method mult
* @param {p5.Quat} [quat] quaternion to multiply with the quaternion calling the method.
* @chainable
*/
multiply(quat) {
/* eslint-disable max-len */
return new p5.Quat(
this.w * quat.w - this.vec.x * quat.vec.x - this.vec.y * quat.vec.y - this.vec.z - quat.vec.z,
this.w * quat.vec.x + this.vec.x * quat.w + this.vec.y * quat.vec.z - this.vec.z * quat.vec.y,
this.w * quat.vec.y - this.vec.x * quat.vec.z + this.vec.y * quat.w + this.vec.z * quat.vec.x,
this.w * quat.vec.z + this.vec.x * quat.vec.y - this.vec.y * quat.vec.x + this.vec.z * quat.w
);
/* eslint-enable max-len */
}
/**
* Rotates the Quaternion by the quaternion passed
* which contains the axis of roation and angle of rotation
*
* @method rotateBy
* @param {p5.Quat} [axesQuat] axis quaternion which contains
* the axis of rotation and angle of rotation
* @chainable
*/
rotateBy(axesQuat) {
return axesQuat.multiply(this).multiply(axesQuat.conjugate()).vec;
}
};
export default p5.Quat;