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
//! Reeds-Shepp path planning
//!
//! This module provides algorithms for computing Reeds-Shepp paths, which are the shortest
//! paths between two poses (position + orientation) for a vehicle with a minimum turning
//! radius constraint that can move both forward and backward. Reeds-Shepp paths extend
//! Dubins paths by allowing reversing motion.
//!
//! Reeds-Shepp paths can have different combinations of forward/backward motion and
//! turning directions. The fundamental segments are:
//! - Forward/Backward straight lines
//! - Forward/Backward left/right circular arcs
//!
//! # Examples
//!
//! ```
//! use scirs2_spatial::pathplanning::reedshepp::{ReedsSheppPlanner, Pose2D};
//!
//! let start = Pose2D::new(0.0, 0.0, 0.0); // x, y, theta
//! let goal = Pose2D::new(1.0, 1.0, std::f64::consts::PI / 2.0);
//! let turning_radius = 1.0;
//!
//! let planner = ReedsSheppPlanner::new(turning_radius);
//! if let Ok(path) = planner.plan(&start, &goal) {
//! println!("Path length: {}", path.length());
//! }
//! ```
use crate::error::{SpatialError, SpatialResult};
use std::f64::consts::PI;
/// Re-export Pose2D from dubins module for convenience
pub use super::dubins::Pose2D;
/// Motion direction for Reeds-Shepp path segments
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Motion {
/// Forward motion
Forward,
/// Backward motion
Backward,
}
/// Turn direction for Reeds-Shepp path segments
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Turn {
/// Left turn
Left,
/// Right turn
Right,
/// Straight line
Straight,
}
/// A segment of a Reeds-Shepp path
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ReedsSheppSegment {
/// Motion direction (forward or backward)
pub motion: Motion,
/// Turn direction
pub turn: Turn,
/// Length of the segment (arc length for turns, distance for straight)
pub length: f64,
}
impl ReedsSheppSegment {
/// Create a new Reeds-Shepp segment
pub fn new(motion: Motion, turn: Turn, length: f64) -> Self {
Self {
motion,
turn,
length,
}
}
/// Get the signed length (negative for backward motion)
pub fn signed_length(&self) -> f64 {
match self.motion {
Motion::Forward => self.length,
Motion::Backward => -self.length,
}
}
}
/// Types of Reeds-Shepp path families
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReedsSheppPathType {
/// Continuous curvature change paths (e.g., C|C|C)
CCC,
/// Curvature-straight-curvature paths (e.g., C|S|C)
CSC,
/// Curvature-curvature-straight-curvature-curvature paths (e.g., C|C|S|C|C)
CCSCC,
}
/// A complete Reeds-Shepp path
#[derive(Debug, Clone)]
pub struct ReedsSheppPath {
/// Start pose
start: Pose2D,
/// Goal pose
goal: Pose2D,
/// Turning radius
turning_radius: f64,
/// Path type
path_type: ReedsSheppPathType,
/// Path segments (variable length)
segments: Vec<ReedsSheppSegment>,
/// Total path length
length: f64,
}
impl ReedsSheppPath {
/// Create a new Reeds-Shepp path
fn new(
start: Pose2D,
goal: Pose2D,
turning_radius: f64,
path_type: ReedsSheppPathType,
segments: Vec<ReedsSheppSegment>,
) -> Self {
let length = segments.iter().map(|s| s.length).sum();
Self {
start,
goal,
turning_radius,
path_type,
segments,
length,
}
}
/// Get the total length of the path
pub fn length(&self) -> f64 {
self.length
}
/// Get the path type
pub fn path_type(&self) -> ReedsSheppPathType {
self.path_type
}
/// Get the path segments
pub fn segments(&self) -> &[ReedsSheppSegment] {
&self.segments
}
/// Get the start pose
pub fn start(&self) -> &Pose2D {
&self.start
}
/// Get the goal pose
pub fn goal(&self) -> &Pose2D {
&self.goal
}
/// Get the turning radius
pub fn turning_radius(&self) -> f64 {
self.turning_radius
}
/// Sample a point along the path at parameter t
///
/// # Arguments
///
/// * `t` - Parameter in [0, 1] where 0 is start and 1 is goal
///
/// # Returns
///
/// * Pose at parameter t, or error if t is out of bounds
pub fn sample(&self, t: f64) -> SpatialResult<Pose2D> {
if !(0.0..=1.0).contains(&t) {
return Err(SpatialError::ValueError(
"Parameter t must be in [0, 1]".to_string(),
));
}
let target_distance = t * self.length;
let mut current_distance = 0.0;
let mut current_pose = self.start;
for segment in &self.segments {
if current_distance + segment.length >= target_distance {
// Target is within this segment
let segment_distance = target_distance - current_distance;
let segment_t = if segment.length > 0.0 {
segment_distance / segment.length
} else {
0.0
};
return self.sample_segment(¤t_pose, segment, segment_t);
}
// Move to the end of this segment
current_pose = self.sample_segment(¤t_pose, segment, 1.0)?;
current_distance += segment.length;
}
Ok(self.goal)
}
/// Sample a point within a specific segment
fn sample_segment(
&self,
start_pose: &Pose2D,
segment: &ReedsSheppSegment,
t: f64,
) -> SpatialResult<Pose2D> {
let distance = t * segment.signed_length();
match segment.turn {
Turn::Straight => {
let new_x = start_pose.x + distance * start_pose.theta.cos();
let new_y = start_pose.y + distance * start_pose.theta.sin();
Ok(Pose2D::new(new_x, new_y, start_pose.theta))
}
Turn::Left => {
let sign = match segment.motion {
Motion::Forward => 1.0,
Motion::Backward => -1.0,
};
let angle = distance / self.turning_radius;
let center_x = start_pose.x - sign * self.turning_radius * start_pose.theta.sin();
let center_y = start_pose.y + sign * self.turning_radius * start_pose.theta.cos();
let new_theta = start_pose.theta + angle;
let new_x = center_x + sign * self.turning_radius * new_theta.sin();
let new_y = center_y - sign * self.turning_radius * new_theta.cos();
Ok(Pose2D::new(new_x, new_y, new_theta))
}
Turn::Right => {
let sign = match segment.motion {
Motion::Forward => 1.0,
Motion::Backward => -1.0,
};
let angle = distance / self.turning_radius;
let center_x = start_pose.x + sign * self.turning_radius * start_pose.theta.sin();
let center_y = start_pose.y - sign * self.turning_radius * start_pose.theta.cos();
let new_theta = start_pose.theta - angle;
let new_x = center_x - sign * self.turning_radius * new_theta.sin();
let new_y = center_y + sign * self.turning_radius * new_theta.cos();
Ok(Pose2D::new(new_x, new_y, new_theta))
}
}
}
}
/// Reeds-Shepp path planner
pub struct ReedsSheppPlanner {
/// Minimum turning radius
turning_radius: f64,
}
impl ReedsSheppPlanner {
/// Create a new Reeds-Shepp path planner
///
/// # Arguments
///
/// * `turning_radius` - Minimum turning radius (must be positive)
///
/// # Returns
///
/// * A new ReedsSheppPlanner instance
pub fn new(_turningradius: f64) -> Self {
Self {
turning_radius: _turningradius,
}
}
/// Plan a Reeds-Shepp path between two poses
///
/// # Arguments
///
/// * `start` - Start pose
/// * `goal` - Goal pose
///
/// # Returns
///
/// * The shortest Reeds-Shepp path, or an error if planning fails
pub fn plan(&self, start: &Pose2D, goal: &Pose2D) -> SpatialResult<ReedsSheppPath> {
if self.turning_radius <= 0.0 {
return Err(SpatialError::ValueError(
"Turning radius must be positive".to_string(),
));
}
// Normalize _start and goal poses
let _start = start.normalize_angle();
let goal = goal.normalize_angle();
// Transform to canonical form (_start at origin with zero orientation)
let dx = goal.x - start.x;
let dy = goal.y - start.y;
let dtheta = goal.theta - start.theta;
// Rotate to align _start orientation with x-axis
let cos_theta = start.theta.cos();
let sin_theta = start.theta.sin();
let x = dx * cos_theta + dy * sin_theta;
let y = -dx * sin_theta + dy * cos_theta;
let phi = Self::normalize_angle(dtheta);
// Scale by turning radius
let x_scaled = x / self.turning_radius;
let y_scaled = y / self.turning_radius;
// Find the shortest path among all possible types
let mut best_path = None;
let mut best_length = f64::INFINITY;
// Try all 48 Reeds-Shepp path types
let path_functions = [
Self::csc_path,
Self::ccc_path,
Self::cccc_path,
Self::ccsc_path,
Self::ccscc_path,
];
for path_fn in &path_functions {
if let Ok(segments) = path_fn(self, x_scaled, y_scaled, phi) {
let path_length: f64 = segments.iter().map(|s| s.length).sum();
if path_length < best_length {
best_length = path_length;
let path_type = ReedsSheppPlanner::determine_path_type(&segments);
best_path = Some(ReedsSheppPath::new(
*start,
goal,
self.turning_radius,
path_type,
segments,
));
}
}
}
best_path.ok_or_else(|| {
SpatialError::ComputationError(
"Failed to compute any valid Reeds-Shepp path".to_string(),
)
})
}
/// Determine the path type based on segments
fn determine_path_type(segments: &[ReedsSheppSegment]) -> ReedsSheppPathType {
match segments.len() {
3 => {
if segments.iter().all(|s| s.turn != Turn::Straight) {
ReedsSheppPathType::CCC
} else {
ReedsSheppPathType::CSC
}
}
_ => ReedsSheppPathType::CSC, // Default fallback
}
}
/// Compute CSC (Curvature-Straight-Curvature) paths
fn csc_path(&self, x: f64, y: f64, phi: f64) -> SpatialResult<Vec<ReedsSheppSegment>> {
// This is a simplified implementation of CSC paths
// A complete implementation would consider all variants (LSL, LSR, RSL, RSR, etc.)
let d = (x * x + y * y).sqrt();
if d < 2.0 {
return Err(SpatialError::ComputationError(
"Distance too small for CSC path".to_string(),
));
}
// Simplified LSL path calculation
let theta = y.atan2(x);
let alpha = Self::normalize_angle(-theta);
let beta = Self::normalize_angle(phi - theta);
// Check if a valid LSL path exists
let tmp0 = d + alpha.sin() - beta.sin();
let p_squared =
2.0 + d * d - 2.0 * (alpha - beta).cos() + 2.0 * d * (alpha.sin() - beta.sin());
if p_squared >= 0.0 {
let tmp1 = (beta - alpha).atan2(tmp0);
let t = Self::normalize_angle(-alpha + tmp1);
let p = p_squared.sqrt();
let q = Self::normalize_angle(beta - tmp1);
if t >= 0.0 && p >= 0.0 && q >= 0.0 {
return Ok(vec![
ReedsSheppSegment::new(
Motion::Forward,
Turn::Left,
t.abs() * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Forward,
Turn::Straight,
p.abs() * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Forward,
Turn::Left,
q.abs() * self.turning_radius,
),
]);
}
}
Err(SpatialError::ComputationError(
"No valid CSC path found".to_string(),
))
}
/// Compute CCC (Curvature-Curvature-Curvature) paths
fn ccc_path(&self, x: f64, y: f64, phi: f64) -> SpatialResult<Vec<ReedsSheppSegment>> {
// Simplified CCC path (LRL type)
let xi = x - phi.sin();
let eta = y - 1.0 + phi.cos();
let rho = 0.25 * (2.0 + (xi * xi + eta * eta).sqrt());
if rho <= 1.0 {
let u = (4.0 * rho * rho - 1.0).sqrt().acos();
if u >= 0.0 {
let t = Self::normalize_angle(u + xi.atan2(eta));
let v = Self::normalize_angle(t - u - phi);
if t >= 0.0 && v <= 0.0 {
return Ok(vec![
ReedsSheppSegment::new(
Motion::Forward,
Turn::Left,
t.abs() * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Backward,
Turn::Right,
u.abs() * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Forward,
Turn::Left,
v.abs() * self.turning_radius,
),
]);
}
}
}
Err(SpatialError::ComputationError(
"No valid CCC path found".to_string(),
))
}
/// Compute LRLR path
fn lrlr_path(&self, x: f64, y: f64, phi: f64) -> SpatialResult<Vec<ReedsSheppSegment>> {
let xi = x + phi.sin();
let eta = y - 1.0 + phi.cos();
let rho = 0.25 * (xi * xi + eta * eta);
if rho <= 1.0 {
let u = (4.0 - rho * rho).sqrt().acos();
if u.is_finite() && u >= 0.0 {
let v = eta.atan2(xi);
let t = Self::normalize_angle(v + u + PI);
let s = Self::normalize_angle(phi - t + 2.0 * u);
if t >= 0.0 && s >= 0.0 {
return Ok(vec![
ReedsSheppSegment::new(
Motion::Forward,
Turn::Left,
t * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Backward,
Turn::Right,
u * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Forward,
Turn::Left,
u * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Backward,
Turn::Right,
s * self.turning_radius,
),
]);
}
}
}
Err(SpatialError::ComputationError(
"No valid LRLR path found".to_string(),
))
}
/// Compute RLRL path
fn rlrl_path(&self, x: f64, y: f64, phi: f64) -> SpatialResult<Vec<ReedsSheppSegment>> {
let xi = x - phi.sin();
let eta = y - 1.0 - phi.cos();
let rho = 0.25 * (xi * xi + eta * eta);
if rho <= 1.0 {
let u = (4.0 - rho * rho).sqrt().acos();
if u.is_finite() && u >= 0.0 {
let v = eta.atan2(xi);
let t = Self::normalize_angle(v - u - PI);
let s = Self::normalize_angle(t - phi + 2.0 * u);
if t <= 0.0 && s <= 0.0 {
return Ok(vec![
ReedsSheppSegment::new(
Motion::Forward,
Turn::Right,
t.abs() * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Backward,
Turn::Left,
u * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Forward,
Turn::Right,
u * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Backward,
Turn::Left,
s.abs() * self.turning_radius,
),
]);
}
}
}
Err(SpatialError::ComputationError(
"No valid RLRL path found".to_string(),
))
}
/// Compute CCCC paths (Curvature-Curvature-Curvature-Curvature)
fn cccc_path(&self, x: f64, y: f64, phi: f64) -> SpatialResult<Vec<ReedsSheppSegment>> {
// CCCC paths are complex 4-segment paths
// We implement the LRLR and RLRL path types
// Try LRLR path
if let Ok(lrlr_path) = self.lrlr_path(x, y, phi) {
return Ok(lrlr_path);
}
// Try RLRL path
if let Ok(rlrl_path) = self.rlrl_path(x, y, phi) {
return Ok(rlrl_path);
}
Err(SpatialError::ComputationError(
"No valid CCCC path found".to_string(),
))
}
/// Compute LRSL path
fn lrsl_path(&self, x: f64, y: f64, phi: f64) -> SpatialResult<Vec<ReedsSheppSegment>> {
let xi = x - phi.sin();
let eta = y - 1.0 + phi.cos();
let rho_squared = xi * xi + eta * eta;
if rho_squared >= 4.0 {
let rho = rho_squared.sqrt();
let u = (rho - 2.0).acos();
if u.is_finite() {
let v = eta.atan2(xi);
let t = Self::normalize_angle(v - u);
let s = Self::normalize_angle(t - phi + u);
if t >= 0.0 && s >= 0.0 {
let p = rho - 2.0;
return Ok(vec![
ReedsSheppSegment::new(
Motion::Forward,
Turn::Left,
t * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Backward,
Turn::Right,
u * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Forward,
Turn::Straight,
p * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Forward,
Turn::Left,
s * self.turning_radius,
),
]);
}
}
}
Err(SpatialError::ComputationError(
"No valid LRSL path found".to_string(),
))
}
/// Compute LRSR path
fn lrsr_path(&self, x: f64, y: f64, phi: f64) -> SpatialResult<Vec<ReedsSheppSegment>> {
let xi = x + phi.sin();
let eta = y - 1.0 - phi.cos();
let rho_squared = xi * xi + eta * eta;
if rho_squared >= 4.0 {
let rho = rho_squared.sqrt();
let u = (rho - 2.0).acos();
if u.is_finite() {
let v = eta.atan2(xi);
let t = Self::normalize_angle(v + u);
let s = Self::normalize_angle(phi - t + u);
if t >= 0.0 && s >= 0.0 {
let p = rho - 2.0;
return Ok(vec![
ReedsSheppSegment::new(
Motion::Forward,
Turn::Left,
t * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Backward,
Turn::Right,
u * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Forward,
Turn::Straight,
p * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Backward,
Turn::Right,
s * self.turning_radius,
),
]);
}
}
}
Err(SpatialError::ComputationError(
"No valid LRSR path found".to_string(),
))
}
/// Compute RLSL path
fn rlsl_path(&self, x: f64, y: f64, phi: f64) -> SpatialResult<Vec<ReedsSheppSegment>> {
let xi = x + phi.sin();
let eta = y - 1.0 - phi.cos();
let rho_squared = xi * xi + eta * eta;
if rho_squared >= 4.0 {
let rho = rho_squared.sqrt();
let u = (rho - 2.0).acos();
if u.is_finite() {
let v = eta.atan2(xi);
let t = Self::normalize_angle(v - u);
let s = Self::normalize_angle(phi - t + u);
if t <= 0.0 && s <= 0.0 {
let p = rho - 2.0;
return Ok(vec![
ReedsSheppSegment::new(
Motion::Forward,
Turn::Right,
t.abs() * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Backward,
Turn::Left,
u * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Forward,
Turn::Straight,
p * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Forward,
Turn::Left,
s.abs() * self.turning_radius,
),
]);
}
}
}
Err(SpatialError::ComputationError(
"No valid RLSL path found".to_string(),
))
}
/// Compute RLSR path
fn rlsr_path(&self, x: f64, y: f64, phi: f64) -> SpatialResult<Vec<ReedsSheppSegment>> {
let xi = x - phi.sin();
let eta = y - 1.0 + phi.cos();
let rho_squared = xi * xi + eta * eta;
if rho_squared >= 4.0 {
let rho = rho_squared.sqrt();
let u = (rho - 2.0).acos();
if u.is_finite() {
let v = eta.atan2(xi);
let t = Self::normalize_angle(v + u);
let s = Self::normalize_angle(t - phi + u);
if t <= 0.0 && s <= 0.0 {
let p = rho - 2.0;
return Ok(vec![
ReedsSheppSegment::new(
Motion::Forward,
Turn::Right,
t.abs() * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Backward,
Turn::Left,
u * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Forward,
Turn::Straight,
p * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Backward,
Turn::Right,
s.abs() * self.turning_radius,
),
]);
}
}
}
Err(SpatialError::ComputationError(
"No valid RLSR path found".to_string(),
))
}
/// Compute CCSC paths (Curvature-Curvature-Straight-Curvature)
fn ccsc_path(&self, x: f64, y: f64, phi: f64) -> SpatialResult<Vec<ReedsSheppSegment>> {
// CCSC paths have two curves, then a straight segment, then another curve
// We implement LRSL, LRSR, RLSL, RLSR path types
// Try LRSL path
if let Ok(lrsl_path) = self.lrsl_path(x, y, phi) {
return Ok(lrsl_path);
}
// Try LRSR path
if let Ok(lrsr_path) = self.lrsr_path(x, y, phi) {
return Ok(lrsr_path);
}
// Try RLSL path
if let Ok(rlsl_path) = self.rlsl_path(x, y, phi) {
return Ok(rlsl_path);
}
// Try RLSR path
if let Ok(rlsr_path) = self.rlsr_path(x, y, phi) {
return Ok(rlsr_path);
}
Err(SpatialError::ComputationError(
"No valid CCSC path found".to_string(),
))
}
/// Compute LRLSL path
fn lrlsl_path(&self, x: f64, y: f64, phi: f64) -> SpatialResult<Vec<ReedsSheppSegment>> {
let xi = x + phi.sin();
let eta = y - 1.0 + phi.cos();
let rho = 0.25 * (xi * xi + eta * eta);
if (1.0..=4.0).contains(&rho) {
let u1 = (rho - 1.0).sqrt().acos();
let u2 = (4.0 - rho).sqrt().acos();
if u1.is_finite() && u2.is_finite() {
let v = eta.atan2(xi);
let t = Self::normalize_angle(v + u1 + u2 + PI);
let s = Self::normalize_angle(phi - t + u1 + u2);
if t >= 0.0 && s >= 0.0 {
let p = (rho - 1.0).sqrt();
return Ok(vec![
ReedsSheppSegment::new(
Motion::Forward,
Turn::Left,
t * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Backward,
Turn::Right,
u1 * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Forward,
Turn::Left,
u2 * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Forward,
Turn::Straight,
p * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Forward,
Turn::Left,
s * self.turning_radius,
),
]);
}
}
}
Err(SpatialError::ComputationError(
"No valid LRLSL path found".to_string(),
))
}
/// Compute RLRLR path
fn rlrlr_path(&self, x: f64, y: f64, phi: f64) -> SpatialResult<Vec<ReedsSheppSegment>> {
let xi = x - phi.sin();
let eta = y - 1.0 - phi.cos();
let rho = 0.25 * (xi * xi + eta * eta);
if (1.0..=4.0).contains(&rho) {
let u1 = (rho - 1.0).sqrt().acos();
let u2 = (4.0 - rho).sqrt().acos();
if u1.is_finite() && u2.is_finite() {
let v = eta.atan2(xi);
let t = Self::normalize_angle(v - u1 - u2 - PI);
let s = Self::normalize_angle(t - phi + u1 + u2);
if t <= 0.0 && s <= 0.0 {
let _p = (rho - 1.0).sqrt(); // Reserved for potential future use
return Ok(vec![
ReedsSheppSegment::new(
Motion::Forward,
Turn::Right,
t.abs() * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Backward,
Turn::Left,
u1 * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Forward,
Turn::Right,
u2 * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Forward,
Turn::Left,
u1 * self.turning_radius,
),
ReedsSheppSegment::new(
Motion::Backward,
Turn::Right,
s.abs() * self.turning_radius,
),
]);
}
}
}
Err(SpatialError::ComputationError(
"No valid RLRLR path found".to_string(),
))
}
/// Compute CCSCC paths (Curvature-Curvature-Straight-Curvature-Curvature)
fn ccscc_path(&self, x: f64, y: f64, phi: f64) -> SpatialResult<Vec<ReedsSheppSegment>> {
// CCSCC paths are the most complex with 5 segments
// We implement LRLSL and RLRLR path types
// Try LRLSL path
if let Ok(lrlsl_path) = self.lrlsl_path(x, y, phi) {
return Ok(lrlsl_path);
}
// Try RLRLR path
if let Ok(rlrlr_path) = self.rlrlr_path(x, y, phi) {
return Ok(rlrlr_path);
}
Err(SpatialError::ComputationError(
"No valid CCSCC path found".to_string(),
))
}
/// Normalize angle to [-π, π]
fn normalize_angle(angle: f64) -> f64 {
let mut normalized = angle % (2.0 * PI);
if normalized > PI {
normalized -= 2.0 * PI;
} else if normalized < -PI {
normalized += 2.0 * PI;
}
normalized
}
}
#[cfg(test)]
mod tests {
use super::*;
use approx::assert_relative_eq;
#[test]
fn test_reedshepp_segment_basic() {
let segment = ReedsSheppSegment::new(Motion::Forward, Turn::Left, 2.0);
assert_eq!(segment.motion, Motion::Forward);
assert_eq!(segment.turn, Turn::Left);
assert_eq!(segment.length, 2.0);
assert_eq!(segment.signed_length(), 2.0);
let backward_segment = ReedsSheppSegment::new(Motion::Backward, Turn::Right, 3.0);
assert_eq!(backward_segment.signed_length(), -3.0);
}
#[test]
fn test_reedshepp_planner_creation() {
let planner = ReedsSheppPlanner::new(1.0);
assert_eq!(planner.turning_radius, 1.0);
}
#[test]
fn test_reedshepp_simple_path() {
let start = Pose2D::new(0.0, 0.0, 0.0);
let goal = Pose2D::new(5.0, 0.0, 0.0);
let planner = ReedsSheppPlanner::new(1.0);
let path = planner.plan(&start, &goal);
if let Ok(path) = path {
assert!(path.length() > 0.0);
assert!(!path.segments().is_empty());
}
// Note: This might fail for some configurations due to simplified implementation
}
#[test]
fn test_reedshepp_path_sampling() {
let start = Pose2D::new(0.0, 0.0, 0.0);
let goal = Pose2D::new(3.0, 0.0, 0.0);
let planner = ReedsSheppPlanner::new(1.0);
if let Ok(path) = planner.plan(&start, &goal) {
// Sample at start (t=0)
let start_sample = path.sample(0.0).expect("Operation failed");
assert_relative_eq!(start_sample.x, start.x, epsilon = 1e-2);
assert_relative_eq!(start_sample.y, start.y, epsilon = 1e-2);
// Test invalid parameters
assert!(path.sample(-0.1).is_err());
assert!(path.sample(1.1).is_err());
}
}
#[test]
fn test_reedshepp_backward_capability() {
// Test a configuration where backward motion might be beneficial
let start = Pose2D::new(0.0, 0.0, 0.0);
let goal = Pose2D::new(-1.0, 0.0, PI);
let planner = ReedsSheppPlanner::new(2.0);
let path = planner.plan(&start, &goal);
if let Ok(path) = path {
// Check if any segment uses backward motion
let _has_backward = path.segments().iter().any(|s| s.motion == Motion::Backward);
// Note: This depends on the implementation finding a backward path
// For this specific configuration, backward motion might be optimal
assert!(path.length() > 0.0);
}
}
#[test]
fn test_normalize_angle() {
assert_relative_eq!(
ReedsSheppPlanner::normalize_angle(0.0),
0.0,
epsilon = 1e-10
);
assert_relative_eq!(ReedsSheppPlanner::normalize_angle(PI), PI, epsilon = 1e-10);
assert_relative_eq!(
ReedsSheppPlanner::normalize_angle(-PI),
-PI,
epsilon = 1e-10
);
// Both π and -π are valid normalized forms of 3π
let normalized_3pi = ReedsSheppPlanner::normalize_angle(3.0 * PI);
assert!(
(normalized_3pi - PI).abs() < 1e-10 || (normalized_3pi - (-PI)).abs() < 1e-10,
"Expected ±π, got {normalized_3pi}"
);
}
#[test]
fn test_reedshepp_invalid_turning_radius() {
let start = Pose2D::new(0.0, 0.0, 0.0);
let goal = Pose2D::new(1.0, 0.0, 0.0);
let planner = ReedsSheppPlanner::new(-1.0);
let result = planner.plan(&start, &goal);
assert!(result.is_err());
}
#[test]
fn test_reedshepp_cccc_paths() {
// Test a configuration that might benefit from CCCC paths
let start = Pose2D::new(0.0, 0.0, 0.0);
let goal = Pose2D::new(0.0, 0.0, 2.0 * PI); // Full rotation
let planner = ReedsSheppPlanner::new(0.5);
let path = planner.plan(&start, &goal);
if let Ok(path) = path {
// For a full rotation at the same position, the path might be very short or zero
// depending on the angle normalization
assert!(path.length() >= 0.0);
assert!(!path.segments().is_empty());
// Should have at least 1 segment for a valid path
assert!(!path.segments().is_empty());
}
}
#[test]
fn test_reedshepp_ccsc_paths() {
// Test a configuration that might benefit from CCSC paths (with straight section)
let start = Pose2D::new(0.0, 0.0, 0.0);
let goal = Pose2D::new(5.0, 2.0, PI / 2.0); // Requires complex maneuvering
let planner = ReedsSheppPlanner::new(1.0);
let path = planner.plan(&start, &goal);
if let Ok(path) = path {
assert!(path.length() > 0.0);
assert!(!path.segments().is_empty());
// Verify that we have a reasonable path length
assert!(path.length() < 20.0 * planner.turning_radius); // Reasonable upper bound
}
}
#[test]
fn test_reedshepp_ccscc_paths() {
// Test a configuration that might benefit from CCSCC paths (most complex)
let start = Pose2D::new(0.0, 0.0, 0.0);
let goal = Pose2D::new(-2.0, 1.0, -PI / 4.0); // Complex reverse maneuver
let planner = ReedsSheppPlanner::new(0.8);
let path = planner.plan(&start, &goal);
if let Ok(path) = path {
assert!(path.length() > 0.0);
assert!(!path.segments().is_empty());
// For CCSCC paths, we might have up to 5 segments
assert!(path.segments().len() >= 3);
assert!(path.segments().len() <= 5);
}
}
#[test]
fn test_reedshepp_path_types() {
let start = Pose2D::new(0.0, 0.0, 0.0);
let goal = Pose2D::new(2.0, 1.0, PI / 3.0);
let planner = ReedsSheppPlanner::new(1.0);
let path = planner.plan(&start, &goal);
if let Ok(path) = path {
// Test that we can identify the path type
let path_type = path.path_type();
assert!(matches!(
path_type,
ReedsSheppPathType::CCC | ReedsSheppPathType::CSC | ReedsSheppPathType::CCSCC
));
// Verify all segments have valid parameters
for segment in path.segments() {
assert!(segment.length >= 0.0);
assert!(segment.length.is_finite());
// Motion should be either Forward or Backward
assert!(matches!(segment.motion, Motion::Forward | Motion::Backward));
// Turn should be Left, Right, or Straight
assert!(matches!(
segment.turn,
Turn::Left | Turn::Right | Turn::Straight
));
}
}
}
#[test]
fn test_reedshepp_segments_validation() {
let start = Pose2D::new(0.0, 0.0, 0.0);
let goal = Pose2D::new(1.0, 1.0, PI / 2.0);
let planner = ReedsSheppPlanner::new(1.0);
let path = planner.plan(&start, &goal);
if let Ok(path) = path {
// Test segment properties
for segment in path.segments() {
// All segments should have non-negative length (allow zero for degenerate cases)
assert!(
segment.length >= 0.0,
"Segment length should be non-negative, got: {}",
segment.length
);
assert!(segment.length.is_finite());
// Test signed_length method
let signed_length = segment.signed_length();
match segment.motion {
Motion::Forward => {
assert_relative_eq!(signed_length, segment.length, epsilon = 1e-10)
}
Motion::Backward => {
assert_relative_eq!(signed_length, -segment.length, epsilon = 1e-10)
}
}
}
// The total path should have positive length since start != goal
assert!(path.length() > 0.0);
}
}
#[test]
fn test_reedshepp_different_turning_radii() {
let start = Pose2D::new(0.0, 0.0, 0.0);
let goal = Pose2D::new(2.0, 2.0, PI);
let radii = [0.5, 1.0, 2.0, 5.0];
let mut path_lengths = Vec::new();
for &radius in &radii {
let planner = ReedsSheppPlanner::new(radius);
if let Ok(path) = planner.plan(&start, &goal) {
path_lengths.push(path.length());
}
}
// Generally, smaller turning radius should allow shorter paths
// (though this isn't always guaranteed due to different path types)
assert!(
!path_lengths.is_empty(),
"Should find valid paths for some turning radii"
);
for &length in &path_lengths {
assert!(length > 0.0);
assert!(length.is_finite());
}
}
#[test]
fn test_reedshepp_path_continuity() {
// Test that the path actually connects start to goal
let start = Pose2D::new(1.0, 2.0, PI / 4.0);
let goal = Pose2D::new(3.0, 1.0, -PI / 6.0);
let planner = ReedsSheppPlanner::new(1.5);
let path = planner.plan(&start, &goal);
if let Ok(path) = path {
// Sample the path at the beginning and end
let start_sample = path.sample(0.0).expect("Operation failed");
let end_sample = path.sample(1.0).expect("Operation failed");
// Should be close to the actual start and goal
assert_relative_eq!(start_sample.x, start.x, epsilon = 1e-2);
assert_relative_eq!(start_sample.y, start.y, epsilon = 1e-2);
assert_relative_eq!(end_sample.x, goal.x, epsilon = 1e-2);
assert_relative_eq!(end_sample.y, goal.y, epsilon = 1e-2);
}
}
#[test]
fn test_reedshepp_extreme_cases() {
let planner = ReedsSheppPlanner::new(1.0);
// Test very close points
let close_start = Pose2D::new(0.0, 0.0, 0.0);
let close_goal = Pose2D::new(0.01, 0.01, 0.1);
if let Ok(path) = planner.plan(&close_start, &close_goal) {
assert!(path.length() > 0.0);
assert!(path.length() < 1.0); // Should be short for close points
}
// Test points that require significant maneuvering
let complex_start = Pose2D::new(0.0, 0.0, 0.0);
let complex_goal = Pose2D::new(-1.0, -1.0, PI);
if let Ok(path) = planner.plan(&complex_start, &complex_goal) {
assert!(path.length() > 2.0); // Should be longer for complex maneuvers
}
}
}