-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvec.py
80 lines (59 loc) · 1.88 KB
/
vec.py
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
import math
import svg
svg.Length.__neg__ = lambda self: svg.Length(self.value, self.unit)
class Vec:
def __init__(self, x, y):
self.x = x
self.y = y
def copy(self) -> "Vec":
return Vec(self.x, self.y)
@property
def magnitude(self) -> float:
return math.sqrt(self.x * self.x + self.y * self.y)
@property
def normalised(self) -> float:
return self * (1 / self.magnitude)
def dot(self, other: "Vec") -> float:
return self.x * other.x + self.y * other.y
def __neg__(self):
return Vec(-self.x, -self.y)
def __mul__(self, n: float):
return Vec(self.x * n, self.y * n)
def __add__(self, v: "Vec"):
return Vec(self.x + v.x, self.y + v.y)
def __sub__(self, v: "Vec"):
return Vec(self.x - v.x, self.y - v.y)
def __div__(self, n: float | int):
return Vec(self.x / n, self.y / n)
@property
def length(self):
return math.sqrt(self.x * self.x + self.y * self.y)
def dist(self, v: "Vec") -> float:
return (self - v).length
def __iter__(self):
yield self.x
yield self.y
def __getitem__(self, key):
if key == 0 or key == "x":
return self.x
if key == 1 or key == "y":
return self.y
raise IndexError
def keys(self):
return ["x","y"]
def __repr__(self):
return f"({self.x}, {self.y})"
# supports quick unpacking for svg funcs
# Also supports readers thinking "why would you do this??"
@property
def v1(self):
return {"x1": self.x, "y1": self.y}
@property
def v2(self):
return {"x2": self.x, "y2": self.y}
@property
def c(self):
return {"cx": self.x, "cy": self.y}
@property
def bla(self):
return Vec(f"{self.x.value}{self.x.unit}", f"{self.y.value}{self.y.unit}")