UNPKG

1.8 kBJavaScriptView Raw
1/**
2 * @prototype Point3d
3 * @param {number} [x]
4 * @param {number} [y]
5 * @param {number} [z]
6 */
7function Point3d(x, y, z) {
8 this.x = x !== undefined ? x : 0;
9 this.y = y !== undefined ? y : 0;
10 this.z = z !== undefined ? z : 0;
11}
12
13/**
14 * Subtract the two provided points, returns a-b
15 * @param {Point3d} a
16 * @param {Point3d} b
17 * @return {Point3d} a-b
18 */
19Point3d.subtract = function(a, b) {
20 var sub = new Point3d();
21 sub.x = a.x - b.x;
22 sub.y = a.y - b.y;
23 sub.z = a.z - b.z;
24 return sub;
25};
26
27/**
28 * Add the two provided points, returns a+b
29 * @param {Point3d} a
30 * @param {Point3d} b
31 * @return {Point3d} a+b
32 */
33Point3d.add = function(a, b) {
34 var sum = new Point3d();
35 sum.x = a.x + b.x;
36 sum.y = a.y + b.y;
37 sum.z = a.z + b.z;
38 return sum;
39};
40
41/**
42 * Calculate the average of two 3d points
43 * @param {Point3d} a
44 * @param {Point3d} b
45 * @return {Point3d} The average, (a+b)/2
46 */
47Point3d.avg = function(a, b) {
48 return new Point3d(
49 (a.x + b.x) / 2,
50 (a.y + b.y) / 2,
51 (a.z + b.z) / 2
52 );
53};
54
55/**
56 * Calculate the cross product of the two provided points, returns axb
57 * Documentation: http://en.wikipedia.org/wiki/Cross_product
58 * @param {Point3d} a
59 * @param {Point3d} b
60 * @return {Point3d} cross product axb
61 */
62Point3d.crossProduct = function(a, b) {
63 var crossproduct = new Point3d();
64
65 crossproduct.x = a.y * b.z - a.z * b.y;
66 crossproduct.y = a.z * b.x - a.x * b.z;
67 crossproduct.z = a.x * b.y - a.y * b.x;
68
69 return crossproduct;
70};
71
72
73/**
74 * Rtrieve the length of the vector (or the distance from this point to the origin
75 * @return {number} length
76 */
77Point3d.prototype.length = function() {
78 return Math.sqrt(
79 this.x * this.x +
80 this.y * this.y +
81 this.z * this.z
82 );
83};
84
85module.exports = Point3d;