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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
use crate::CartesianTreeError;
use crate::Pose;
use crate::lazy_access::LazyRotation;
use crate::lazy_access::LazyTranslation;
use crate::rotation::Rotation;
use crate::tree::Walking;
use crate::tree::{HasChildren, HasParent, NodeEquality};
use nalgebra::UnitQuaternion;
use nalgebra::{Isometry3, Translation3, Vector3};
use std::cell::RefCell;
use std::ops::Add;
use std::ops::Mul;
use std::ops::Sub;
use std::rc::{Rc, Weak};
use serde::{Deserialize, Serialize};
use serde_json;
use uuid::Uuid;
/// Represents a coordinate frame in a Cartesian tree structure.
///
/// Each frame can have one parent and multiple children. The frame stores its
/// transformation (position and orientation) relative to its parent.
///
/// Root frames (created via `Frame::new_origin`) have no parent and use the identity transform.
#[derive(Clone, Debug)]
pub struct Frame {
pub(crate) data: Rc<RefCell<FrameData>>,
}
#[derive(Debug)]
pub(crate) struct FrameData {
/// The name of the frame (must be unique among siblings).
pub(crate) name: String,
/// Reference to the parent frame.
parent: Option<Weak<RefCell<FrameData>>>,
/// Transformation from this frame to its parent frame.
transform_to_parent: Isometry3<f64>,
/// Child frames directly connected to this frame.
children: Vec<Frame>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct SerialFrame {
name: String,
position: Vector3<f64>,
orientation: UnitQuaternion<f64>,
children: Vec<SerialFrame>,
}
impl Frame {
/// Creates a new root frame (origin) with the given name.
///
/// The origin has no parent and uses the identity transform.
/// # Arguments
/// - `name`: The name of the root frame.
///
/// # Example
/// ```
/// use cartesian_tree::Frame;
///
/// let origin = Frame::new_origin("world");
/// ```
pub fn new_origin(name: impl Into<String>) -> Self {
Self {
data: Rc::new(RefCell::new(FrameData {
name: name.into(),
parent: None,
children: Vec::new(),
transform_to_parent: Isometry3::identity(),
})),
}
}
pub(crate) fn borrow(&self) -> std::cell::Ref<'_, FrameData> {
self.data.borrow()
}
fn borrow_mut(&self) -> std::cell::RefMut<'_, FrameData> {
self.data.borrow_mut()
}
pub(crate) fn downgrade(&self) -> Weak<RefCell<FrameData>> {
Rc::downgrade(&self.data)
}
pub(crate) fn walk_up_and_transform(
&self,
target: &Self,
) -> Result<Isometry3<f64>, CartesianTreeError> {
let mut transform = Isometry3::identity();
let mut current = self.clone();
while !current.is_same(target) {
let transform_to_its_parent = {
// Scope borrow
let current_data = current.borrow();
// If current frame is root and not target, then target is not an ancestor.
if current_data.parent.is_none() {
return Err(CartesianTreeError::IsNoAncestor(target.name(), self.name()));
}
current_data.transform_to_parent
};
transform = transform_to_its_parent * transform;
let parent_frame_opt = current.parent();
current = parent_frame_opt
.ok_or_else(|| CartesianTreeError::IsNoAncestor(target.name(), self.name()))?;
}
Ok(transform)
}
/// Returns the name of the frame.
#[must_use]
pub fn name(&self) -> String {
self.borrow().name.clone()
}
/// Returns the transformation from this frame to its parent frame.
///
/// # Returns
/// - The isometry from this frame to its parent frame.
///
/// # Errors
/// Returns a [`CartesianTreeError`] if:
/// - The frame has no parent.
pub fn transformation(&self) -> Result<Isometry3<f64>, CartesianTreeError> {
if self.parent().is_none() {
return Err(CartesianTreeError::RootHasNoParent(self.name()));
}
Ok(self.borrow().transform_to_parent)
}
/// Returns the position of this frame relative to its parent frame.
///
/// # Returns
/// The position of the frame in its parent frame.
#[must_use]
pub fn position(&self) -> Vector3<f64> {
self.borrow().transform_to_parent.translation.vector
}
/// Returns the orientation of this frame relative to its parent frame.
///
/// # Returns
/// The orientation of the frame in its parent frame.
#[must_use]
pub fn orientation(&self) -> Rotation {
self.borrow().transform_to_parent.rotation.into()
}
/// Sets the frame's transformation relative to its parent.
///
/// This method modifies the frame's position and orientation relative to its parent frame.
/// It fails if the frame is a root frame (i.e., has no parent).
///
/// # Arguments
/// - `position`: A 3D vector representing the new translational offset from the parent.
/// - `orientation`: An orientation convertible into a unit quaternion for new orientational offset from the parent.
///
/// # Returns
/// - `Ok(())` if the transformation was updated successfully.
///
/// # Errors
/// Returns a [`CartesianTreeError`] if:
/// - The frame has no parent (i.e., the root frame).
///
/// # Example
/// ```
/// use cartesian_tree::Frame;
/// use nalgebra::{Vector3, UnitQuaternion};
///
/// let root = Frame::new_origin("root");
/// let child = root
/// .add_child("camera", Vector3::new(0.0, 0.0, 1.0), UnitQuaternion::identity())
/// .unwrap();
/// child.set(Vector3::new(1.0, 0.0, 0.0), UnitQuaternion::identity())
/// .unwrap();
/// ```
pub fn set(
&self,
position: Vector3<f64>,
orientation: impl Into<Rotation>,
) -> Result<(), CartesianTreeError> {
if self.parent().is_none() {
return Err(CartesianTreeError::CannotUpdateRootTransform(self.name()));
}
self.borrow_mut().transform_to_parent = Isometry3::from_parts(
Translation3::from(position),
orientation.into().as_quaternion(),
);
Ok(())
}
/// Applies the provided isometry interpreted in the parent frame to this frame.
///
/// This method modifies the frame's position and orientation relative to its current position and orientation.
/// It fails if the frame is a root frame (i.e., has no parent).
///
/// # Arguments
/// - `isometry`: The isometry (describing a motion in the parent frame coordinates) to apply to the current transformation.
///
/// # Returns
/// - `Ok(())` if the transformation was updated successfully.
///
/// # Errors
/// Returns a [`CartesianTreeError`] if:
/// - The frame has no parent (i.e., the root frame).
///
/// # Example
/// ```
/// use cartesian_tree::Frame;
/// use nalgebra::{Isometry3, Translation3, Vector3, UnitQuaternion};
///
/// let root = Frame::new_origin("root");
/// let child = root
/// .add_child("camera", Vector3::new(1.0, 0.0, 1.0), UnitQuaternion::identity())
/// .unwrap();
/// child.apply_in_parent_frame(&Isometry3::from_parts(Translation3::new(1.0, 0.0, 0.0), UnitQuaternion::identity()))
/// .unwrap();
///
/// ```
pub fn apply_in_parent_frame(
&self,
isometry: &Isometry3<f64>,
) -> Result<(), CartesianTreeError> {
if self.parent().is_none() {
return Err(CartesianTreeError::CannotUpdateRootTransform(self.name()));
}
let mut borrow = self.borrow_mut();
borrow.transform_to_parent = isometry * borrow.transform_to_parent;
Ok(())
}
/// Applies the provided isometry interpreted in this frame to this frame.
///
/// This method modifies the frame's position and orientation relative to its current position and orientation.
/// It fails if the frame is a root frame (i.e., has no parent).
///
/// # Arguments
/// - `isometry`: The isometry (describing a motion in this frame) to apply to the current transformation.
///
/// # Returns
/// - `Ok(())` if the transformation was updated successfully.
///
/// # Errors
/// Returns a [`CartesianTreeError`] if:
/// - The frame has no parent (i.e., the root frame).
///
/// # Example
/// ```
/// use cartesian_tree::Frame;
/// use nalgebra::{Isometry3, Translation3, Vector3, UnitQuaternion};
///
/// let root = Frame::new_origin("root");
/// let child = root
/// .add_child("camera", Vector3::zeros(), UnitQuaternion::from_euler_angles(0.0, 0.0, std::f64::consts::FRAC_PI_2))
/// .unwrap();
/// child.apply_in_local_frame(&Isometry3::from_parts(Translation3::new(1.0, 0.0, 0.0), UnitQuaternion::identity()))
/// .unwrap();
///
/// ```
pub fn apply_in_local_frame(
&self,
isometry: &Isometry3<f64>,
) -> Result<(), CartesianTreeError> {
if self.parent().is_none() {
return Err(CartesianTreeError::CannotUpdateRootTransform(self.name()));
}
let mut borrow = self.borrow_mut();
borrow.transform_to_parent *= isometry;
Ok(())
}
/// Adds a new child frame to the current frame.
///
/// The child is positioned and oriented relative to this frame.
///
/// Returns an error if a child with the same name already exists.
///
/// # Arguments
/// - `name`: The name of the new child frame.
/// - `position`: A 3D vector representing the translational offset from the parent.
/// - `orientation`: An orientation convertible into a unit quaternion.
///
/// # Returns
/// The newly added child frame.
///
/// # Errors
/// Returns a [`CartesianTreeError`] if:
/// - A child with the same name already exists.
///
/// # Example
/// ```
/// use cartesian_tree::Frame;
/// use nalgebra::{Vector3, UnitQuaternion};
///
/// let root = Frame::new_origin("base");
/// let child = root
/// .add_child("camera", Vector3::new(0.0, 0.0, 1.0), UnitQuaternion::identity())
/// .unwrap();
/// ```
pub fn add_child(
&self,
name: impl Into<String>,
position: Vector3<f64>,
orientation: impl Into<Rotation>,
) -> Result<Self, CartesianTreeError> {
let child_name = name.into();
{
let frame = self.borrow();
if frame
.children
.iter()
.any(|child| child.borrow().name == child_name)
{
return Err(CartesianTreeError::ChildNameConflict(
child_name,
self.name(),
));
}
}
let transform = Isometry3::from_parts(
Translation3::from(position),
orientation.into().as_quaternion(),
);
let child = Self {
data: Rc::new(RefCell::new(FrameData {
name: child_name,
parent: Some(Rc::downgrade(&self.data)),
children: Vec::new(),
transform_to_parent: transform,
})),
};
self.borrow_mut().children.push(child.clone());
Ok(child)
}
/// Adds a new child frame calibrated such that a reference pose, when expressed in the new frame,
/// matches the desired position and orientation.
///
/// # Arguments
/// - `name`: The name of the new child frame.
/// - `desired_position`: The desired position of the reference pose in the new frame.
/// - `desired_orientation`: The desired orientation of the reference pose in the new frame.
/// - `reference_pose`: The existing pose (in some frame A) used as the calibration reference.
///
/// # Returns
/// - The new child frame if successful.
///
/// # Errors
/// Returns a [`CartesianTreeError`] if:
/// - The reference frame is invalid.
/// - No common ancestor exists.
/// - A child with the same name already exists.
///
/// # Example
/// ```
/// use cartesian_tree::Frame;
/// use nalgebra::{Vector3, UnitQuaternion};
///
/// let root = Frame::new_origin("root");
/// let reference_pose = root.add_pose(Vector3::new(1.0, 0.0, 0.0), UnitQuaternion::identity());
/// let calibrated_child = root.calibrate_child(
/// "calibrated",
/// Vector3::zeros(),
/// UnitQuaternion::identity(),
/// &reference_pose,
/// ).unwrap();
/// ```
pub fn calibrate_child(
&self,
name: impl Into<String>,
desired_position: Vector3<f64>,
desired_orientation: impl Into<Rotation>,
reference_pose: &Pose,
) -> Result<Self, CartesianTreeError> {
let reference_frame = reference_pose.frame().ok_or_else(|| {
CartesianTreeError::FrameDropped("Reference pose frame has been dropped".to_string())
})?;
let ancestor = self.lca_with(&reference_frame).ok_or_else(|| {
CartesianTreeError::NoCommonAncestor(self.name(), reference_frame.name())
})?;
let t_reference_to_ancestor = reference_frame.walk_up_and_transform(&ancestor)?;
let t_pose_to_reference = reference_pose.transformation();
let t_pose_to_ancestor = t_reference_to_ancestor * t_pose_to_reference;
let t_parent_to_ancestor = self.walk_up_and_transform(&ancestor)?;
let t_ancestor_to_parent = t_parent_to_ancestor.inverse();
let desired_pose = Isometry3::from_parts(
Translation3::from(desired_position),
desired_orientation.into().as_quaternion(),
);
let t_calibrated_to_parent =
t_pose_to_ancestor * desired_pose.inverse() * t_ancestor_to_parent;
self.add_child(
name,
t_calibrated_to_parent.translation.vector,
t_calibrated_to_parent.rotation,
)
}
/// Adds a pose to the current frame.
///
/// # Arguments
/// - `position`: The translational part of the pose.
/// - `orientation`: The orientational part of the pose.
///
/// # Returns
/// - The newly added pose.
///
/// # Example
/// ```
/// use cartesian_tree::Frame;
/// use nalgebra::{Vector3, UnitQuaternion};
///
/// let frame = Frame::new_origin("base");
/// let pose = frame.add_pose(Vector3::new(0.5, 0.0, 0.0), UnitQuaternion::identity());
/// ```
pub fn add_pose(&self, position: Vector3<f64>, orientation: impl Into<Rotation>) -> Pose {
Pose::new(self.downgrade(), position, orientation)
}
/// Serializes the frame tree to a JSON string.
///
/// This recursively serializes the hierarchy starting from this frame (ideally the root).
/// Transforms for root frames are set to identity.
///
/// # Returns
/// The serialized tree as a JSON string.
///
/// # Errors
/// Returns a [`CartesianTreeError`] if:
/// - On deserialization failure.
pub fn to_json(&self) -> Result<String, CartesianTreeError> {
let serial = self.to_serial();
Ok(serde_json::to_string_pretty(&serial)?)
}
/// Helper function to convert the frame and its children recursively into a serializable structure.
///
/// This is used internally for JSON serialization.
fn to_serial(&self) -> SerialFrame {
let (position, orientation) = if self.parent().is_some() {
let iso = self
.transformation()
.unwrap_or_else(|_| Isometry3::identity());
(iso.translation.vector, iso.rotation)
} else {
(Vector3::zeros(), UnitQuaternion::identity())
};
SerialFrame {
name: self.name(),
position,
orientation,
children: self.children().into_iter().map(|c| c.to_serial()).collect(),
}
}
/// Applies a JSON config to this frame tree by updating matching transforms.
///
/// Deserializes the JSON to a temporary structure, then recursively updates transforms
/// where names match (partial apply; ignores unmatched frames in config).
/// Skips updating root frames (identity assumed) - assumes this frame is the root.
///
/// # Arguments
/// - `json`: The JSON string to apply.
///
/// # Returns
/// `Ok(())` if applied successfully (even if partial).
///
/// # Errors
/// Returns a [`CartesianTreeError`] if:
/// - On deserialization failure.
/// - The frame names do not match at the root.
///
pub fn apply_config(&self, json: &str) -> Result<(), CartesianTreeError> {
let serial: SerialFrame = serde_json::from_str(json)?;
self.apply_serial(&serial)
}
fn apply_serial(&self, serial: &SerialFrame) -> Result<(), CartesianTreeError> {
if self.name() != serial.name {
return Err(CartesianTreeError::Mismatch(format!(
"Frame names do not match: {} vs {}",
self.name(),
serial.name
)));
}
// only update if frame has parent
if self.parent().is_some() {
self.set(serial.position, serial.orientation)?;
}
for potential_child in &serial.children {
if let Some(child) = self
.children()
.into_iter()
.find(|c| c.name() == potential_child.name)
{
child.apply_serial(potential_child)?;
}
}
Ok(())
}
}
impl Add<LazyTranslation> for &Frame {
type Output = Frame;
fn add(self, rhs: LazyTranslation) -> Self::Output {
let auto_name = Uuid::new_v4().to_string();
let current_position = self.borrow().transform_to_parent.translation.vector;
let current_orientation = self.borrow().transform_to_parent.rotation;
let child = self
.add_child(auto_name, current_position, current_orientation)
.unwrap();
child.apply_in_parent_frame(&rhs.inner).unwrap();
child // Not sure yet what to do with errors
}
}
impl Sub<LazyTranslation> for &Frame {
type Output = Frame;
fn sub(self, rhs: LazyTranslation) -> Self::Output {
let auto_name = Uuid::new_v4().to_string();
let current_position = self.borrow().transform_to_parent.translation.vector;
let current_orientation = self.borrow().transform_to_parent.rotation;
let child = self
.add_child(auto_name, current_position, current_orientation)
.unwrap();
child.apply_in_parent_frame(&rhs.inner.inverse()).unwrap();
child // Not sure yet what to do with errors
}
}
impl Mul<LazyRotation> for &Frame {
type Output = Frame;
fn mul(self, rhs: LazyRotation) -> Self::Output {
let auto_name = Uuid::new_v4().to_string();
let current_position = self.borrow().transform_to_parent.translation.vector;
let current_orientation = self.borrow().transform_to_parent.rotation;
let child = self
.add_child(auto_name, current_position, current_orientation)
.unwrap();
child.apply_in_local_frame(&rhs.inner).unwrap();
child // Not sure yet what to do with errors
}
}
impl HasParent for Frame {
type Node = Self;
fn parent(&self) -> Option<Self::Node> {
self.borrow()
.parent
.clone()
.and_then(|data_weak| data_weak.upgrade().map(|data_rc| Self { data: data_rc }))
}
}
impl NodeEquality for Frame {
fn is_same(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.data, &other.data)
}
}
impl HasChildren for Frame {
type Node = Self;
fn children(&self) -> Vec<Self> {
self.borrow().children.clone()
}
}
#[cfg(test)]
mod tests {
use crate::lazy_access::{rz, y, z};
use super::*;
use approx::assert_relative_eq;
use nalgebra::{UnitQuaternion, Vector3};
#[test]
fn create_origin_frame() {
let root = Frame::new_origin("world");
let root_borrow = root.borrow();
assert_eq!(root_borrow.name, "world");
assert!(root_borrow.parent.is_none());
assert_eq!(root_borrow.children.len(), 0);
}
#[test]
fn add_child_frame_with_quaternion() {
let root = Frame::new_origin("world");
let child = root
.add_child(
"dummy",
Vector3::new(1.0, 0.0, 0.0),
UnitQuaternion::identity(),
)
.unwrap();
let root_borrow = root.borrow();
assert_eq!(root_borrow.children.len(), 1);
let child_borrow = child.borrow();
assert_eq!(child_borrow.name, "dummy");
assert!(child_borrow.parent.is_some());
let parent_name = child_borrow
.parent
.as_ref()
.unwrap()
.upgrade()
.unwrap()
.borrow()
.name
.clone();
assert_eq!(parent_name, "world");
}
#[test]
fn add_child_frame_with_rpy() {
let root = Frame::new_origin("world");
let child = root
.add_child(
"dummy",
Vector3::new(0.0, 1.0, 0.0),
Rotation::from_rpy(0.0, 0.0, std::f64::consts::FRAC_PI_2),
)
.unwrap();
let child_borrow = child.borrow();
assert_eq!(child_borrow.name, "dummy");
let rotation = child_borrow.transform_to_parent.rotation;
let expected = UnitQuaternion::from_euler_angles(0.0, 0.0, std::f64::consts::FRAC_PI_2);
assert!((rotation.angle() - expected.angle()).abs() < 1e-10);
}
#[test]
fn test_child_frame_transform_to_parent() {
let root = Frame::new_origin("world");
let child = root
.add_child(
"dummy",
Vector3::new(0.0, 0.0, 1.0),
UnitQuaternion::identity(),
)
.unwrap();
let transform = child.transformation().unwrap();
assert_eq!(transform.translation.vector, Vector3::new(0.0, 0.0, 1.0));
assert_eq!(transform.rotation, UnitQuaternion::identity());
assert_eq!(child.position(), Vector3::new(0.0, 0.0, 1.0));
assert_eq!(
child.orientation().as_quaternion(),
UnitQuaternion::identity()
);
}
#[test]
fn multiple_child_frames() {
let root = Frame::new_origin("world");
let a = root
.add_child("a", Vector3::new(1.0, 0.0, 0.0), UnitQuaternion::identity())
.unwrap();
let b = root
.add_child("b", Vector3::new(0.0, 1.0, 0.0), UnitQuaternion::identity())
.unwrap();
let root_borrow = root.borrow();
assert_eq!(root_borrow.children.len(), 2);
let a_borrow = a.borrow();
let b_borrow = b.borrow();
assert_eq!(
a_borrow
.parent
.as_ref()
.unwrap()
.upgrade()
.unwrap()
.borrow()
.name,
"world"
);
assert_eq!(
b_borrow
.parent
.as_ref()
.unwrap()
.upgrade()
.unwrap()
.borrow()
.name,
"world"
);
}
#[test]
fn reject_duplicate_child_name() {
let root = Frame::new_origin("world");
let _ = root
.add_child(
"duplicate",
Vector3::new(1.0, 0.0, 0.0),
UnitQuaternion::identity(),
)
.unwrap();
let result = root.add_child(
"duplicate",
Vector3::new(2.0, 0.0, 0.0),
UnitQuaternion::identity(),
);
assert!(result.is_err());
}
#[test]
#[should_panic(expected = "already borrowed")]
fn test_borrow_conflict() {
let frame = Frame::new_origin("root");
let _borrow = frame.borrow(); // Immutable borrow
frame.borrow_mut(); // Should panic
}
#[test]
fn test_add_pose_to_frame() {
let frame = Frame::new_origin("dummy");
let pose = frame.add_pose(Vector3::new(1.0, 2.0, 3.0), UnitQuaternion::identity());
assert_eq!(pose.frame().unwrap().name(), "dummy");
}
#[test]
fn test_set_transform() {
let root = Frame::new_origin("root");
let child = root
.add_child(
"dummy",
Vector3::new(0.0, 0.0, 1.0),
UnitQuaternion::identity(),
)
.unwrap();
child
.set(Vector3::new(1.0, 0.0, 0.0), UnitQuaternion::identity())
.unwrap();
assert_eq!(
child.transformation().unwrap().translation.vector,
Vector3::new(1.0, 0.0, 0.0)
);
// Test root frame error
assert!(
root.set(Vector3::new(1.0, 0.0, 0.0), UnitQuaternion::identity())
.is_err()
);
}
#[test]
fn test_apply_in_parent_frame() {
let root = Frame::new_origin("root");
let child = root
.add_child(
"dummy",
Vector3::new(1.0, 0.0, 1.0),
UnitQuaternion::identity(),
)
.unwrap();
child
.apply_in_parent_frame(&Isometry3::from_parts(
Translation3::identity(),
UnitQuaternion::from_euler_angles(0.0, 0.0, std::f64::consts::FRAC_PI_2),
))
.unwrap();
assert_relative_eq!(
child.transformation().unwrap().translation.vector,
Vector3::new(0.0, 1.0, 1.0),
epsilon = 1e-10
);
child
.apply_in_parent_frame(&Isometry3::from_parts(
Translation3::new(1.0, 0.0, 1.0),
UnitQuaternion::identity(),
))
.unwrap();
assert_relative_eq!(
child.transformation().unwrap().translation.vector,
Vector3::new(1.0, 1.0, 2.0),
epsilon = 1e-10
);
// Test root frame error
assert!(
root.set(Vector3::new(1.0, 0.0, 0.0), UnitQuaternion::identity())
.is_err()
);
}
#[test]
fn test_apply_in_local_frame() {
let root = Frame::new_origin("root");
let child = root
.add_child(
"dummy",
Vector3::zeros(),
UnitQuaternion::from_euler_angles(0.0, 0.0, std::f64::consts::FRAC_PI_2),
)
.unwrap();
child
.apply_in_local_frame(&Isometry3::from_parts(
Translation3::new(1.0, 0.0, 0.0),
UnitQuaternion::identity(),
))
.unwrap();
assert_relative_eq!(
child.transformation().unwrap().translation.vector,
Vector3::new(0.0, 1.0, 0.0),
epsilon = 1e-10
);
child
.apply_in_local_frame(&Isometry3::from_parts(
Translation3::identity(),
UnitQuaternion::from_euler_angles(0.0, 0.0, std::f64::consts::FRAC_PI_2),
))
.unwrap();
assert_relative_eq!(
child.transformation().unwrap().translation.vector,
Vector3::new(0.0, 1.0, 0.0),
epsilon = 1e-10
);
let (roll, pitch, yaw) = child.transformation().unwrap().rotation.euler_angles();
assert_relative_eq!(roll, 0.0, epsilon = 1e-10);
assert_relative_eq!(pitch, 0.0, epsilon = 1e-10);
assert_relative_eq!(yaw, std::f64::consts::PI, epsilon = 1e-10);
// Test root frame error
assert!(
root.set(Vector3::new(1.0, 0.0, 0.0), UnitQuaternion::identity())
.is_err()
);
}
#[test]
fn test_pose_apply_in_parent_frame() {
let root = Frame::new_origin("root");
let mut pose = root.add_pose(Vector3::new(1.0, 0.0, 1.0), UnitQuaternion::identity());
pose.apply_in_parent_frame(&Isometry3::from_parts(
Translation3::identity(),
UnitQuaternion::from_euler_angles(0.0, 0.0, std::f64::consts::FRAC_PI_2),
));
assert_relative_eq!(
pose.transformation().translation.vector,
Vector3::new(0.0, 1.0, 1.0),
epsilon = 1e-10
);
pose.apply_in_parent_frame(&Isometry3::from_parts(
Translation3::new(1.0, 0.0, 1.0),
UnitQuaternion::identity(),
));
assert_relative_eq!(
pose.transformation().translation.vector,
Vector3::new(1.0, 1.0, 2.0),
epsilon = 1e-10
);
}
#[test]
fn test_pose_apply_in_local_frame() {
let root = Frame::new_origin("root");
let mut pose = root.add_pose(
Vector3::zeros(),
UnitQuaternion::from_euler_angles(0.0, 0.0, std::f64::consts::FRAC_PI_2),
);
pose.apply_in_local_frame(&Isometry3::from_parts(
Translation3::new(1.0, 0.0, 0.0),
UnitQuaternion::identity(),
));
assert_relative_eq!(
pose.transformation().translation.vector,
Vector3::new(0.0, 1.0, 0.0),
epsilon = 1e-10
);
pose.apply_in_local_frame(&Isometry3::from_parts(
Translation3::identity(),
UnitQuaternion::from_euler_angles(0.0, 0.0, std::f64::consts::FRAC_PI_2),
));
assert_relative_eq!(
pose.transformation().translation.vector,
Vector3::new(0.0, 1.0, 0.0),
epsilon = 1e-10
);
let (roll, pitch, yaw) = pose.transformation().rotation.euler_angles();
assert_relative_eq!(roll, 0.0, epsilon = 1e-10);
assert_relative_eq!(pitch, 0.0, epsilon = 1e-10);
assert_relative_eq!(yaw, std::f64::consts::PI, epsilon = 1e-10);
// Test root frame error
assert!(
root.set(Vector3::new(1.0, 0.0, 0.0), UnitQuaternion::identity())
.is_err()
);
}
#[test]
fn test_pose_transform_to_parent() {
let root = Frame::new_origin("root");
let pose = root.add_pose(Vector3::new(1.0, 2.0, 3.0), UnitQuaternion::identity());
let transformation = pose.transformation();
assert_eq!(
transformation.translation.vector,
Vector3::new(1.0, 2.0, 3.0)
);
assert_eq!(transformation.rotation, UnitQuaternion::identity());
assert_eq!(pose.position(), Vector3::new(1.0, 2.0, 3.0));
assert_eq!(
pose.orientation().as_quaternion(),
UnitQuaternion::identity()
);
}
#[test]
fn test_pose_transformation_between_frames() {
let root = Frame::new_origin("root");
let f1 = root
.add_child(
"f1",
Vector3::new(1.0, 0.0, 0.0),
UnitQuaternion::identity(),
)
.unwrap();
let f2 = f1
.add_child(
"f2",
Vector3::new(0.0, 2.0, 0.0),
UnitQuaternion::identity(),
)
.unwrap();
let pose_in_f2 = f2.add_pose(Vector3::new(1.0, 1.0, 0.0), UnitQuaternion::identity());
let pose_in_root = pose_in_f2.in_frame(&root).unwrap();
let pos = pose_in_root.transformation().translation.vector;
// Total offset should be: f2 (0,2,0) + pose (1,1,0) + f1 (1,0,0)
assert!((pos - Vector3::new(2.0, 3.0, 0.0)).norm() < 1e-6);
}
#[test]
fn test_calibrate_child() {
let root = Frame::new_origin("root");
let reference_pose = root.add_pose(
Vector3::new(1.0, 2.0, 3.0),
UnitQuaternion::from_euler_angles(0.0, 0.0, std::f64::consts::FRAC_PI_2),
);
// Calibrate a child where the reference pose should appear at (0,0,0) with identity orientation.
let calibrated_frame = root
.calibrate_child(
"calibrated",
Vector3::zeros(),
UnitQuaternion::identity(),
&reference_pose,
)
.unwrap();
let pose_in_calibrated = reference_pose.in_frame(&calibrated_frame).unwrap();
let transformation = pose_in_calibrated.transformation();
assert!((transformation.translation.vector - Vector3::zeros()).norm() < 1e-6);
assert!((transformation.rotation.angle() - 0.0).abs() < 1e-6);
// Verify the child's transform matches the reference pose's original transform.
let calibrated_transformation = calibrated_frame.transformation().unwrap();
assert!(
(calibrated_transformation.translation.vector - Vector3::new(1.0, 2.0, 3.0)).norm()
< 1e-6
);
assert!(
(calibrated_transformation.rotation.angle() - std::f64::consts::FRAC_PI_2).abs() < 1e-6
);
}
#[test]
fn test_to_json_and_apply_config() {
let root = Frame::new_origin("root");
let _ = root
.add_child(
"child",
Vector3::new(1.0, 2.0, 3.0),
UnitQuaternion::from_euler_angles(0.1, 0.2, 0.3),
)
.unwrap();
let json = root.to_json().unwrap();
// roughly verify JSON structure
assert!(json.contains(r#""name": "root""#));
assert!(json.contains(r#""name": "child""#));
// Create a default tree with different transforms
let default_root = Frame::new_origin("root");
default_root
.add_child(
"child",
Vector3::new(0.0, 0.0, 0.0),
UnitQuaternion::identity(),
)
.unwrap();
// Apply config
default_root.apply_config(&json).unwrap();
// Verify child transform updated
let updated_child = default_root
.children()
.into_iter()
.find(|c| c.name() == "child")
.unwrap();
let iso = updated_child.transformation().unwrap();
assert_eq!(iso.translation.vector, Vector3::new(1.0, 2.0, 3.0));
let (r, p, y) = iso.rotation.euler_angles();
assert!((r - 0.1).abs() < 1e-6);
assert!((p - 0.2).abs() < 1e-6);
assert!((y - 0.3).abs() < 1e-6);
// Test partial: If config has extra, ignore it
let partial_json = r#"
{
"name": "root",
"position": [0.0, 0.0, 0.0],
"orientation": [0.0, 0.0, 0.0, 1.0],
"children": [
{
"name": "child",
"position": [4.0, 5.0, 6.0],
"orientation": [0.0, 0.0, 0.0, 1.0],
"children": []
},
{
"name": "extra",
"position": [0.0, 0.0, 0.0],
"orientation": [0.0, 0.0, 0.0, 1.0],
"children": []
}
]
}
"#;
default_root.apply_config(partial_json).unwrap();
let updated_child = default_root
.children()
.into_iter()
.find(|c| c.name() == "child")
.unwrap();
assert_eq!(
updated_child.transformation().unwrap().translation.vector,
Vector3::new(4.0, 5.0, 6.0)
);
// Test mismatch
let mismatch_json = r#"
{
"name": "wrong_root",
"position": [0.0, 0.0, 0.0],
"orientation": [0.0, 0.0, 0.0, 1.0],
"children": []
}
"#;
assert!(default_root.apply_config(mismatch_json).is_err());
}
#[test]
fn test_lazy_translation_frame() {
use nalgebra::UnitQuaternion;
let root = Frame::new_origin("root");
let child = root
.add_child(
"child",
Vector3::new(0.0, 0.0, 0.0),
UnitQuaternion::identity(),
)
.unwrap();
let result = &child + z(5.0);
assert_relative_eq!(
result.transformation().unwrap().translation.vector,
Vector3::new(0.0, 0.0, 5.0),
epsilon = 1e-10
);
assert_relative_eq!(
child.transformation().unwrap().translation.vector,
Vector3::new(0.0, 0.0, 0.0),
epsilon = 1e-10
);
let result = &result - y(3.0);
assert_relative_eq!(
result.transformation().unwrap().translation.vector,
Vector3::new(0.0, -3.0, 5.0),
epsilon = 1e-10
);
let (roll, pitch, yaw) = result.transformation().unwrap().rotation.euler_angles();
assert_relative_eq!(
Vector3::new(roll, pitch, yaw),
Vector3::new(0.0, 0.0, 0.0),
epsilon = 1e-10
);
}
#[test]
fn test_lazy_rotation_frame() {
use nalgebra::UnitQuaternion;
let root = Frame::new_origin("root");
let child = root
.add_child(
"child",
Vector3::new(0.0, 0.0, 0.0),
UnitQuaternion::identity(),
)
.unwrap();
let result = &child * rz(std::f64::consts::FRAC_PI_4);
let (roll, pitch, yaw) = result.transformation().unwrap().rotation.euler_angles();
assert_relative_eq!(
Vector3::new(roll, pitch, yaw),
Vector3::new(0.0, 0.0, std::f64::consts::FRAC_PI_4),
epsilon = 1e-10
);
assert_relative_eq!(
result.transformation().unwrap().translation.vector,
Vector3::new(0.0, 0.0, 0.0),
epsilon = 1e-10
);
let (roll, pitch, yaw) = child.transformation().unwrap().rotation.euler_angles();
assert_relative_eq!(
Vector3::new(roll, pitch, yaw),
Vector3::new(0.0, 0.0, 0.0),
epsilon = 1e-10
);
}
#[test]
fn test_lazy_translation_pose() {
use nalgebra::UnitQuaternion;
let root = Frame::new_origin("root");
let pose = root.add_pose(Vector3::new(0.0, 0.0, 0.0), UnitQuaternion::identity());
let result = &pose + z(5.0);
assert_relative_eq!(
result.transformation().translation.vector,
Vector3::new(0.0, 0.0, 5.0),
epsilon = 1e-10
);
assert_relative_eq!(
pose.transformation().translation.vector,
Vector3::new(0.0, 0.0, 0.0),
epsilon = 1e-10
);
let result = &result - y(3.0);
assert_relative_eq!(
result.transformation().translation.vector,
Vector3::new(0.0, -3.0, 5.0),
epsilon = 1e-10
);
let (roll, pitch, yaw) = result.transformation().rotation.euler_angles();
assert_relative_eq!(
Vector3::new(roll, pitch, yaw),
Vector3::new(0.0, 0.0, 0.0),
epsilon = 1e-10
);
}
#[test]
fn test_lazy_rotation_pose() {
use nalgebra::UnitQuaternion;
let root = Frame::new_origin("root");
let pose = root.add_pose(Vector3::new(0.0, 0.0, 0.0), UnitQuaternion::identity());
let result = &pose * rz(std::f64::consts::FRAC_PI_4);
let (roll, pitch, yaw) = result.transformation().rotation.euler_angles();
assert_relative_eq!(
Vector3::new(roll, pitch, yaw),
Vector3::new(0.0, 0.0, std::f64::consts::FRAC_PI_4),
epsilon = 1e-10
);
assert_relative_eq!(
result.transformation().translation.vector,
Vector3::new(0.0, 0.0, 0.0),
epsilon = 1e-10
);
let (roll, pitch, yaw) = pose.transformation().rotation.euler_angles();
assert_relative_eq!(
Vector3::new(roll, pitch, yaw),
Vector3::new(0.0, 0.0, 0.0),
epsilon = 1e-10
);
}
}