]> rtime.felk.cvut.cz Git - hubacji1/rrts.git/blob - src/rrts.cc
Merge branch 'gz-entries'
[hubacji1/rrts.git] / src / rrts.cc
1 #include <algorithm>
2 #include "rrts.h"
3
4 #include "reeds_shepp.h"
5
6 template <typename T> int sgn(T val) {
7         return (T(0) < val) - (val < T(0));
8 }
9
10 RRTNode::RRTNode()
11 {
12 }
13
14 RRTNode::RRTNode(const BicycleCar &bc)
15 {
16     this->x(bc.x());
17     this->y(bc.y());
18     this->h(bc.h());
19     this->sp(bc.sp());
20     this->st(bc.st());
21 }
22
23 bool RRTNode::operator==(const RRTNode& n)
24 {
25         if (this == &n)
26                 return true;
27         return false;
28 }
29
30 Obstacle::Obstacle()
31 {
32 }
33
34 double RRTS::elapsed()
35 {
36         std::chrono::duration<double> dt;
37         dt = std::chrono::duration_cast<std::chrono::duration<double>>(
38                 std::chrono::high_resolution_clock::now()
39                 - this->tstart_
40         );
41         this->scnt_ = dt.count();
42         return this->scnt_;
43 }
44
45 void RRTS::log_path_cost()
46 {
47         this->log_path_cost_.push_back(cc(this->goals().front()));
48         this->log_path_time_ += 0.1;
49 }
50
51 bool RRTS::should_stop()
52 {
53         // the following counters must be updated, do not comment
54         this->icnt_++;
55         this->elapsed();
56         // current iteration stop conditions
57         if (this->should_finish()) return true;
58         if (this->should_break()) return true;
59         // but continue by default
60         return false;
61 }
62
63 bool RRTS::should_finish()
64 {
65         // decide finish conditions (maybe comment some lines)
66         //if (this->icnt_ > 999) return true;
67         if (this->scnt_ > 2) return true;
68         //if (this->gf()) return true;
69         // but continue by default
70         return false;
71 }
72
73 bool RRTS::should_break()
74 {
75         // decide break conditions (maybe comment some lines)
76         //if (this->scnt_ - this->pcnt_ > 2) return true;
77         // but continue by default
78         return false;
79 }
80
81 bool RRTS::should_continue()
82 {
83         // decide the stop conditions (maybe comment some lines)
84         // it is exact opposite of `should_stop`
85         //if (this->icnt_ > 999) return false;
86         if (this->scnt_ > 10) return false;
87         if (this->gf()) return false;
88         // and reset pause counter if should continue
89         this->pcnt_ = this->scnt_;
90         return true;
91 }
92
93 void RRTS::store_node(RRTNode n)
94 {
95         this->nodes().push_back(n);
96 }
97
98 // RRT procedures
99 std::tuple<bool, unsigned int, unsigned int>
100 RRTS::collide(std::vector<std::tuple<double, double>> &poly)
101 {
102         for (auto &o: this->obstacles())
103                 if (std::get<0>(::collide(poly, o.poly())))
104                         return ::collide(poly, o.poly());
105         return std::make_tuple(false, 0, 0);
106 }
107
108 std::tuple<bool, unsigned int, unsigned int>
109 RRTS::collide_steered_from(RRTNode &f)
110 {
111         auto fbc = BicycleCar();
112         fbc.x(f.x());
113         fbc.y(f.y());
114         fbc.h(f.h());
115         std::vector<std::tuple<double, double>> s;
116         s.push_back(std::make_tuple(fbc.x(), fbc.y()));
117         for (auto &n: this->steered()) {
118                 auto nbc = BicycleCar();
119                 nbc.x(n.x());
120                 nbc.y(n.y());
121                 nbc.h(n.h());
122                 s.push_back(std::make_tuple(nbc.lfx(), nbc.lfy()));
123                 s.push_back(std::make_tuple(nbc.lrx(), nbc.lry()));
124                 s.push_back(std::make_tuple(nbc.rrx(), nbc.rry()));
125                 s.push_back(std::make_tuple(nbc.rfx(), nbc.rfy()));
126         }
127         auto col = this->collide(s);
128         auto strip_from = this->steered().size() - std::get<1>(col) / 4;
129         if (std::get<0>(col) && strip_from > 0) {
130                 while (strip_from-- > 0) {
131                         this->steered().pop_back();
132                 }
133                 return this->collide_steered_from(f);
134         }
135         return col;
136 }
137
138 std::tuple<bool, unsigned int, unsigned int>
139 RRTS::collide_two_nodes(RRTNode &f, RRTNode &t)
140 {
141         auto fbc = BicycleCar();
142         fbc.x(f.x());
143         fbc.y(f.y());
144         fbc.h(f.h());
145         auto tbc = BicycleCar();
146         tbc.x(f.x());
147         tbc.y(f.y());
148         tbc.h(f.h());
149         std::vector<std::tuple<double, double>> p;
150         p.push_back(std::make_tuple(fbc.lfx(), fbc.lfy()));
151         p.push_back(std::make_tuple(fbc.lrx(), fbc.lry()));
152         p.push_back(std::make_tuple(fbc.rrx(), fbc.rry()));
153         p.push_back(std::make_tuple(fbc.rfx(), fbc.rfy()));
154         p.push_back(std::make_tuple(tbc.lfx(), tbc.lfy()));
155         p.push_back(std::make_tuple(tbc.lrx(), tbc.lry()));
156         p.push_back(std::make_tuple(tbc.rrx(), tbc.rry()));
157         p.push_back(std::make_tuple(tbc.rfx(), tbc.rfy()));
158         return this->collide(p);
159 }
160
161 double RRTS::cost_build(RRTNode &f, RRTNode &t)
162 {
163         double cost = 0;
164         cost = sqrt(pow(t.y() - f.y(), 2) + pow(t.x() - f.x(), 2));
165         return cost;
166 }
167
168 double RRTS::cost_search(RRTNode &f, RRTNode &t)
169 {
170         double cost = 0;
171         cost = sqrt(pow(t.y() - f.y(), 2) + pow(t.x() - f.x(), 2));
172         return cost;
173 }
174
175 void RRTS::sample()
176 {
177         double x = 0;
178         double y = 0;
179         double h = 0;
180         switch (this->sample_dist_type()) {
181         case 1: // uniform
182                 x = this->udx_(this->gen_);
183                 y = this->udy_(this->gen_);
184                 h = this->udh_(this->gen_);
185                 break;
186         case 2: // uniform circle
187         {
188                 // see https://stackoverflow.com/questions/5837572/generate-a-random-point-within-a-circle-uniformly/50746409#50746409
189                 double R = sqrt(
190                         pow(
191                                 this->nodes().front().x()
192                                 - this->goals().front().x(),
193                                 2
194                         )
195                         + pow(
196                                 this->nodes().front().y()
197                                 - this->goals().front().y(),
198                                 2
199                         )
200                 );
201                 double a = atan2(
202                         this->goals().front().y() - this->nodes().front().y(),
203                         this->goals().front().x() - this->nodes().front().x()
204                 );
205                 double cx = this->goals().front().x() + R/2 * cos(a);
206                 double cy = this->goals().front().y() + R/2 * sin(a);
207                 double r = R * sqrt(this->udx_(this->gen_));
208                 double theta = this->udy_(this->gen_) * 2 * M_PI;
209                 x = cx + r * cos(theta);
210                 y = cy + r * sin(theta);
211                 h = this->udh_(this->gen_);
212         }
213                 break;
214         default: // normal
215                 x = this->ndx_(this->gen_);
216                 y = this->ndy_(this->gen_);
217                 h = this->ndh_(this->gen_);
218         }
219         this->samples().push_back(RRTNode());
220         this->samples().back().x(x);
221         this->samples().back().y(y);
222         this->samples().back().h(h);
223 }
224
225 RRTNode *RRTS::nn(RRTNode &t)
226 {
227         RRTNode *nn = &this->nodes().front();
228         double cost = this->cost_search(*nn, t);
229         for (auto &f: this->nodes()) {
230                 if (this->cost_search(f, t) < cost) {
231                         nn = &f;
232                         cost = this->cost_search(f, t);
233                 }
234         }
235         return nn;
236 }
237
238 std::vector<RRTNode *> RRTS::nv(RRTNode &t)
239 {
240         std::vector<RRTNode *> nv;
241         double cost = std::min(GAMMA(this->nodes().size()), ETA);
242         for (auto &f: this->nodes())
243                 if (this->cost_search(f, t) < cost)
244                         nv.push_back(&f);
245         return nv;
246 }
247
248 int cb_rs_steer(double q[4], void *user_data)
249 {
250         std::vector<RRTNode> *nodes = (std::vector<RRTNode> *) user_data;
251         RRTNode *ln = nullptr;
252         if (nodes->size() > 0)
253                 ln = &nodes->back();
254         nodes->push_back(RRTNode());
255         nodes->back().x(q[0]);
256         nodes->back().y(q[1]);
257         nodes->back().h(q[2]);
258         nodes->back().sp(q[3]);
259         if (nodes->back().sp() == 0)
260                 nodes->back().set_t(RRTNodeType::cusp);
261         else if (ln != nullptr && sgn(ln->sp()) != sgn(nodes->back().sp()))
262                 ln->set_t(RRTNodeType::cusp);
263         return 0;
264 }
265
266 void RRTS::steer(RRTNode &f, RRTNode &t)
267 {
268         this->steered().clear();
269         double q0[] = {f.x(), f.y(), f.h()};
270         double q1[] = {t.x(), t.y(), t.h()};
271         ReedsSheppStateSpace rsss(this->bc.mtr());
272         rsss.sample(q0, q1, 0.05, cb_rs_steer, &this->steered());
273 }
274
275 void RRTS::steer1(RRTNode &f, RRTNode &t)
276 {
277     return this->steer(f, t);
278 }
279
280 void RRTS::steer2(RRTNode &f, RRTNode &t)
281 {
282     return this->steer(f, t);
283 }
284
285 void RRTS::join_steered(RRTNode *f)
286 {
287         while (this->steered().size() > 0) {
288                 this->store_node(this->steered().front());
289                 RRTNode *t = &this->nodes().back();
290                 t->p(f);
291                 t->c(this->cost_build(*f, *t));
292                 this->steered().erase(this->steered().begin());
293                 f = t;
294         }
295 }
296
297 bool RRTS::goal_found(RRTNode &f)
298 {
299         auto &g = this->goals().front();
300         double cost = this->cost_build(f, g);
301         double edist = sqrt(
302                 pow(f.x() - g.x(), 2)
303                 + pow(f.y() - g.y(), 2)
304         );
305         double adist = std::abs(f.h() - g.h());
306         if (edist < 0.05 && adist < M_PI / 32) {
307                 if (g.p() == nullptr || cc(f) + cost < cc(g)) {
308                         g.p(&f);
309                         g.c(cost);
310                 }
311                 return true;
312         }
313         return false;
314 }
315
316 // RRT* procedures
317 bool RRTS::connect()
318 {
319         RRTNode *t = &this->steered().front();
320         RRTNode *f = this->nn(this->samples().back());
321         double cost = this->cost_search(*f, *t);
322         for (auto n: this->nv(*t)) {
323                 if (
324                         !std::get<0>(this->collide_two_nodes(*n, *t))
325                         && this->cost_search(*n, *t) < cost
326                 ) {
327                         f = n;
328                         cost = this->cost_search(*n, *t);
329                 }
330         }
331         this->store_node(this->steered().front());
332         t = &this->nodes().back();
333         t->p(f);
334         t->c(this->cost_build(*f, *t));
335         t->set_t(RRTNodeType::connected);
336         return true;
337 }
338
339 void RRTS::rewire()
340 {
341         RRTNode *f = &this->nodes().back();
342         for (auto n: this->nv(*f)) {
343                 if (
344                         !std::get<0>(this->collide_two_nodes(*f, *n))
345                         && cc(*f) + this->cost_search(*f, *n) < cc(*n)
346                 ) {
347                         n->p(f);
348                         n->c(this->cost_build(*f, *n));
349                 }
350         }
351 }
352
353 // API
354 void RRTS::init()
355 {
356 }
357
358 void RRTS::deinit()
359 {
360         this->nodes().clear();
361         this->samples().clear();
362         this->steered().clear();
363         this->store_node(RRTNode()); // root
364         this->icnt_ = 0;
365         this->scnt_ = 0;
366         this->pcnt_ = 0;
367         this->gf_ = false;
368 }
369
370 std::vector<RRTNode *> RRTS::path()
371 {
372         std::vector<RRTNode *> path;
373         if (this->goals().size() == 0)
374                 return path;
375         RRTNode *goal = &this->goals().back();
376         if (goal->p() == nullptr)
377                 return path;
378         while (goal != nullptr) {
379                 path.push_back(goal);
380                 goal = goal->p();
381         }
382         std::reverse(path.begin(), path.end());
383         return path;
384 }
385
386 bool RRTS::next()
387 {
388         if (this->icnt_ == 0)
389                 this->tstart_ = std::chrono::high_resolution_clock::now();
390         bool next = true;
391         if (this->scnt_ > this->log_path_time_)
392             this->log_path_cost();
393         if (this->should_stop())
394                 return false;
395         if (this->samples().size() == 0) {
396                 this->samples().push_back(RRTNode());
397                 this->samples().back().x(this->goals().front().x());
398                 this->samples().back().y(this->goals().front().y());
399                 this->samples().back().h(this->goals().front().h());
400         } else {
401                 this->sample();
402         }
403         this->steer1(
404                 *this->nn(this->samples().back()),
405                 this->samples().back()
406         );
407         if (std::get<0>(this->collide_steered_from(
408                 *this->nn(this->samples().back())
409         )))
410                 return next;
411         if (!this->connect())
412                 return next;
413         this->rewire();
414         unsigned scnt = this->steered().size();
415         this->join_steered(&this->nodes().back());
416         RRTNode *just_added = &this->nodes().back();
417         while (scnt > 0) {
418                 scnt--;
419                 auto &g = this->goals().front();
420                 this->steer2(*just_added, g);
421                 if (std::get<0>(this->collide_steered_from(
422                         *just_added
423                 )))
424                         continue;
425                 this->join_steered(just_added);
426                 this->gf(this->goal_found(this->nodes().back()));
427                 just_added = just_added->p();
428         }
429         return next;
430 }
431
432 void RRTS::set_sample_normal(
433         double mx, double dx,
434         double my, double dy,
435         double mh, double dh
436 )
437 {
438         this->ndx_ = std::normal_distribution<double>(mx, dx);
439         this->ndy_ = std::normal_distribution<double>(my, dy);
440         this->ndh_ = std::normal_distribution<double>(mh, dh);
441 }
442 void RRTS::set_sample_uniform(
443         double xmin, double xmax,
444         double ymin, double ymax,
445         double hmin, double hmax
446 )
447 {
448         this->udx_ = std::uniform_real_distribution<double>(xmin,xmax);
449         this->udy_ = std::uniform_real_distribution<double>(ymin,ymax);
450         this->udh_ = std::uniform_real_distribution<double>(hmin,hmax);
451 }
452 void RRTS::set_sample_uniform_circle()
453 {
454         this->udx_ = std::uniform_real_distribution<double>(0, 1);
455         this->udy_ = std::uniform_real_distribution<double>(0, 1);
456         this->udh_ = std::uniform_real_distribution<double>(0, 2 * M_PI);
457 }
458 void RRTS::set_sample(
459         double x1, double x2,
460         double y1, double y2,
461         double h1, double h2
462 )
463 {
464         switch (this->sample_dist_type()) {
465         case 1: // uniform
466                 x1 += this->nodes().front().x();
467                 x2 += this->nodes().front().x();
468                 y1 += this->nodes().front().y();
469                 y2 += this->nodes().front().y();
470                 this->set_sample_uniform(x1, x2, y1, y2, h1, h2);
471                 break;
472         case 2: // uniform circle
473                 this->set_sample_uniform_circle();
474                 break;
475         default: // normal
476                 this->set_sample_normal(x1, x2, y1, y2, h1, h2);
477         }
478 }
479
480 Json::Value RRTS::json()
481 {
482         Json::Value jvo;
483         {
484                 jvo["time"] = this->scnt();
485         }
486         {
487                 jvo["iterations"] = this->icnt();
488         }
489         {
490                 jvo["init"][0] = this->nodes().front().x();
491                 jvo["init"][1] = this->nodes().front().y();
492                 jvo["init"][2] = this->nodes().front().h();
493         }
494         {
495                 jvo["path_cost_before_opt"] = this->path_cost_before_opt_;
496         }
497         {
498                 if (this->path().size() > 0) {
499                         jvo["cost"] = cc(*this->path().back());
500                         jvo["entry"][0] = this->goals().front().x();
501                         jvo["entry"][1] = this->goals().front().y();
502                         jvo["entry"][2] = this->goals().front().h();
503                         jvo["goal"][0] = this->goals().back().x();
504                         jvo["goal"][1] = this->goals().back().y();
505                         jvo["goal"][2] = this->goals().back().h();
506                 }
507         }
508         {
509                 unsigned int cu = 0;
510                 unsigned int co = 0;
511                 unsigned int pcnt = 0;
512                 for (auto n: this->path()) {
513                         jvo["path"][pcnt][0] = n->x();
514                         jvo["path"][pcnt][1] = n->y();
515                         jvo["path"][pcnt][2] = n->h();
516                         if (n->t(RRTNodeType::cusp))
517                                 cu++;
518                         if (n->t(RRTNodeType::connected))
519                                 co++;
520                         pcnt++;
521                 }
522                 jvo["cusps-in-path"] = cu;
523                 jvo["connecteds-in-path"] = co;
524         }
525         {
526                 unsigned int gcnt = 0;
527                 for (auto g: this->goals()) {
528                         jvo["goals"][gcnt][0] = g.x();
529                         jvo["goals"][gcnt][1] = g.y();
530                         jvo["goals"][gcnt][2] = g.h();
531                         gcnt++;
532                 }
533         }
534         {
535                 unsigned int ocnt = 0;
536                 for (auto o: this->obstacles()) {
537                         unsigned int ccnt = 0;
538                         for (auto c: o.poly()) {
539                                 jvo["obst"][ocnt][ccnt][0] = std::get<0>(c);
540                                 jvo["obst"][ocnt][ccnt][1] = std::get<1>(c);
541                                 ccnt++;
542                         }
543                         ocnt++;
544                 }
545         }
546         {
547                 jvo["nodes"] = (unsigned int) this->nodes().size();
548         }
549         {
550                 unsigned int cnt = 0;
551                 for (auto i: this->log_path_cost_)
552                         jvo["log_path_cost"][cnt++] = i;
553         }
554         //{
555         //        unsigned int ncnt = 0;
556         //        for (auto n: this->nodes()) {
557         //                jvo["nodes_x"][ncnt] = n.x();
558         //                jvo["nodes_y"][ncnt] = n.y();
559         //                //jvo["nodes_h"][ncnt] = n.h();
560         //                ncnt++;
561         //        }
562         //}
563         return jvo;
564 }
565
566 void RRTS::json(Json::Value jvi)
567 {
568         assert(jvi["init"] != Json::nullValue);
569         assert(jvi["goals"] != Json::nullValue);
570         assert(jvi["obst"] != Json::nullValue);
571
572         this->nodes().front().x(jvi["init"][0].asDouble());
573         this->nodes().front().y(jvi["init"][1].asDouble());
574         this->nodes().front().h(jvi["init"][2].asDouble());
575         {
576             if (jvi["entry"] != Json::nullValue) {
577                 this->entry_set = true;
578                 this->entry.x = jvi["entry"][0].asDouble();
579                 this->entry.y = jvi["entry"][1].asDouble();
580                 this->entry.b = jvi["entry"][2].asDouble();
581                 this->entry.e = jvi["entry"][3].asDouble();
582             } else {
583                 this->entry.x = 0.0;
584                 this->entry.y = 0.0;
585                 this->entry.b = 0.0;
586                 this->entry.e = 0.0;
587             }
588         }
589         {
590                 RRTNode tmp_node;
591                 RRTNode* gp = nullptr;
592                 if (jvi["entry"] != Json::nullValue) {
593                     this->entry_set = true;
594                     this->entry.x = jvi["entry"][0].asDouble();
595                     this->entry.y = jvi["entry"][1].asDouble();
596                     this->entry.b = jvi["entry"][2].asDouble();
597                     this->entry.e = jvi["entry"][3].asDouble();
598                     tmp_node.x(this->entry.x);
599                     tmp_node.y(this->entry.y);
600                     tmp_node.h((this->entry.b + this->entry.e) / 2.0);
601                     this->goals().push_back(tmp_node);
602                     this->goals().back().p(gp);
603                     gp = &this->goals().back();
604                 }
605                 for (auto g: jvi["goals"]) {
606                         tmp_node.x(g[0].asDouble());
607                         tmp_node.y(g[1].asDouble());
608                         tmp_node.h(g[2].asDouble());
609                         this->goals().push_back(tmp_node);
610                         this->goals().back().p(gp);
611                         gp = &this->goals().back();
612                 }
613                 this->goals().front().set_t(RRTNodeType::cusp);
614                 this->goals().back().set_t(RRTNodeType::cusp);
615         }
616         {
617                 Obstacle tmp_obstacle;
618                 for (auto o: jvi["obst"]) {
619                         tmp_obstacle.poly().clear();
620                         for (auto c: o) {
621                                 double tmp_x = c[0].asDouble();
622                                 double tmp_y = c[1].asDouble();
623                                 auto tmp_tuple = std::make_tuple(tmp_x, tmp_y);
624                                 tmp_obstacle.poly().push_back(tmp_tuple);
625                         }
626                         this->obstacles().push_back(tmp_obstacle);
627                 }
628         }
629         {
630                 double edist_init_goal = sqrt(
631                         pow(
632                                 this->nodes().front().x()
633                                 - this->goals().front().x(),
634                                 2
635                         )
636                         + pow(
637                                 this->nodes().front().y()
638                                 - this->goals().front().y(),
639                                 2
640                         )
641                 );
642                 this->set_sample(
643                         this->nodes().front().x(), edist_init_goal,
644                         this->nodes().front().y(), edist_init_goal,
645                         0, 2 * M_PI
646                 );
647         }
648 }
649
650 RRTS::RRTS()
651         : gen_(std::random_device{}())
652 {
653         this->goals().reserve(100);
654         this->nodes().reserve(4000000);
655         this->samples().reserve(1000);
656         this->steered().reserve(20000);
657         this->store_node(RRTNode()); // root
658 }
659
660 double cc(RRTNode &t)
661 {
662         RRTNode *n = &t;
663         double cost = 0;
664         while (n != nullptr) {
665                 cost += n->c();
666                 n = n->p();
667         }
668         return cost;
669 }