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