-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathtf.js
331 lines (268 loc) · 8.45 KB
/
tf.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
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import { rosbridge } from './rosbridge.js';
/* class TimeStampedData {
constructor(maxLength) {
this.maxLength = maxLength;
this.data = [];
this.index = new Map();
}
getKey({ secs, nsecs }) {
// Use the provided data structure to form a unique key
// The precision should be enough for up to 1ns resolution over approximately 285 years.
return secs * 1e9 + nsecs;
}
add(key, value) {
const timestampKey = this.getKey(key);
// If we're at maximum capacity, remove the oldest item
if (this.data.length >= this.maxLength) {
const oldestKey = this.getKey(this.data[0].key);
this.index.delete(oldestKey);
this.data.shift();
}
// Add the new item
this.data.push({ key, value });
this.index.set(timestampKey, value);
}
get(key) {
const timestampKey = this.getKey(key);
return this.index.get(timestampKey);
}
find(key) {
const timestampKey = this.getKey(key);
const keys = Array.from(this.index.keys());
console.log("Find: ",timestampKey," in ",keys);
// Find the key closest to the input timestamp
const closestKey = keys.reduce((prev, curr) => {
return (Math.abs(curr - timestampKey) < Math.abs(prev - timestampKey) ? curr : prev);
});
return this.index.get(closestKey);
}
} */
export function applyRotation(vector, r, inverse){
if(inverse)
r = r.inverse();
const v = r.rotateVector([
vector.x,
vector.y,
vector.z
]);
return {
x: v[0],
y: v[1],
z: v[2]
}
}
export class TF {
constructor() {
this.fixed_frame = '';
this.transforms = {};
this.absoluteTransforms = {};
//this.absoluteTransformsHistory = new TimeStampedData(20);
this.frame_list = new Set();
this.frame_timestamps = {};
this.frame_headerstamps = {};
this.tf_topic = new ROSLIB.Topic({
ros: rosbridge.ros,
name: 'vizanti/tf_consolidated',
messageType: 'tf/tfMessage',
throttle_rate: 33,
compression: "cbor"
});
this.tf_listener = this.tf_topic.subscribe((msg) => {
//local timestamping for removing inactive frames
const time_stamp = new Date();
msg.transforms.forEach((pose) => {
this.frame_timestamps[pose.child_frame_id] = time_stamp;
this.frame_timestamps[pose.header.frame_id] = time_stamp;
this.updateFrameTimestamp(pose.child_frame_id,pose.header.stamp)
})
this.updateTransforms(msg.transforms, false);
//this.absoluteTransformsHistory.add(msg.transforms[0].header.stamp, this.absoluteTransforms);
});
this.tf_static_topic = new ROSLIB.Topic({
ros: rosbridge.ros,
name: 'tf_static',
messageType: 'tf/tfMessage',
compression: "cbor"
});
this.tf_static_listener = this.tf_static_topic.subscribe((msg) => {
this.updateTransforms(msg.transforms, true);
});
this.event_timestamp = performance.now();
window.addEventListener("view_changed", ()=> {
this.event_timestamp = performance.now();
});
//removing inactive TF frames
setInterval(()=>{
const now = new Date()
let deleted_anything = false;
for (const [frame_id, time_stamp] of Object.entries(this.frame_timestamps)) {
if(now - time_stamp > 1000 * 100){
delete this.frame_list[frame_id];
delete this.transforms[frame_id];
delete this.absoluteTransforms[frame_id];
delete this.frame_headerstamps[frame_id];
deleted_anything = true;
}
}
if(deleted_anything){
window.dispatchEvent(new Event("tf_changed"));
}
},5000)
}
updateFrameTimestamp(frame_id, stamp){
this.frame_headerstamps[frame_id] = stamp;
//update all child frames that were moved as well
for (const frame in this.transforms) {
if (this.transforms[frame].parent === frame_id) {
this.frame_headerstamps[frame] = stamp; //we assume that the frame we just got is newer than what we already have
this.updateFrameTimestamp(frame, stamp);
}
}
}
/* interpolateTransforms() {
if (this.lastReceivedTransforms !== null && this.previousTransforms !== null && performance.now() - this.lastReceivedTime > 15) {
const prevdelta = (this.lastReceivedTime - this.previousTime) / 1000;
let delta = ((performance.now() - this.lastReceivedTime) / 1000) / prevdelta;
console.log("interpolation")
delta *= 0.005;
const transformsMap = new Map();
this.previousTransforms.forEach(transform => {
transformsMap.set(transform.child_frame_id, { previous: transform });
});
this.lastReceivedTransforms.forEach(transform => {
if (transformsMap.has(transform.child_frame_id)) {
transformsMap.get(transform.child_frame_id).current = transform;
}
});
const interpolatedTransforms = [];
transformsMap.forEach(({ previous, current }, child_frame_id) => {
if (current) {
const positionDelta = {
x: current.transform.translation.x - previous.transform.translation.x,
y: current.transform.translation.y - previous.transform.translation.y
};
const velocity = {
x: positionDelta.x * delta,
y: positionDelta.y * delta,
};
const interpolatedTransform = {
child_frame_id: child_frame_id,
header: current.header,
transform: {
translation: {
x: current.transform.translation.x + velocity.x,
y: current.transform.translation.y + velocity.y,
z: current.transform.translation.z
},
rotation: current.transform.rotation
}
};
interpolatedTransforms.push(interpolatedTransform);
}
});
this.updateTransforms(interpolatedTransforms);
}
} */
async sendUpdateEvent(){
if(performance.now() - this.event_timestamp > 12){
window.dispatchEvent(new Event("tf_changed"));
this.event_timestamp = performance.now();
}
}
getPathToRoot(frame) {
const currentFrame = this.transforms[frame];
if (!currentFrame) {
return [frame];
}
if (!currentFrame.parent) {
return [frame];
}
return [frame].concat(this.getPathToRoot(currentFrame.parent));
}
findPath(startFrame, endFrame) {
const p = this.getPathToRoot(startFrame);
const q = this.getPathToRoot(endFrame);
let common = null;
while (p.length > 0 && q.length > 0 && p[p.length - 1] === q[q.length - 1]) {
common = p.pop();
q.pop();
}
return p.concat(common, q.reverse());
}
updateTransforms(newtransforms) {
newtransforms.forEach((pose) => {
const childFrameId = pose.child_frame_id;
const parentFrameId = pose.header.frame_id;
this.frame_list.add(childFrameId);
this.frame_list.add(parentFrameId);
this.transforms[childFrameId] = {
translation: pose.transform.translation,
rotation: new Quaternion(
pose.transform.rotation.w,
pose.transform.rotation.x,
pose.transform.rotation.y,
pose.transform.rotation.z
),
parent: parentFrameId
};
});
this.recalculateAbsoluteTransforms();
this.sendUpdateEvent();
}
setFixedFrame(newframe) {
this.fixed_frame = newframe;
this.recalculateAbsoluteTransforms();
window.dispatchEvent(new Event("tf_fixed_frame_changed"));
}
recalculateAbsoluteTransforms() {
for (const key of this.frame_list.values()) {
this.absoluteTransforms[key] = this.transformPose(key, this.fixed_frame, {x: 0, y:0, z:0}, new Quaternion());
}
}
getZeroFrame(){
return {
translation:{x: 0, y:0, z:0},
rotation: new Quaternion()
}
}
transformPose(sourceFrame, targetFrame, inputVector, inputQuat) {
let outputVector = Object.assign({}, inputVector);
let outputQuat = new Quaternion(inputQuat);
if(sourceFrame == targetFrame){
return {
translation: outputVector,
rotation: outputQuat
};
}
const path = this.findPath(sourceFrame, targetFrame);
for (let i = 0; i < path.length - 1; i++) {
let source = this.transforms[path[i]];
if(!source)
source = this.getZeroFrame();
if(source.parent == path[i+1]){
outputQuat = source.rotation.mul(outputQuat);
outputVector = applyRotation(outputVector, source.rotation, false);
outputVector.x += source.translation.x;
outputVector.y += source.translation.y;
outputVector.z += source.translation.z;
}else{
source = this.transforms[path[i+1]];
if(!source)
source = this.getZeroFrame();
outputQuat = source.rotation.inverse().mul(outputQuat);
outputVector.x -= source.translation.x;
outputVector.y -= source.translation.y;
outputVector.z -= source.translation.z;
outputVector = applyRotation(outputVector, source.rotation, true);
}
}
return {
translation: outputVector,
rotation: outputQuat
};
}
getTimeStampDelta(timestamp1, timestamp2) {
return timestamp2.secs - timestamp1.secs + ((timestamp2.nsecs - timestamp1.nsecs) / 1e9);
}
}
export let tf = new TF();