vector.js 1.99 KB
Newer Older
Athanasios's avatar
Athanasios committed
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const angle = require("./angle");

class Vector3 {

  constructor(x, y, z) {
    this.x = x;
    this.y = y;
    this.z = z;
  }

  magnitude() {
    return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  }

  normalize() {
    let magnitude = this.magnitude();
    this.x /= magnitude;
    this.y /= magnitude;
    this.z /= magnitude;
  }

  add(vector) {
    return new Vector3(
      this.x + vector.x,
      this.y + vector.y,
      this.z + vector.z
    );
  }

  subtract(vector) {
    return new Vector3(
      this.x - vector.x,
      this.y - vector.y,
      this.z - vector.z
    );
  }

  multiply(vector) {
    return new Vector3(
      this.x * vector.x,
      this.y * vector.y,
      this.z * vector.z
    );
  }

  multiplyScalar(value) {
    this.x *= value;
    this.y *= value;
    this.z *= value;
  }

  devideScalar(value) {
    this.x /= value;
    this.y /= value;
    this.z /= value;
  }

  dot(vector) {
    return this.x * vector.x + this.y * vector.y + this.z * vector.z;
  }

  distance(vector) {
    return this.subtract(vector).magnitude();
  }

  clone() {
    return new Vector3(this.x, this.y, this.z);
  }

}

const fromString = (str) => {
  let tokens = str.split(",");
  return new Vector3(...tokens.map(token => parseFloat(token)));
}

const fromDegrees = (lng, lat, height) => {
  lng = angle.degreesToRadians(lng);
  lat = angle.degreesToRadians(lat);
  let radiiSquared = new Vector3(6378137.0 * 6378137.0, 6378137.0 * 6378137.0, 6356752.3142451793 * 6356752.3142451793);
  let cosLatitude = Math.cos(lat);
  let scratchN = new Vector3(cosLatitude * Math.cos(lng), cosLatitude * Math.sin(lng), Math.sin(lat));
  scratchN.normalize();
  let scratchK = radiiSquared.multiply(scratchN);
  let gamma = Math.sqrt(scratchN.dot(scratchK));
  scratchK.devideScalar(gamma);
  scratchN.multiplyScalar(height);
  return scratchK.add(scratchN);
}

module.exports = { Vector3, fromString, fromDegrees };