-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
1701 lines (1510 loc) · 64 KB
/
main.cpp
File metadata and controls
1701 lines (1510 loc) · 64 KB
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
// TARE Planner - dimos NativeModule port
//
// Technology-Aware Robot Exploration planner: receives registered point clouds
// and odometry, maintains a rolling occupancy grid, detects exploration
// frontiers, plans exploration paths that maximise information gain via sensor
// coverage planning, and outputs waypoints for the local planner.
//
// Original: src/exploration_planner/tare_planner/
// Authors: Chao Cao et al. (CMU), port by dimos team
//
// Key algorithm:
// 1. Receives registered point clouds and odometry
// 2. Maintains a rolling occupancy grid
// 3. Detects exploration frontiers (boundaries between explored/unexplored)
// 4. Plans exploration paths that maximise information gain
// 5. Uses sensor coverage planning to optimise exploration
// 6. Outputs waypoints for the local planner to follow
#include <atomic>
#include <algorithm>
#include <cassert>
#include <chrono>
#include <cmath>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <deque>
#include <functional>
#include <limits>
#include <map>
#include <mutex>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <string>
#include <thread>
#include <vector>
#include <lcm/lcm-cpp.hpp>
#include "dimos_native_module.hpp"
#include "point_cloud_utils.hpp"
#include "sensor_msgs/PointCloud2.hpp"
#include "nav_msgs/Odometry.hpp"
#include "geometry_msgs/PointStamped.hpp"
#ifdef USE_PCL
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/search/kdtree.h>
#include <pcl/segmentation/extract_clusters.h>
#include <pcl/PointIndices.h>
#include <Eigen/Core>
#include <Eigen/Dense>
#endif
// ============================================================================
// Signal handling
// ============================================================================
static std::atomic<bool> g_shutdown{false};
static void signal_handler(int) { g_shutdown.store(true); }
// ============================================================================
// Wall-clock helper
// ============================================================================
static double now_seconds() {
using namespace std::chrono;
return duration_cast<duration<double>>(
steady_clock::now().time_since_epoch()).count();
}
// ============================================================================
// Eigen/math helpers (minimal, no ROS geometry_msgs dependency)
// ============================================================================
using Vec3d = Eigen::Vector3d;
using Vec3i = Eigen::Vector3i;
struct Point3 {
double x = 0, y = 0, z = 0;
};
static double point_dist(const Point3& a, const Point3& b) {
double dx = a.x - b.x, dy = a.y - b.y, dz = a.z - b.z;
return std::sqrt(dx*dx + dy*dy + dz*dz);
}
static double point_xy_dist(const Point3& a, const Point3& b) {
double dx = a.x - b.x, dy = a.y - b.y;
return std::sqrt(dx*dx + dy*dy);
}
// ============================================================================
// Timer utility (replaces misc_utils_ns::Timer)
// ============================================================================
class Timer {
public:
explicit Timer(const std::string& name = "") : name_(name), duration_ms_(0) {}
void Start() { start_ = std::chrono::steady_clock::now(); }
void Stop(bool print = false) {
auto end = std::chrono::steady_clock::now();
duration_ms_ = std::chrono::duration_cast<std::chrono::milliseconds>(end - start_).count();
if (print) fprintf(stderr, "[Timer] %s: %d ms\n", name_.c_str(), duration_ms_);
}
int GetDurationMs() const { return duration_ms_; }
private:
std::string name_;
std::chrono::steady_clock::time_point start_;
int duration_ms_;
};
// ============================================================================
// Voxel grid downsampler (non-PCL fallback)
// ============================================================================
struct PointXYZI {
float x, y, z, intensity;
};
struct VoxelKey {
int ix, iy, iz;
bool operator==(const VoxelKey& o) const { return ix==o.ix && iy==o.iy && iz==o.iz; }
};
struct VoxelKeyHash {
size_t operator()(const VoxelKey& k) const {
size_t h = std::hash<int>()(k.ix);
h ^= std::hash<int>()(k.iy) + 0x9e3779b9 + (h<<6) + (h>>2);
h ^= std::hash<int>()(k.iz) + 0x9e3779b9 + (h<<6) + (h>>2);
return h;
}
};
static void downsample_cloud(std::vector<PointXYZI>& cloud, float lx, float ly, float lz) {
if (cloud.empty() || lx <= 0 || ly <= 0 || lz <= 0) return;
std::unordered_map<VoxelKey, std::pair<PointXYZI, int>, VoxelKeyHash> voxels;
for (const auto& p : cloud) {
VoxelKey k{(int)std::floor(p.x / lx), (int)std::floor(p.y / ly), (int)std::floor(p.z / lz)};
auto it = voxels.find(k);
if (it == voxels.end()) {
voxels[k] = {p, 1};
} else {
auto& [acc, cnt] = it->second;
acc.x += p.x; acc.y += p.y; acc.z += p.z; acc.intensity += p.intensity;
cnt++;
}
}
cloud.clear();
cloud.reserve(voxels.size());
for (auto& [k, v] : voxels) {
auto& [acc, cnt] = v;
cloud.push_back({acc.x/cnt, acc.y/cnt, acc.z/cnt, acc.intensity/cnt});
}
}
// ============================================================================
// 3-D Grid template (replaces grid_ns::Grid)
// ============================================================================
template<typename T>
class Grid3D {
public:
Grid3D() : sx_(0), sy_(0), sz_(0) {}
Grid3D(int sx, int sy, int sz, const T& init_val, Vec3d origin, Vec3d resolution)
: sx_(sx), sy_(sy), sz_(sz), origin_(origin), res_(resolution),
data_(sx*sy*sz, init_val) {}
void Resize(int sx, int sy, int sz, const T& init_val, Vec3d origin, Vec3d resolution) {
sx_ = sx; sy_ = sy; sz_ = sz;
origin_ = origin; res_ = resolution;
data_.assign(sx*sy*sz, init_val);
}
int CellNumber() const { return sx_*sy_*sz_; }
bool InRange(const Vec3i& sub) const {
return sub.x()>=0 && sub.x()<sx_ && sub.y()>=0 && sub.y()<sy_ && sub.z()>=0 && sub.z()<sz_;
}
bool InRange(int ind) const { return ind >= 0 && ind < (int)data_.size(); }
int Sub2Ind(const Vec3i& s) const { return s.x() + s.y()*sx_ + s.z()*sx_*sy_; }
int Sub2Ind(int x, int y, int z) const { return x + y*sx_ + z*sx_*sy_; }
Vec3i Ind2Sub(int ind) const {
int z = ind / (sx_*sy_);
int rem = ind % (sx_*sy_);
int y = rem / sx_;
int x = rem % sx_;
return Vec3i(x,y,z);
}
Vec3d Ind2Pos(int ind) const {
Vec3i s = Ind2Sub(ind);
return Vec3d(origin_.x() + (s.x()+0.5)*res_.x(),
origin_.y() + (s.y()+0.5)*res_.y(),
origin_.z() + (s.z()+0.5)*res_.z());
}
Vec3i Pos2Sub(const Vec3d& pos) const {
return Vec3i((int)std::floor((pos.x()-origin_.x())/res_.x()),
(int)std::floor((pos.y()-origin_.y())/res_.y()),
(int)std::floor((pos.z()-origin_.z())/res_.z()));
}
Vec3d Sub2Pos(const Vec3i& s) const {
return Vec3d(origin_.x() + (s.x()+0.5)*res_.x(),
origin_.y() + (s.y()+0.5)*res_.y(),
origin_.z() + (s.z()+0.5)*res_.z());
}
T& At(int ind) { return data_[ind]; }
const T& At(int ind) const { return data_[ind]; }
void Set(int ind, const T& v) { data_[ind] = v; }
Vec3i Size() const { return Vec3i(sx_,sy_,sz_); }
Vec3d Origin() const { return origin_; }
Vec3d Resolution() const { return res_; }
void SetOrigin(const Vec3d& o) { origin_ = o; }
private:
int sx_, sy_, sz_;
Vec3d origin_, res_;
std::vector<T> data_;
};
// ============================================================================
// Rolling Grid (index indirection for rolling arrays)
// ============================================================================
class RollingGrid {
public:
RollingGrid() : sx_(0), sy_(0), sz_(0) {}
RollingGrid(const Vec3i& size)
: sx_(size.x()), sy_(size.y()), sz_(size.z()),
offset_(0,0,0)
{
int n = sx_*sy_*sz_;
ind_map_.resize(n);
std::iota(ind_map_.begin(), ind_map_.end(), 0);
}
int GetArrayInd(int grid_ind) const {
Vec3i sub = GridInd2Sub(grid_ind);
Vec3i arr_sub;
for (int i = 0; i < 3; i++) {
int s = (i==0?sx_:(i==1?sy_:sz_));
arr_sub(i) = ((sub(i) + offset_(i)) % s + s) % s;
}
return arr_sub.x() + arr_sub.y()*sx_ + arr_sub.z()*sx_*sy_;
}
int GetArrayInd(const Vec3i& sub) const {
return GetArrayInd(sub.x() + sub.y()*sx_ + sub.z()*sx_*sy_);
}
void Roll(const Vec3i& step, std::vector<int>& rolled_out, std::vector<int>& updated) {
rolled_out.clear();
updated.clear();
// Collect indices that will be rolled out
int total = sx_*sy_*sz_;
for (int ind = 0; ind < total; ind++) {
Vec3i sub = GridInd2Sub(ind);
bool out = false;
for (int d = 0; d < 3; d++) {
int s = (d==0?sx_:(d==1?sy_:sz_));
int new_s = sub(d) + step(d);
if (new_s < 0 || new_s >= s) { out = true; break; }
}
if (out) rolled_out.push_back(ind);
}
// Apply the offset
for (int d = 0; d < 3; d++) {
int s = (d==0?sx_:(d==1?sy_:sz_));
offset_(d) = ((offset_(d) - step(d)) % s + s) % s;
}
// Collect updated array indices
for (int ind : rolled_out) {
updated.push_back(GetArrayInd(ind));
}
}
private:
Vec3i GridInd2Sub(int ind) const {
int z = ind / (sx_*sy_);
int rem = ind % (sx_*sy_);
int y = rem / sx_;
int x = rem % sx_;
return Vec3i(x,y,z);
}
int sx_, sy_, sz_;
Vec3i offset_;
std::vector<int> ind_map_;
};
// ============================================================================
// Rolling Occupancy Grid
// ============================================================================
enum class OccState : char { UNKNOWN = 0, OCCUPIED = 1, FREE = 2 };
class RollingOccupancyGrid {
public:
RollingOccupancyGrid() : initialized_(false) {}
void Init(double cell_size, double cell_height, int neighbor_num,
double res_x, double res_y, double res_z) {
Vec3d range(cell_size * neighbor_num, cell_size * neighbor_num, cell_height * neighbor_num);
res_ = Vec3d(res_x, res_y, res_z);
for (int i = 0; i < 3; i++)
grid_size_(i) = (int)(range(i) / res_(i));
rollover_step_ = Vec3i((int)(cell_size/res_x), (int)(cell_size/res_y), (int)(cell_height/res_z));
origin_ = -range / 2.0;
grid_.Resize(grid_size_.x(), grid_size_.y(), grid_size_.z(), OccState::UNKNOWN, origin_, res_);
rolling_ = RollingGrid(grid_size_);
}
void InitializeOrigin(const Vec3d& origin) {
if (!initialized_) {
initialized_ = true;
origin_ = origin;
grid_.SetOrigin(origin_);
}
}
bool UpdateRobotPosition(const Vec3d& robot_pos) {
if (!initialized_) return false;
Vec3d diff = robot_pos - origin_;
Vec3i robot_grid_sub;
for (int i = 0; i < 3; i++) {
double step = rollover_step_(i) * res_(i);
robot_grid_sub(i) = diff(i) > 0 ? (int)(diff(i) / step) : -1;
}
Vec3i sub_diff;
for (int i = 0; i < 3; i++)
sub_diff(i) = (grid_size_(i) / rollover_step_(i)) / 2 - robot_grid_sub(i);
if (sub_diff.x()==0 && sub_diff.y()==0 && sub_diff.z()==0) return false;
Vec3i rollover_step(0,0,0);
for (int i = 0; i < 3; i++) {
if (std::abs(sub_diff(i)) > 0)
rollover_step(i) = rollover_step_(i) * (sub_diff(i)>0?1:-1) * std::abs(sub_diff(i));
}
std::vector<int> rolled_out, updated;
rolling_.Roll(rollover_step, rolled_out, updated);
// Update origin
for (int i = 0; i < 3; i++)
origin_(i) -= rollover_step(i) * res_(i);
grid_.SetOrigin(origin_);
// Reset rolled-in cells
for (int arr_ind : updated)
if (grid_.InRange(arr_ind)) grid_.Set(arr_ind, OccState::UNKNOWN);
return true;
}
void UpdateOccupancy(const std::vector<PointXYZI>& cloud) {
if (!initialized_) return;
updated_indices_.clear();
for (const auto& p : cloud) {
Vec3i sub = grid_.Pos2Sub(Vec3d(p.x, p.y, p.z));
if (!grid_.InRange(sub)) continue;
int ind = grid_.Sub2Ind(sub);
int arr_ind = rolling_.GetArrayInd(ind);
if (grid_.InRange(arr_ind)) {
grid_.Set(arr_ind, OccState::OCCUPIED);
updated_indices_.push_back(ind);
}
}
}
// Simple ray tracing from origin through occupied cells
void RayTrace(const Vec3d& origin) {
if (!initialized_) return;
Vec3i origin_sub = grid_.Pos2Sub(origin);
if (!grid_.InRange(origin_sub)) return;
// Uniquify
std::sort(updated_indices_.begin(), updated_indices_.end());
updated_indices_.erase(std::unique(updated_indices_.begin(), updated_indices_.end()), updated_indices_.end());
for (int ind : updated_indices_) {
if (!grid_.InRange(ind)) continue;
Vec3i end_sub = grid_.Ind2Sub(ind);
int arr_ind = rolling_.GetArrayInd(ind);
if (!grid_.InRange(arr_ind) || grid_.At(arr_ind) != OccState::OCCUPIED) continue;
// Bresenham-like ray cast
Vec3i diff = end_sub - origin_sub;
int steps = std::max({std::abs(diff.x()), std::abs(diff.y()), std::abs(diff.z()), 1});
for (int s = 1; s < steps; s++) {
Vec3i cur(origin_sub.x() + diff.x()*s/steps,
origin_sub.y() + diff.y()*s/steps,
origin_sub.z() + diff.z()*s/steps);
if (!grid_.InRange(cur)) break;
int cur_arr = rolling_.GetArrayInd(cur);
if (!grid_.InRange(cur_arr)) break;
if (grid_.At(cur_arr) == OccState::OCCUPIED) break;
grid_.Set(cur_arr, OccState::FREE);
}
}
}
// Extract frontier cells: UNKNOWN cells adjacent to FREE cells in XY
void GetFrontier(std::vector<PointXYZI>& frontier, const Vec3d& origin, const Vec3d& range) {
if (!initialized_) return;
frontier.clear();
Vec3i sub_min = grid_.Pos2Sub(origin - range);
Vec3i sub_max = grid_.Pos2Sub(origin + range);
int cell_num = grid_.CellNumber();
for (int ind = 0; ind < cell_num; ind++) {
Vec3i cur = grid_.Ind2Sub(ind);
if (!grid_.InRange(cur)) continue;
// Bounds check
bool in_range = true;
for (int d = 0; d < 3; d++)
if (cur(d) < sub_min(d) || cur(d) > sub_max(d)) { in_range = false; break; }
if (!in_range) continue;
int arr_ind = rolling_.GetArrayInd(cur);
if (!grid_.InRange(arr_ind) || grid_.At(arr_ind) != OccState::UNKNOWN) continue;
// Check if z-neighbors are free (skip if so - not a frontier)
bool z_free = false;
for (int dz : {-1, 1}) {
Vec3i nb = cur; nb(2) += dz;
if (grid_.InRange(nb)) {
int nb_arr = rolling_.GetArrayInd(nb);
if (grid_.InRange(nb_arr) && grid_.At(nb_arr) == OccState::FREE) { z_free = true; break; }
}
}
if (z_free) continue;
// Check if xy-neighbors are free
bool xy_free = false;
for (int d = 0; d < 2; d++) {
for (int dd : {-1, 1}) {
Vec3i nb = cur; nb(d) += dd;
if (grid_.InRange(nb)) {
int nb_arr = rolling_.GetArrayInd(nb);
if (grid_.InRange(nb_arr) && grid_.At(nb_arr) == OccState::FREE) { xy_free = true; break; }
}
}
if (xy_free) break;
}
if (xy_free) {
Vec3d pos = grid_.Sub2Pos(cur);
frontier.push_back({(float)pos.x(), (float)pos.y(), (float)pos.z(), 0.0f});
}
}
}
private:
bool initialized_;
Vec3d res_;
Vec3i grid_size_;
Vec3i rollover_step_;
Vec3d origin_;
Grid3D<OccState> grid_;
RollingGrid rolling_;
std::vector<int> updated_indices_;
};
// ============================================================================
// Exploration path node types
// ============================================================================
enum class NodeType {
ROBOT = 0,
LOOKAHEAD_POINT = 2,
LOCAL_VIEWPOINT = 4,
LOCAL_PATH_START = 6,
LOCAL_PATH_END = 8,
LOCAL_VIA_POINT = 10,
GLOBAL_VIEWPOINT = 1,
GLOBAL_VIA_POINT = 3,
HOME = 5
};
struct PathNode {
Vec3d position = Vec3d::Zero();
NodeType type = NodeType::LOCAL_VIA_POINT;
int local_viewpoint_ind = -1;
int global_subspace_index = -1;
bool operator==(const PathNode& o) const {
return (position - o.position).norm() < 0.2 && type == o.type;
}
bool operator!=(const PathNode& o) const { return !(*this == o); }
};
struct ExplorationPath {
std::vector<PathNode> nodes;
double GetLength() const {
double len = 0;
for (size_t i = 1; i < nodes.size(); i++)
len += (nodes[i].position - nodes[i-1].position).norm();
return len;
}
int GetNodeNum() const { return (int)nodes.size(); }
void Append(const PathNode& n) {
if (nodes.empty() || nodes.back() != n) nodes.push_back(n);
}
void Append(const ExplorationPath& p) {
for (const auto& n : p.nodes) Append(n);
}
void Reverse() { std::reverse(nodes.begin(), nodes.end()); }
void Reset() { nodes.clear(); }
};
// ============================================================================
// Viewpoint - simplified sensor coverage model
// ============================================================================
struct Viewpoint {
Point3 position;
bool in_collision = false;
bool in_line_of_sight = true;
bool connected = true;
bool visited = false;
bool selected = false;
bool is_candidate = false;
bool in_exploring_cell = false;
double height = 0;
int cell_ind = -1;
std::vector<int> covered_points;
std::vector<int> covered_frontier_points;
void Reset() {
in_collision = false; in_line_of_sight = true;
connected = true; visited = false; selected = false;
is_candidate = false; in_exploring_cell = false;
covered_points.clear(); covered_frontier_points.clear();
}
void ResetCoverage() {
covered_points.clear();
covered_frontier_points.clear();
}
};
// ============================================================================
// Greedy TSP solver (replaces OR-Tools when not available)
// ============================================================================
#ifdef USE_ORTOOLS
#include "ortools/constraint_solver/routing.h"
#include "ortools/constraint_solver/routing_enums.pb.h"
#include "ortools/constraint_solver/routing_index_manager.h"
#include "ortools/constraint_solver/routing_parameters.h"
#endif
static void solve_tsp_greedy(const std::vector<std::vector<int>>& dist_matrix,
int depot,
std::vector<int>& order) {
int n = (int)dist_matrix.size();
if (n <= 1) { order.clear(); if (n==1) order.push_back(0); return; }
std::vector<bool> visited(n, false);
order.clear();
order.push_back(depot);
visited[depot] = true;
for (int step = 1; step < n; step++) {
int cur = order.back();
int best = -1;
int best_dist = std::numeric_limits<int>::max();
for (int j = 0; j < n; j++) {
if (!visited[j] && dist_matrix[cur][j] < best_dist) {
best_dist = dist_matrix[cur][j];
best = j;
}
}
if (best < 0) break;
visited[best] = true;
order.push_back(best);
}
}
#ifdef USE_ORTOOLS
static void solve_tsp_ortools(const std::vector<std::vector<int>>& dist_matrix,
int depot,
std::vector<int>& order) {
using namespace operations_research;
int n = (int)dist_matrix.size();
RoutingIndexManager manager(n, 1, RoutingIndexManager::NodeIndex{depot});
RoutingModel routing(manager);
const int cb = routing.RegisterTransitCallback(
[&](int64_t from, int64_t to) -> int64_t {
return dist_matrix[manager.IndexToNode(from).value()][manager.IndexToNode(to).value()];
});
routing.SetArcCostEvaluatorOfAllVehicles(cb);
RoutingSearchParameters params = DefaultRoutingSearchParameters();
params.set_first_solution_strategy(FirstSolutionStrategy::PATH_CHEAPEST_ARC);
const Assignment* sol = routing.SolveWithParameters(params);
order.clear();
if (sol) {
int64_t idx = routing.Start(0);
while (!routing.IsEnd(idx)) {
order.push_back((int)manager.IndexToNode(idx).value());
idx = sol->Value(routing.NextVar(idx));
}
}
}
#endif
static void solve_tsp(const std::vector<std::vector<int>>& dist_matrix,
int depot, std::vector<int>& order) {
#ifdef USE_ORTOOLS
solve_tsp_ortools(dist_matrix, depot, order);
#else
solve_tsp_greedy(dist_matrix, depot, order);
#endif
}
// ============================================================================
// Keypose Graph - simplified graph of robot key poses
// ============================================================================
struct KeyposeNode {
Point3 position;
int node_ind = 0;
int keypose_id = 0;
bool is_keypose = true;
bool is_connected = true;
};
class KeyposeGraph {
public:
std::vector<KeyposeNode> nodes;
std::vector<std::vector<int>> graph;
std::vector<std::vector<double>> dist;
double kAddNodeMinDist = 0.5;
double kAddNonKeyposeNodeMinDist = 0.5;
double kAddEdgeConnectDistThr = 0.5;
double kAddEdgeToLastKeyposeDistThr = 0.5;
double kAddEdgeVerticalThreshold = 0.5;
int current_keypose_id = 0;
Point3 current_keypose_position;
void AddNode(const Point3& pos, int node_ind, int keypose_id, bool is_kp) {
KeyposeNode n;
n.position = pos; n.node_ind = node_ind;
n.keypose_id = keypose_id; n.is_keypose = is_kp;
nodes.push_back(n);
graph.push_back({});
dist.push_back({});
}
void AddEdge(int from, int to, double d) {
if (from < 0 || from >= (int)graph.size() || to < 0 || to >= (int)graph.size()) return;
graph[from].push_back(to); graph[to].push_back(from);
dist[from].push_back(d); dist[to].push_back(d);
}
bool HasEdgeBetween(int a, int b) const {
if (a < 0 || a >= (int)graph.size() || b < 0 || b >= (int)graph.size()) return false;
return std::find(graph[a].begin(), graph[a].end(), b) != graph[a].end();
}
int AddKeyposeNode(const Point3& pos, int keypose_id) {
current_keypose_position = pos;
current_keypose_id = keypose_id;
int new_ind = (int)nodes.size();
if (nodes.empty()) {
AddNode(pos, new_ind, keypose_id, true);
return new_ind;
}
// Find closest keypose and last keypose
double min_dist = 1e18; int min_ind = -1;
double last_dist = 1e18; int last_ind = -1; int max_kp_id = 0;
for (int i = 0; i < (int)nodes.size(); i++) {
if (!nodes[i].is_keypose) continue;
if (std::abs(nodes[i].position.z - pos.z) > kAddEdgeVerticalThreshold) continue;
double d = point_dist(nodes[i].position, pos);
if (d < min_dist) { min_dist = d; min_ind = i; }
if (nodes[i].keypose_id > max_kp_id) {
max_kp_id = nodes[i].keypose_id;
last_dist = d; last_ind = i;
}
}
if (min_ind >= 0 && min_dist > kAddNodeMinDist) {
if (last_dist < kAddEdgeToLastKeyposeDistThr && last_ind >= 0) {
AddNode(pos, new_ind, keypose_id, true);
AddEdge(last_ind, new_ind, last_dist);
} else {
AddNode(pos, new_ind, keypose_id, true);
AddEdge(min_ind, new_ind, min_dist);
}
// Connect to other in-range nodes
for (int i = 0; i < (int)nodes.size()-1; i++) {
double d = point_dist(nodes[i].position, pos);
if (d < kAddEdgeConnectDistThr && !HasEdgeBetween(new_ind, i)) {
AddEdge(new_ind, i, d);
}
}
return new_ind;
} else if (min_ind >= 0) {
return min_ind;
} else {
AddNode(pos, new_ind, keypose_id, true);
return new_ind;
}
}
int GetClosestNodeInd(const Point3& pos) const {
int best = -1; double best_d = 1e18;
for (int i = 0; i < (int)nodes.size(); i++) {
double d = point_dist(nodes[i].position, pos);
if (d < best_d) { best_d = d; best = i; }
}
return best;
}
Point3 GetClosestNodePosition(const Point3& pos) const {
int ind = GetClosestNodeInd(pos);
if (ind >= 0) return nodes[ind].position;
return Point3{0,0,0};
}
// Dijkstra shortest path
double GetShortestPath(const Point3& start, const Point3& goal,
std::vector<Point3>& path_points) const {
path_points.clear();
if (nodes.size() < 2) {
path_points.push_back(start);
path_points.push_back(goal);
return point_dist(start, goal);
}
int from = GetClosestNodeInd(start);
int to = GetClosestNodeInd(goal);
if (from < 0 || to < 0) return 1e18;
int n = (int)nodes.size();
std::vector<double> d(n, 1e18);
std::vector<int> prev(n, -1);
d[from] = 0;
using PII = std::pair<double, int>;
std::priority_queue<PII, std::vector<PII>, std::greater<PII>> pq;
pq.push({0, from});
while (!pq.empty()) {
auto [cd, u] = pq.top(); pq.pop();
if (cd > d[u]) continue;
for (int j = 0; j < (int)graph[u].size(); j++) {
int v = graph[u][j];
double nd = d[u] + dist[u][j];
if (nd < d[v]) {
d[v] = nd; prev[v] = u;
pq.push({nd, v});
}
}
}
if (d[to] >= 1e17) {
path_points.push_back(start);
path_points.push_back(goal);
return point_dist(start, goal);
}
std::vector<int> idx;
for (int cur = to; cur != -1; cur = prev[cur]) idx.push_back(cur);
std::reverse(idx.begin(), idx.end());
for (int i : idx) path_points.push_back(nodes[i].position);
return d[to];
}
// Connectivity check (BFS from first keypose)
void CheckConnectivity() {
for (auto& n : nodes) n.is_connected = false;
int start = -1;
for (int i = 0; i < (int)nodes.size(); i++) {
if (nodes[i].is_keypose) { start = i; break; }
}
if (start < 0) return;
std::queue<int> q; q.push(start);
nodes[start].is_connected = true;
while (!q.empty()) {
int u = q.front(); q.pop();
for (int v : graph[u]) {
if (!nodes[v].is_connected) {
nodes[v].is_connected = true;
q.push(v);
}
}
}
}
};
// ============================================================================
// Grid World - maintains global exploration subspaces
// ============================================================================
enum class CellStatus { UNSEEN = 0, EXPLORING = 1, COVERED = 2, NOGO = 3 };
struct GridCell {
Point3 center;
CellStatus status = CellStatus::UNSEEN;
std::vector<int> viewpoint_indices;
int visit_count = 0;
int keypose_id = 0;
Vec3d viewpoint_position = Vec3d::Zero();
};
class GridWorld {
public:
GridWorld() : initialized_(false), neighbors_init_(false), return_home_(false), set_home_(false),
kCellSize(6.0), kCellHeight(6.0), kNearbyGridNum(5),
kRowNum(121), kColNum(121), kLevelNum(12),
kMinAddPointNumSmall(60), kMinAddFrontierPointNum(30),
kCellExploringToCoveredThr(1), kCellUnknownToExploringThr(1),
cur_robot_cell_ind_(-1) {}
void Init(int rows, int cols, int levels, double cell_size, double cell_height, int nearby,
int min_add_small, int min_add_frontier, int exp_to_cov, int unk_to_exp) {
kRowNum = rows; kColNum = cols; kLevelNum = levels;
kCellSize = cell_size; kCellHeight = cell_height; kNearbyGridNum = nearby;
kMinAddPointNumSmall = min_add_small;
kMinAddFrontierPointNum = min_add_frontier;
kCellExploringToCoveredThr = exp_to_cov;
kCellUnknownToExploringThr = unk_to_exp;
Vec3d origin(-kRowNum * kCellSize / 2, -kColNum * kCellSize / 2, -kLevelNum * kCellHeight / 2);
Vec3d res(kCellSize, kCellSize, kCellHeight);
grid_.Resize(kRowNum, kColNum, kLevelNum, GridCell{}, origin, res);
// Initialize cell centers
for (int ind = 0; ind < grid_.CellNumber(); ind++) {
Vec3d pos = grid_.Ind2Pos(ind);
grid_.At(ind).center = {pos.x(), pos.y(), pos.z()};
}
initialized_ = true;
}
bool Initialized() const { return initialized_; }
bool NeighborsInitialized() const { return neighbors_init_; }
void UpdateRobotPosition(const Point3& pos) {
robot_position_ = pos;
Vec3i sub = grid_.Pos2Sub(Vec3d(pos.x, pos.y, pos.z));
if (grid_.InRange(sub)) {
cur_robot_cell_ind_ = grid_.Sub2Ind(sub);
}
}
void UpdateNeighborCells(const Point3& pos) {
// Re-center the grid on the robot position
Vec3d robot_pos(pos.x, pos.y, pos.z);
Vec3d origin(robot_pos.x() - kRowNum * kCellSize / 2.0,
robot_pos.y() - kColNum * kCellSize / 2.0,
robot_pos.z() - kLevelNum * kCellHeight / 2.0);
grid_.SetOrigin(origin);
neighbor_indices_.clear();
Vec3i center = grid_.Pos2Sub(robot_pos);
for (int dx = -kNearbyGridNum; dx <= kNearbyGridNum; dx++) {
for (int dy = -kNearbyGridNum; dy <= kNearbyGridNum; dy++) {
for (int dz = -1; dz <= 1; dz++) {
Vec3i sub(center.x()+dx, center.y()+dy, center.z()+dz);
if (grid_.InRange(sub)) {
neighbor_indices_.push_back(grid_.Sub2Ind(sub));
}
}
}
}
neighbors_init_ = true;
}
// Update cell status using frontier points to drive UNSEEN → EXPLORING.
// frontier_cloud contains detected frontier (unexplored boundary) points.
void UpdateCellStatus(const std::vector<PointXYZI>& frontier_cloud) {
// Count frontier points per neighbor cell
std::map<int, int> frontier_count_per_cell;
for (const auto& fp : frontier_cloud) {
Vec3i sub = grid_.Pos2Sub(Vec3d(fp.x, fp.y, fp.z));
if (grid_.InRange(sub)) {
int ind = grid_.Sub2Ind(sub);
frontier_count_per_cell[ind]++;
}
}
int exploring_count = 0;
for (int ind : neighbor_indices_) {
auto& cell = grid_.At(ind);
int fc = 0;
auto it = frontier_count_per_cell.find(ind);
if (it != frontier_count_per_cell.end()) fc = it->second;
// Cells with enough frontier points transition to EXPLORING
if (cell.status == CellStatus::UNSEEN && fc >= kCellUnknownToExploringThr) {
cell.status = CellStatus::EXPLORING;
}
// Exploring cells with no remaining frontiers transition to COVERED
if (cell.status == CellStatus::EXPLORING && fc == 0) {
cell.visit_count++;
if (cell.visit_count >= kCellExploringToCoveredThr * 10) {
cell.status = CellStatus::COVERED;
}
}
if (cell.status == CellStatus::EXPLORING) exploring_count++;
}
return_home_ = (exploring_count == 0 && initialized_);
}
bool IsReturningHome() const { return return_home_; }
int ExploringCount() const {
int c = 0;
for (int ind : neighbor_indices_)
if (grid_.At(ind).status == CellStatus::EXPLORING) c++;
return c;
}
void SetHomePosition(const Vec3d& pos) { home_position_ = pos; set_home_ = true; }
bool HomeSet() const { return set_home_; }
// Simple global TSP: visit exploring cells in nearest-first order
ExplorationPath SolveGlobalTSP(const KeyposeGraph& keypose_graph) {
ExplorationPath path;
std::vector<int> exploring_cells;
for (int ind : neighbor_indices_) {
if (grid_.At(ind).status == CellStatus::EXPLORING)
exploring_cells.push_back(ind);
}
if (exploring_cells.empty()) {
if (set_home_) {
PathNode rn; rn.position = Vec3d(robot_position_.x, robot_position_.y, robot_position_.z);
rn.type = NodeType::ROBOT;
path.Append(rn);
PathNode hn; hn.position = home_position_; hn.type = NodeType::HOME;
path.Append(hn);
}
return path;
}
// Build distance matrix for exploring cells + robot
int n = (int)exploring_cells.size() + 1; // last is robot
std::vector<std::vector<int>> dist_matrix(n, std::vector<int>(n, 0));
std::vector<Point3> positions(n);
for (int i = 0; i < (int)exploring_cells.size(); i++) {
positions[i] = grid_.At(exploring_cells[i]).center;
}
positions[n-1] = robot_position_;
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
int d = (int)(10.0 * point_dist(positions[i], positions[j]));
dist_matrix[i][j] = d;
dist_matrix[j][i] = d;
}
}
std::vector<int> order;
solve_tsp(dist_matrix, n-1, order);
PathNode robot_node;
robot_node.position = Vec3d(robot_position_.x, robot_position_.y, robot_position_.z);
robot_node.type = NodeType::ROBOT;
path.Append(robot_node);
for (int idx : order) {
if (idx == n-1) continue; // skip robot
PathNode node;
const auto& c = positions[idx];
node.position = Vec3d(c.x, c.y, c.z);
node.type = NodeType::GLOBAL_VIEWPOINT;
node.global_subspace_index = exploring_cells[idx];
path.Append(node);
}
// Append home
if (set_home_) {
PathNode hn; hn.position = home_position_; hn.type = NodeType::HOME;
path.Append(hn);
}
return path;
}
const std::vector<int>& GetNeighborIndices() const { return neighbor_indices_; }
private:
bool initialized_;
bool neighbors_init_;
bool return_home_;
bool set_home_;
Vec3d home_position_;
Point3 robot_position_;
double kCellSize, kCellHeight;
int kNearbyGridNum;
int kRowNum, kColNum, kLevelNum;
int kMinAddPointNumSmall, kMinAddFrontierPointNum;
int kCellExploringToCoveredThr, kCellUnknownToExploringThr;
int cur_robot_cell_ind_;
Grid3D<GridCell> grid_;
std::vector<int> neighbor_indices_;
};
// ============================================================================
// TARE Planner - main exploration planner class
// ============================================================================
class TarePlanner {
public:
// --- Configuration ---
bool kAutoStart = true;
bool kRushHome = true;
bool kUseTerrainHeight = false;
bool kCheckTerrainCollision = true;
bool kExtendWayPoint = true;
bool kUseLineOfSightLookAheadPoint = true;
bool kNoExplorationReturnHome = true;
bool kUseMomentum = false;
bool kUseFrontier = true;
double kKeyposeCloudDwzFilterLeafSize = 0.2;
double kRushHomeDist = 10.0;
double kAtHomeDistThreshold = 0.5;
double kTerrainCollisionThreshold = 0.5;
double kLookAheadDistance = 5.0;
double kExtendWayPointDistanceBig = 8.0;
double kExtendWayPointDistanceSmall = 3.0;
double kSensorRange = 10.0;