forked from geidav/ombb-rotating-calipers
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvector.js
116 lines (96 loc) · 2.2 KB
/
vector.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
function Vector(x, y)
{
this.x = x;
this.y = y;
this.min = function(vec)
{
x = Math.min(x, vec.x);
y = Math.min(y, vec.y);
}
this.max = function(vec)
{
x = Math.max(x, vec.x);
y = Math.max(y, vec.y);
}
this.midpoint = function(vec)
{
return new Vector((x+vec.x)*0.5, (y+vec.y)*0.5);
}
this.clone = function()
{
return new Vector(this.x, this.y);
}
this.normalize = function()
{
var len = this.length();
this.x /= len;
this.y /= len;
}
this.normalized = function()
{
var vec = new Vector(this.x, this.y);
vec.normalize();
return vec;
}
this.negate = function()
{
this.x = -this.x;
this.y = -this.y;
}
this.sqrLength = function()
{
return this.x * this.x + this.y * this.y;
}
this.length = function()
{
return Math.sqrt(this.x * this.x + this.y * this.y);
}
this.scale = function(len)
{
this.x *= len;
this.y *= len;
}
this.add = function(vec)
{
this.x += vec.x;
this.y += vec.y;
}
this.sub = function(vec)
{
this.x -= vec.x;
this.y -= vec.y;
}
this.diff = function(vec)
{
return new Vector(this.x-vec.x, this.y-vec.y);
}
this.distance = function(vec)
{
var x = this.x-vec.x;
var y = this.y-vec.y;
return Math.sqrt(x*x+y*y);
}
this.dot = function(vec)
{
return this.x*vec.x+this.y*vec.y;
}
this.equals = function(vec)
{
return this.x == vec.x && this.y == vec.y;
}
this.orthogonal = function()
{
return new Vector(this.y, -this.x);
}
this.distanceToLine = function(v0, v1)
{
var sqrLen = v1.diff(v0).sqrLength();
var u = ((this.x-v0.x)*(v1.x-v0.x)+(this.y-v0.y)*(v1.y-v0.y))/sqrLen;
var v1c = v1.diff(v0);
v1c.scale(u);
var pl = v0.clone();
pl.add(v1c);
return this.distance(pl);
}
};
module.exports = Vector