-
Notifications
You must be signed in to change notification settings - Fork 1
/
Waypoint.py
277 lines (217 loc) · 8.16 KB
/
Waypoint.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
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
from scipy.spatial.transform.rotation import Rotation
import copy
import numpy as np
import numpy.typing as npt
class PositionVector:
"""A simple numpy based Vector class for positions"""
def __init__(self, *args):
if len(args) == 3:
self._data: npt.NDArray[np.float64] = np.array(args)
elif (
len(args) == 1 and isinstance(args[0], np.ndarray) and args[0].shape == (3,)
):
self._data: npt.NDArray[np.float64] = args[0].copy()
else:
self._data: npt.NDArray[np.float64] = np.zeros(shape=(3,))
def __eq__(self, other) -> bool:
return np.array_equal(self._data, other._data)
def __str__(self) -> str:
return f"PositionVector({self._data[0]}, {self._data[1]}, {self._data[2]})"
def __setitem__(self, i: int, value: float):
if i < 3 and i >= 0:
self._data[i] = value
else:
raise ValueError("Out of bounds.")
def __getitem__(self, i: int) -> float:
return float(self._data[i])
def __iter__(self):
return self._data.__iter__()
def __add__(self, other):
return PositionVector(self._data + other._data)
def __sub__(self, other):
return PositionVector(self._data - other._data)
@property
def x(self) -> float:
return self._data[0]
@x.setter
def x(self, x: float):
self._data[0] = x
@property
def y(self) -> float:
return self._data[1]
@y.setter
def y(self, y: float):
self._data[1] = y
@property
def z(self) -> float:
return self._data[2]
@z.setter
def z(self, z: float):
self._data[2] = z
def normalize(self) -> 'PositionVector':
norm = self.length()
if norm != 0:
self._data /= norm
return self
def length(self) -> float:
return np.linalg.norm(self._data)
def as_array(self) -> npt.NDArray[np.float64]:
return self._data
class WaypointVolume:
def __init__(self, bead_width: float, bead_height: float, extrusion_scale: float):
"""
extrusion_scale: the relative amount of material to be extruded
bead_width: bead width
bead_height: bead height
"""
self.bead_width = bead_width
self.bead_height = bead_height
self.extrusion_scale = extrusion_scale
def __eq__(self, other):
return (
self.bead_height == other.bead_height
and self.bead_width == other.bead_width
and self.extrusion_scale == other.extrusion_scale
)
def serialize(self):
return self.bead_width, self.bead_height, self.extrusion_scale
def __str__(self):
return f"WaypointVolume(bead_width={self.bead_width}, bead_height={self.bead_height}, extrusion_scale={self.extrusion_scale})"
class Waypoint:
def __init__(self, *args):
super().__init__()
self._volume : WaypointVolume = WaypointVolume(0.0, 0.0, 0.0)
self._position : PositionVector = PositionVector(0.0, 0.0, 0.0)
self._rotation : Rotation = Rotation([0.0, 0.0, 0.0, 1.0])
num_args = len(args)
if num_args >= 1:
if isinstance(args[0], np.ndarray) and args[0].shape == (3,):
self._position = PositionVector(args[0])
else:
raise TypeError('First argument must be of type "Vector".')
if num_args >= 2:
if isinstance(args[1], Rotation):
self._rotation = args[1]
elif isinstance(args[1], np.ndarray) and args[1].shape == (3,):
self.normal = args[1]
else:
raise TypeError('Second arg must be of type "Rotation" or "Vector".')
if num_args == 3:
if isinstance(args[2], WaypointVolume):
self._volume = args[2]
else:
raise TypeError('Third argument must by of type "WaypointVolume".')
if num_args > 3:
raise Exception("Too many arguments")
def __str__(self):
return "Waypoint(X={}, Y={}, Z={}, x0={}, x1i={}, x2j={}, x3k={}, volume={})".format(
*self._position, *self._rotation.as_quat(), self._volume
)
def __eq__(self, other):
return (
self._volume == other.volume
and np.allclose(self._position, other._position)
and np.allclose(self._rotation.as_quat(), other._rotation.as_quat())
)
@property
def volume(self) -> WaypointVolume:
return self._volume
@volume.setter
def volume(self, volume: WaypointVolume):
if not isinstance(volume, WaypointVolume):
raise TypeError("This only supports WaypointVolume.")
self._volume = volume
@property
def position(self) -> PositionVector:
"""For legacy reasons, this returns not the Vector, but the underlying numpy array
Returns:
numpy.ndarray: array containing the position data [x,y,z]
"""
return self._position
@position.setter
def position(self, pos: PositionVector):
"""For legacy reasons, this manipulates not the vector, but the underlying numpy array directly
Args:
pos (np.ndarray): _description_
"""
if not isinstance(pos, PositionVector):
raise TypeError("This only supports PositionVector.")
self._position = pos
@property
def x(self) -> float:
return self._position[0]
@x.setter
def x(self, x: float):
self._position[0] = x
@property
def y(self) -> float:
return self._position[1]
@y.setter
def y(self, y: float):
self._position[1] = y
@property
def z(self) -> float:
return self._position[2]
@z.setter
def z(self, z: float):
self._position[2] = z
# NOTE: the order of euler angles depends on the machine, so this is only true for some cases
# It's best not to use these angles directly, but to derive them from the quaternions in a machine specific post-processor
@property
def a(self) -> float:
return self._rotation.as_euler("XYZ", degrees=True)[0]
@a.setter
def a(self, value):
self._rotation = Rotation.from_euler(
"XYZ", [value, self.b, self.c], degrees=True
)
@property
def b(self) -> float:
return self._rotation.as_euler("XYZ", degrees=True)[1]
@b.setter
def b(self, value: float):
self._rotation = Rotation.from_euler(
"XYZ", [self.a, value, self.c], degrees=True
)
@property
def c(self) -> float:
return self._rotation.as_euler("XYZ", degrees=True)[2]
@c.setter
def c(self, value: float):
self._rotation = Rotation.from_euler(
"XYZ", [self.a, self.b, value], degrees=True
)
@property
def normal(self) -> npt.NDArray[np.float64]:
return self._rotation.apply(np.array([0.0, 0.0, 1.0]))
@normal.setter
def normal(self, vec: npt.NDArray[np.float64]):
# Port of FreeCAD's vector to vector rot implementation
# see https://github.com/FreeCAD/FreeCAD/blob/master/src/Base/Rotation.cpp
vec_len = np.linalg.norm(vec)
if vec_len == 0:
raise ValueError('Length of the Vector is "0.0".')
vec_norm = vec / vec_len
vecz_norm = np.array([0.0, 0.0, 1.0])
dot = np.dot(vec_norm, vecz_norm)
cross = np.cross(vecz_norm, vec_norm)
cross_len = np.linalg.norm(cross)
if cross_len == 0.0:
# Parallel vectors
if dot > 0:
self._rotation = Rotation.from_quat((0.0, 0.0, 0.0, 1.0))
else:
self._rotation = Rotation.from_quat((0.0, 1.0, 0.0, 0.0))
else:
# Vectors not parallel
cross_norm = cross / cross_len
angle = np.arccos(dot)
self._rotation = Rotation.from_rotvec(angle * cross_norm)
# Finally a sanity assertion
np.testing.assert_almost_equal(vec_norm, self.normal, 2)
@property
def rounded_normal(self) -> npt.NDArray[np.float64]:
normal = self.normal.round(decimals=2)
return normal / np.linalg.norm(normal)
def copy(self):
return copy.deepcopy(self)