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