]> rtime.felk.cvut.cz Git - hubacji1/iamcar.git/blob - base/rrtbase.cc
bf366dd056624663be91466f8dfdc95a38d2670e
[hubacji1/iamcar.git] / base / rrtbase.cc
1 /*
2 This file is part of I am car.
3
4 I am car is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 I am car is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with I am car. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 #include <algorithm>
19 #include <cmath>
20 #include <omp.h>
21 #include <queue>
22 #include "bcar.h"
23 #include "rrtbase.h"
24
25 #if USE_GL > 0
26 // OpenGL
27 #include <GL/gl.h>
28 #include <GL/glu.h>
29 #include <SDL2/SDL.h>
30 #endif
31
32 // RRT
33 #include "cost.h"
34 #include "steer.h"
35
36 #if USE_GL > 0
37 extern SDL_Window* gw;
38 extern SDL_GLContext gc;
39 #endif
40
41 Cell::Cell()
42 {
43         pthread_mutex_init(&this->m_, NULL);
44 }
45
46 bool Cell::changed()
47 {
48         pthread_mutex_lock(&this->m_);
49         bool ret = this->changed_;
50         pthread_mutex_unlock(&this->m_);
51         return ret;
52 }
53
54 std::vector<RRTNode *> Cell::nodes()
55 {
56         pthread_mutex_lock(&this->m_);
57         std::vector<RRTNode *> ret(this->nodes_);
58         pthread_mutex_unlock(&this->m_);
59         return ret;
60 }
61
62 void Cell::add_node(RRTNode *n)
63 {
64         pthread_mutex_lock(&this->m_);
65         this->nodes_.push_back(n);
66         this->changed_ = true;
67         pthread_mutex_unlock(&this->m_);
68 }
69
70 RRTBase::~RRTBase()
71 {
72 // Fix heap-use-after-free error when T3 planner is used. If only T2 is used,
73 // please uncommend the following code:
74 //
75         for (auto n: this->nodes_)
76                 if (n != this->root_)
77                         delete n;
78         for (auto n: this->dnodes_)
79                 if (n != this->root_ && n != this->goal_)
80                         delete n;
81         for (auto s: this->samples_)
82                 if (s != this->goal_)
83                         delete s;
84         for (auto edges: this->rlog_)
85                 for (auto e: edges)
86                         delete e;
87         delete this->root_;
88         delete this->goal_;
89 }
90
91 RRTBase::RRTBase()
92         : root_(new RRTNode())
93         , goal_(new RRTNode())
94         , gen_(std::random_device{}())
95 {
96         this->nodes_.reserve(NOFNODES);
97         this->nodes_.push_back(this->root_);
98         this->add_iy(this->root_);
99         this->add_ixy(this->root_);
100         float hcenter = (this->HMAX - this->HMIN) / 2 + this->HMIN;
101         float hrange = (this->HMAX - this->HMIN) / 2;
102         float vcenter = (this->VMAX - this->VMIN) / 2 + this->VMIN;
103         float vrange = (this->VMAX - this->VMIN) / 2;
104         this->ndx_ = std::normal_distribution<float>(hcenter, hrange);
105         this->ndy_ = std::normal_distribution<float>(vcenter, vrange);
106         this->ndh_ = std::normal_distribution<float>(0, 2 * M_PI);
107 }
108
109 RRTBase::RRTBase(RRTNode *init, RRTNode *goal)
110         : root_(init)
111         , goal_(goal)
112         , gen_(std::random_device{}())
113 {
114         this->nodes_.reserve(NOFNODES);
115         this->nodes_.push_back(init);
116         this->add_iy(init);
117         this->add_ixy(init);
118         float hcenter = (this->HMAX - this->HMIN) / 2 + this->HMIN;
119         float hrange = (this->HMAX - this->HMIN) / 2;
120         float vcenter = (this->VMAX - this->VMIN) / 2 + this->VMIN;
121         float vrange = (this->VMAX - this->VMIN) / 2;
122         this->ndx_ = std::normal_distribution<float>(hcenter, hrange);
123         this->ndy_ = std::normal_distribution<float>(vcenter, vrange);
124         this->ndh_ = std::normal_distribution<float>(0, 2 * M_PI);
125 }
126
127 // getter
128 RRTNode *RRTBase::root()
129 {
130         return this->root_;
131 }
132
133 RRTNode *RRTBase::goal()
134 {
135         return this->goal_;
136 }
137
138 std::vector<RRTNode *> &RRTBase::goals()
139 {
140         return this->goals_;
141 }
142
143 std::vector<RRTNode *> &RRTBase::nodes()
144 {
145         return this->nodes_;
146 }
147
148 std::vector<RRTNode *> &RRTBase::dnodes()
149 {
150         return this->dnodes_;
151 }
152
153 std::queue<RRTNode *> &RRTBase::firsts()
154 {
155         return this->firsts_;
156 }
157
158 PolygonObstacle &RRTBase::frame()
159 {
160         return this->frame_;
161 }
162
163 std::vector<RRTNode *> &RRTBase::samples()
164 {
165         return this->samples_;
166 }
167
168 std::vector<CircleObstacle> *RRTBase::co()
169 {
170         return this->cobstacles_;
171 }
172
173 std::vector<SegmentObstacle> *RRTBase::so()
174 {
175         return this->sobstacles_;
176 }
177
178 std::vector<float> &RRTBase::clog()
179 {
180         return this->clog_;
181 }
182
183 std::vector<float> &RRTBase::nlog()
184 {
185         return this->nlog_;
186 }
187
188 std::vector<std::vector<RRTEdge *>> &RRTBase::rlog()
189 {
190         return this->rlog_;
191 }
192
193 std::vector<float> &RRTBase::slog()
194 {
195         return this->slog_;
196 }
197
198 std::vector<std::vector<RRTNode *>> &RRTBase::tlog()
199 {
200         return this->tlog_;
201 }
202
203 std::vector<RRTNode *> &RRTBase::slot_cusp()
204 {
205         return this->slot_cusp_;
206 }
207
208 bool RRTBase::goal_found()
209 {
210         return this->goal_found_;
211 }
212
213 float RRTBase::elapsed()
214 {
215         std::chrono::duration<float> dt;
216         dt = std::chrono::duration_cast<std::chrono::duration<float>>(
217                         this->tend_ - this->tstart_);
218         return dt.count();
219 }
220
221 std::vector<RRTNode *> RRTBase::traj_cusp()
222 {
223         std::vector<RRTNode *> tmp_cusps;
224         for (auto n: this->tlog().back()) {
225                 if (sgn(n->s()) == 0) {
226                         tmp_cusps.push_back(n);
227                 } else if (n->parent() &&
228                                 sgn(n->s()) != sgn(n->parent()->s())) {
229                         tmp_cusps.push_back(n);
230                         tmp_cusps.push_back(n->parent());
231                 }
232         }
233         std::vector<RRTNode *> cusps;
234         for (unsigned int i = 0; i < tmp_cusps.size(); i++) {
235                 if (tmp_cusps[i] != tmp_cusps[(i + 1) % tmp_cusps.size()])
236                         cusps.push_back(tmp_cusps[i]);
237         }
238         return cusps;
239 }
240
241 // setter
242 void RRTBase::root(RRTNode *node)
243 {
244         this->root_ = node;
245 }
246
247 void RRTBase::goal(RRTNode *node)
248 {
249         this->goal_ = node;
250 }
251
252 void RRTBase::goals(std::vector<RRTNode *> g)
253 {
254         this->goals_ = g;
255         std::reverse(this->goals_.begin(), this->goals_.end());
256         RRTNode *pn = this->goals_.front();
257         for (auto n: this->goals_) {
258                 if (n != pn) {
259                         pn->add_child(n, this->cost(pn ,n));
260                         pn = n;
261                 }
262         }
263 }
264
265 bool RRTBase::logr(RRTNode *root)
266 {
267         std::vector<RRTEdge *> e; // Edges to log
268         std::vector<RRTNode *> s; // DFS stack
269         std::vector<RRTNode *> r; // reset visited_
270         RRTNode *tmp;
271         s.push_back(root);
272         while (s.size() > 0) {
273                 tmp = s.back();
274                 s.pop_back();
275                 if (!tmp->visit()) {
276                         r.push_back(tmp);
277                         for (auto ch: tmp->children()) {
278                                 s.push_back(ch);
279                                 e.push_back(new RRTEdge(tmp, ch));
280                         }
281                 }
282         }
283         for (auto n: r)
284                 n->visit(false);
285         this->rlog_.push_back(e);
286         return true;
287 }
288
289 float RRTBase::ocost(RRTNode *n)
290 {
291         float dist = 9999;
292         for (auto o: *this->cobstacles_)
293                 if (o.dist_to(n) < dist)
294                         dist = o.dist_to(n);
295         for (auto o: *this->sobstacles_)
296                 if (o.dist_to(n) < dist)
297                         dist = o.dist_to(n);
298         return n->ocost(dist);
299 }
300
301 bool RRTBase::tlog(std::vector<RRTNode *> t)
302 {
303         if (t.size() > 0) {
304                 this->slog_.push_back(this->elapsed());
305                 this->clog_.push_back(t.front()->ccost() - t.back()->ccost());
306                 this->nlog_.push_back(this->nodes_.size());
307                 this->tlog_.push_back(t);
308                 return true;
309         } else {
310                 return false;
311         }
312 }
313
314 void RRTBase::tstart()
315 {
316         this->tstart_ = std::chrono::high_resolution_clock::now();
317 }
318
319 void RRTBase::tend()
320 {
321         this->tend_ = std::chrono::high_resolution_clock::now();
322 }
323
324 bool RRTBase::link_obstacles(
325                 std::vector<CircleObstacle> *cobstacles,
326                 std::vector<SegmentObstacle> *sobstacles)
327 {
328         this->cobstacles_ = cobstacles;
329         this->sobstacles_ = sobstacles;
330         if (!this->cobstacles_ || !this->sobstacles_) {
331                 return false;
332         }
333         return true;
334 }
335
336 bool RRTBase::add_iy(RRTNode *n)
337 {
338         int i = this->YI(n);
339         if (i < 0)
340                 i = 0;
341         if (i >= IYSIZE)
342                 i = IYSIZE - 1;
343         this->iy_[i].push_back(n);
344         return true;
345 }
346
347 bool RRTBase::add_ixy(RRTNode *n)
348 {
349         int ix = this->XI(n);
350         if (ix < 0)
351                 ix = 0;
352         if (ix >= IXSIZE)
353                 ix = IXSIZE - 1;
354         int iy = this->YI(n);
355         if (iy < 0)
356                 iy = 0;
357         if (iy >= IYSIZE)
358                 iy = IYSIZE - 1;
359         this->ixy_[ix][iy].add_node(n);
360         return true;
361 }
362
363 bool RRTBase::goal_found(bool f)
364 {
365         this->goal_found_ = f;
366         return f;
367 }
368
369 void RRTBase::slot_cusp(std::vector<RRTNode *> sc)
370 {
371         for (unsigned int i = 0; i < sc.size() - 1; i++)
372                 sc[i]->add_child(sc[i + 1], this->cost(sc[i], sc[i + 1]));
373         sc[0]->parent(this->goal());
374         this->slot_cusp_ = sc;
375 }
376
377 // other
378 bool RRTBase::glplot()
379 {
380 #if USE_GL > 0
381         float glplwscale = 1.0 / ((this->VMAX) - (this->VMIN));
382         float glplhscale = 1.0 / ((this->HMAX) - (this->HMIN));
383         glClear(GL_COLOR_BUFFER_BIT);
384         glLineWidth(1);
385         glPointSize(1);
386         // Plot obstacles
387         glBegin(GL_LINES);
388         for (auto o: *this->sobstacles_) {
389                 glColor3f(0, 0, 0);
390                 glVertex2f(GLVERTEX(o.init()));
391                 glVertex2f(GLVERTEX(o.goal()));
392         }
393         glEnd();
394         // Plot root, goal
395         glPointSize(8);
396         glBegin(GL_POINTS);
397         glColor3f(1, 0, 0);
398         glVertex2f(GLVERTEX(this->root_));
399         glVertex2f(GLVERTEX(this->goal_));
400         glEnd();
401         // Plot last sample
402         if (this->samples_.size() > 0) {
403                 glPointSize(8);
404                 glBegin(GL_POINTS);
405                 glColor3f(0, 1, 0);
406                 glVertex2f(GLVERTEX(this->samples_.back()));
407                 glEnd();
408         }
409         // Plot nodes (position, orientation
410         std::vector<RRTNode *> s; // DFS stack
411         std::vector<RRTNode *> r; // reset visited_
412         RRTNode *tmp;
413         glBegin(GL_LINES);
414         s.push_back(this->root_);
415         while (s.size() > 0) {
416                 tmp = s.back();
417                 s.pop_back();
418                 if (!tmp->visit()) {
419                         r.push_back(tmp);
420                         for (auto ch: tmp->children()) {
421                                 s.push_back(ch);
422                                 glColor3f(0.5, 0.5, 0.5);
423                                 BicycleCar bc(tmp->x(), tmp->y(), tmp->h());
424                                 glVertex2f(
425                                         bc.lfx() * glplwscale,
426                                         bc.lfy() * glplhscale
427                                 );
428                                 glVertex2f(
429                                         bc.lrx() * glplwscale,
430                                         bc.lry() * glplhscale
431                                 );
432                                 glVertex2f(
433                                         bc.lrx() * glplwscale,
434                                         bc.lry() * glplhscale
435                                 );
436                                 glVertex2f(
437                                         bc.rrx() * glplwscale,
438                                         bc.rry() * glplhscale
439                                 );
440                                 glVertex2f(
441                                         bc.rrx() * glplwscale,
442                                         bc.rry() * glplhscale
443                                 );
444                                 glVertex2f(
445                                         bc.rfx() * glplwscale,
446                                         bc.rfy() * glplhscale
447                                 );
448                         }
449                 }
450         }
451         glEnd();
452         // Plot nodes
453         glBegin(GL_LINES);
454         s.push_back(this->root_);
455         while (s.size() > 0) {
456                 tmp = s.back();
457                 s.pop_back();
458                 if (!tmp->visit()) {
459                         r.push_back(tmp);
460                         for (auto ch: tmp->children()) {
461                                 s.push_back(ch);
462                                 glColor3f(0.5, 0.5, 0.5);
463                                 glVertex2f(GLVERTEX(tmp));
464                                 glVertex2f(GLVERTEX(ch));
465                         }
466                 }
467         }
468         glEnd();
469         // Plot nodes (from goal)
470         glBegin(GL_LINES);
471         s.push_back(this->goal_);
472         while (s.size() > 0) {
473                 tmp = s.back();
474                 s.pop_back();
475                 if (!tmp->visit()) {
476                         r.push_back(tmp);
477                         for (auto ch: tmp->children()) {
478                                 s.push_back(ch);
479                                 glColor3f(0.5, 0.5, 0.5);
480                                 glVertex2f(GLVERTEX(tmp));
481                                 glVertex2f(GLVERTEX(ch));
482                         }
483                 }
484         }
485         glEnd();
486         std::vector<RRTNode *> cusps;
487         // Plot last trajectory
488         if (this->tlog().size() > 0) {
489                 glLineWidth(2);
490                 glBegin(GL_LINES);
491                 for (auto n: this->tlog().back()) {
492                         if (n->parent()) {
493                                 glColor3f(0, 0, 1);
494                                 glVertex2f(GLVERTEX(n));
495                                 glVertex2f(GLVERTEX(n->parent()));
496                                 if (sgn(n->s()) != sgn(n->parent()->s()))
497                                         cusps.push_back(n);
498                         }
499                 }
500                 glEnd();
501         }
502         // Plot cusps
503         glPointSize(8);
504         glBegin(GL_POINTS);
505         for (auto n: cusps) {
506                 glColor3f(0, 0, 1);
507                 glVertex2f(GLVERTEX(n));
508         }
509         glEnd();
510         SDL_GL_SwapWindow(gw);
511         for (auto n: r)
512                 n->visit(false);
513 #endif
514         return true;
515 }
516
517 bool RRTBase::goal_found(
518                 RRTNode *node,
519                 float (*cost)(RRTNode *, RRTNode* ))
520 {
521         if (GOAL_IS_NEAR(node, this->goal_)) {
522                 if (this->goal_found_) {
523                         if (node->ccost() + this->cost(node, this->goal_) <
524                                         this->goal_->ccost()) {
525                                 RRTNode *op; // old parent
526                                 float oc; // old cumulative cost
527                                 float od; // old direct cost
528                                 op = this->goal_->parent();
529                                 oc = this->goal_->ccost();
530                                 od = this->goal_->dcost();
531                                 node->add_child(this->goal_,
532                                                 this->cost(node, this->goal_));
533                                 if (this->collide(node, this->goal_)) {
534                                         node->children().pop_back();
535                                         this->goal_->parent(op);
536                                         this->goal_->ccost(oc);
537                                         this->goal_->dcost(od);
538                                 } else {
539                                         op->rem_child(this->goal_);
540                                         return true;
541                                 }
542                         } else {
543                                 return false;
544                         }
545                 } else {
546                         node->add_child(
547                                         this->goal_,
548                                         this->cost(node, this->goal_));
549                         if (this->collide(node, this->goal_)) {
550                                 node->children().pop_back();
551                                 this->goal_->remove_parent();
552                                 return false;
553                         }
554                         this->goal_found_ = true;
555                         // Update ccost of goal's parents
556                         if (this->goals().size() > 0) {
557                                 RRTNode *ch = this->goals().back();
558                                 RRTNode *pn = this->goals().back()->parent();
559                                 while (pn) {
560                                         pn->ccost(
561                                                 ch->ccost()
562                                                 - this->cost(pn, ch)
563                                         );
564                                         ch = pn;
565                                         pn = pn->parent();
566                                 }
567                         }
568                         return true;
569                 }
570         }
571         return false;
572 }
573
574 bool RRTBase::goal_found(
575         RRTNode *node,
576         RRTNode *goal
577 )
578 {
579         if (GOAL_IS_NEAR(node, goal)) {
580                 if (this->goal_found_) {
581                         if (
582                                 goal->ccost() != -1
583                                 && node->ccost() + this->cost(node, goal)
584                                 < goal->ccost()
585                         ) {
586                                 RRTNode *op; // old parent
587                                 float oc; // old cumulative cost
588                                 float od; // old direct cost
589                                 op = goal->parent();
590                                 oc = goal->ccost();
591                                 od = goal->dcost();
592                                 node->add_child(goal,
593                                                 this->cost(node, goal));
594                                 if (this->collide(node, goal)) {
595                                         node->children().pop_back();
596                                         goal->parent(op);
597                                         goal->ccost(oc);
598                                         goal->dcost(od);
599                                 } else {
600                                         op->rem_child(goal);
601                                         return true;
602                                 }
603                         } else {
604                                 return false;
605                         }
606                 } else {
607                         node->add_child(
608                                 goal,
609                                 this->cost(node, goal)
610                         );
611                         if (this->collide(node, goal)) {
612                                 node->children().pop_back();
613                                 goal->remove_parent();
614                                 return false;
615                         }
616                         this->goal_found_ = true;
617                         // Update ccost of goal's children
618                         goal->update_ccost();
619                         // Update ccost of goals
620                         for (auto g: this->goals()) {
621                                 if (g == goal)
622                                         break;
623                                 g->ccost(-1);
624                         }
625                         return true;
626                 }
627         }
628         return false;
629 }
630
631 bool RRTBase::collide(RRTNode *init, RRTNode *goal)
632 {
633         std::vector<RRTEdge *> edges;
634         RRTNode *tmp = goal;
635         volatile bool col = false;
636         unsigned int i;
637         while (tmp != init) {
638                 BicycleCar bc(tmp->x(), tmp->y(), tmp->h());
639                 std::vector<RRTEdge *> bcframe = bc.frame();
640                 #pragma omp parallel for reduction(|: col)
641                 for (i = 0; i < (*this->cobstacles_).size(); i++) {
642                         if ((*this->cobstacles_)[i].collide(tmp)) {
643                                 col = true;
644                         }
645                         for (auto &e: bcframe) {
646                                 if ((*this->cobstacles_)[i].collide(e)) {
647                                         col = true;
648                                 }
649                         }
650                 }
651                 if (col) {
652                         for (auto e: bcframe) {
653                                 delete e->init();
654                                 delete e->goal();
655                                 delete e;
656                         }
657                         for (auto e: edges) {
658                                 delete e;
659                         }
660                         return true;
661                 }
662                 #pragma omp parallel for reduction(|: col)
663                 for (i = 0; i < (*this->sobstacles_).size(); i++) {
664                         for (auto &e: bcframe) {
665                                 if ((*this->sobstacles_)[i].collide(e)) {
666                                         col = true;
667                                 }
668                         }
669                 }
670                 if (col) {
671                         for (auto e: bcframe) {
672                                 delete e->init();
673                                 delete e->goal();
674                                 delete e;
675                         }
676                         for (auto e: edges) {
677                                 delete e;
678                         }
679                         return true;
680                 }
681                 if (!tmp->parent()) {
682                         break;
683                 }
684                 edges.push_back(new RRTEdge(tmp, tmp->parent()));
685                 tmp = tmp->parent();
686                 for (auto e: bcframe) {
687                         delete e->init();
688                         delete e->goal();
689                         delete e;
690                 }
691         }
692         for (auto &e: edges) {
693                 #pragma omp parallel for reduction(|: col)
694                 for (i = 0; i < (*this->cobstacles_).size(); i++) {
695                         if ((*this->cobstacles_)[i].collide(e)) {
696                                 col = true;
697                         }
698                 }
699                 if (col) {
700                         for (auto e: edges) {
701                                 delete e;
702                         }
703                         return true;
704                 }
705                 #pragma omp parallel for reduction(|: col)
706                 for (i = 0; i < (*this->sobstacles_).size(); i++) {
707                         if ((*this->sobstacles_)[i].collide(e)) {
708                                 col = true;
709                         }
710                 }
711                 if (col) {
712                         for (auto e: edges) {
713                                 delete e;
714                         }
715                         return true;
716                 }
717         }
718         for (auto e: edges) {
719                 delete e;
720         }
721         return false;
722 }
723
724 class RRTNodeDijkstra {
725         public:
726                 RRTNodeDijkstra(int i):
727                         ni(i),
728                         pi(0),
729                         c(9999),
730                         v(false)
731                 {};
732                 RRTNodeDijkstra(int i, float c):
733                         ni(i),
734                         pi(0),
735                         c(c),
736                         v(false)
737                 {};
738                 RRTNodeDijkstra(int i, int p, float c):
739                         ni(i),
740                         pi(p),
741                         c(c),
742                         v(false)
743                 {};
744                 unsigned int ni;
745                 unsigned int pi;
746                 float c;
747                 bool v;
748                 bool vi()
749                 {
750                         if (this->v)
751                                 return true;
752                         this->v = true;
753                         return false;
754                 };
755 };
756
757 class RRTNodeDijkstraComparator {
758         public:
759                 int operator() (
760                                 const RRTNodeDijkstra& n1,
761                                 const RRTNodeDijkstra& n2)
762                 {
763                         return n1.c > n2.c;
764                 }
765 };
766
767 bool RRTBase::optp_dijkstra(
768                 std::vector<RRTNode *> &cusps,
769                 std::vector<int> &npi)
770 {
771         std::vector<RRTNodeDijkstra> dnodes;
772         for (unsigned int i = 0; i < cusps.size(); i++)
773                 if (i > 0)
774                         dnodes.push_back(RRTNodeDijkstra(
775                                                 i,
776                                                 i - 1,
777                                                 cusps[i]->ccost()));
778                 else
779                         dnodes.push_back(RRTNodeDijkstra(
780                                                 i,
781                                                 cusps[i]->ccost()));
782         dnodes[0].vi();
783         std::priority_queue<
784                 RRTNodeDijkstra,
785                 std::vector<RRTNodeDijkstra>,
786                 RRTNodeDijkstraComparator> pq;
787         RRTNodeDijkstra tmp = dnodes[0];
788         pq.push(tmp);
789         float ch_cost = 9999;
790         std::vector<RRTNode *> steered;
791         while (!pq.empty()) {
792                 tmp = pq.top();
793                 pq.pop();
794                 for (unsigned int i = tmp.ni + 1; i < cusps.size(); i++) {
795                         ch_cost = dnodes[tmp.ni].c +
796                                 this->cost(cusps[tmp.ni], cusps[i]);
797                         steered = this->steer(cusps[tmp.ni], cusps[i]);
798                         if (steered.size() <= 0)
799                                 break;
800                         for (unsigned int j = 0; j < steered.size() - 1; j++)
801                                 steered[j]->add_child(steered[j + 1], 1);
802                         if (this->collide(
803                                         steered[0],
804                                         steered[steered.size() - 1])) {
805                                 for (auto n: steered)
806                                         delete n;
807                                 continue;
808                         }
809                         if (ch_cost < dnodes[i].c) {
810                                 dnodes[i].c = ch_cost;
811                                 dnodes[i].pi = tmp.ni;
812                                 if (!dnodes[i].vi())
813                                         pq.push(dnodes[i]);
814                         }
815                         for (auto n: steered)
816                                 delete n;
817                 }
818         }
819         unsigned int tmpi = 0;
820         for (auto n: dnodes) {
821                 if (n.v && n.ni > tmpi)
822                         tmpi = n.ni;
823         }
824         while (tmpi > 0) {
825                 npi.push_back(tmpi);
826                 tmpi = dnodes[tmpi].pi;
827         }
828         npi.push_back(tmpi);
829         std::reverse(npi.begin(), npi.end());
830         return true;
831 }
832
833 bool RRTBase::optp_rrp(
834                 std::vector<RRTNode *> &cusps,
835                 std::vector<int> &npi)
836 {
837         std::vector<RRTNode *> steered;
838         std::vector<int> candidates;
839         RRTNode *x_j = nullptr;
840         RRTNode *x_i = nullptr;
841         int j = cusps.size() - 1;
842         int i_min = 0;
843         float c_min = 0;
844         float cost = 0;
845         float dx = 0;
846         float dy = 0;
847         float ed = 0;
848         float th_i = 0;
849         float th_j = 0;
850         while (j > 0) {
851                 npi.push_back(j);
852                 steered.clear();
853                 candidates.clear();
854                 x_j = cusps[j];
855                 for (int i = 0; i < j; i++) {
856                         steered = this->steer(cusps[i], x_j);
857                         for (unsigned int k = 0; k < steered.size() - 1; k++)
858                                 steered[k]->add_child(steered[k + 1], 1);
859                         if (!this->collide(
860                                         steered[0],
861                                         steered[steered.size() - 1]))
862                                 candidates.push_back(i);
863                 }
864                 if (candidates.size() <= 0)
865                         return false;
866                 i_min = candidates[0];
867                 x_i = cusps[i_min];
868                 c_min = 9999;
869                 for (auto c: candidates) {
870                         x_i = cusps[c];
871                         dx = x_j->x() - x_i->x();
872                         dy = x_j->y() - x_i->y();
873                         ed = EDIST(x_i, x_j);
874                         th_i = (cos(x_i->h()) * dx + sin(x_i->h()) * dy) / ed;
875                         th_j = (cos(x_j->h()) * dx + sin(x_j->h()) * dy) / ed;
876                         cost = th_i + th_j;
877                         if (cost < c_min) {
878                                 i_min = c;
879                                 c_min = cost;
880                         }
881                 }
882                 j = i_min;
883
884         }
885         npi.push_back(j);
886         std::reverse(npi.begin(), npi.end());
887         return true;
888 }
889
890 bool RRTBase::optp_smart(
891                 std::vector<RRTNode *> &cusps,
892                 std::vector<int> &npi)
893 {
894         std::vector<RRTNode *> steered;
895         int li = cusps.size() - 1;
896         int ai = li - 1;
897         npi.push_back(li);
898         while (ai > 1) {
899                 steered = this->steer(cusps[ai - 1], cusps[li]);
900                 for (unsigned int j = 0; j < steered.size() - 1; j++)
901                         steered[j]->add_child(steered[j + 1], 1);
902                 if (this->collide(steered[0], steered[steered.size() - 1])) {
903                         npi.push_back(ai);
904                         li = ai;
905                 }
906                 ai--;
907                 for (auto n: steered)
908                         delete n;
909         }
910         npi.push_back(0);
911         std::reverse(npi.begin(), npi.end());
912         return true;
913 }
914
915 bool RRTBase::opt_path()
916 {
917         if (this->tlog().size() == 0)
918                 return false;
919         float oc = this->tlog().back().front()->ccost();
920         std::vector<RRTNode *> tmp_cusps;
921         for (auto n: this->tlog().back()) {
922                 if (sgn(n->s()) == 0) {
923                         tmp_cusps.push_back(n);
924                 } else if (n->parent() &&
925                                 sgn(n->s()) != sgn(n->parent()->s())) {
926                         tmp_cusps.push_back(n);
927                         tmp_cusps.push_back(n->parent());
928                 }
929                 //tmp_cusps.push_back(n);
930         }
931         if (tmp_cusps.size() < 2)
932                 return false;
933         std::vector<RRTNode *> cusps;
934         for (unsigned int i = 0; i < tmp_cusps.size(); i++) {
935                 if (!IS_NEAR(
936                         tmp_cusps[i],
937                         tmp_cusps[(i + 1) % tmp_cusps.size()]
938                 ))
939                         cusps.push_back(tmp_cusps[i]);
940         }
941         std::reverse(cusps.begin(), cusps.end());
942         std::vector<int> npi; // new path indexes
943         if (!this->optp_dijkstra(cusps, npi))
944                 return false;
945         RRTNode *pn = cusps[npi[0]];
946         RRTNode *tmp = nullptr;
947         bool en_add = true;
948         for (unsigned int i = 0; i < npi.size() - 1; i++) {
949                 pn = cusps[npi[i]];
950                 for (auto ns: this->steer(cusps[npi[i]], cusps[npi[i + 1]])) {
951                         if (!en_add) {
952                                 delete ns;
953                         } else if (IS_NEAR(cusps[npi[i]], ns)) {
954                                 tmp = ns;
955                                 while (tmp && tmp != cusps[npi[i]]) {
956                                         pn = tmp->parent();
957                                         delete tmp;
958                                         tmp = pn;
959                                 }
960                                 pn = cusps[npi[i]];
961                         } else if (IS_NEAR(ns, cusps[npi[i + 1]])) {
962                                 delete ns;
963                                 cusps[npi[i + 1]]->parent()->rem_child(
964                                                 cusps[npi[i + 1]]);
965                                 pn->add_child(
966                                         cusps[npi[i + 1]],
967                                         this->cost(pn, cusps[npi[i + 1]]));
968                                 en_add = false;
969                         } else if (IS_NEAR(pn, ns)) {
970                                 delete ns;
971                         } else {
972                                 this->nodes().push_back(ns);
973                                 this->add_iy(ns);
974                                 this->add_ixy(ns);
975                                 pn->add_child(ns, this->cost(pn, ns));
976                                 pn = ns;
977                         }
978                 }
979         }
980         this->root()->update_ccost();
981         if (this->tlog().back().front()->ccost() < oc)
982                 return true;
983         return false;
984 }
985
986 bool RRTBase::rebase(RRTNode *nr)
987 {
988         if (!nr || this->goal_ == nr || this->root_ == nr)
989                 return false;
990         std::vector<RRTNode *> s; // DFS stack
991         RRTNode *tmp;
992         unsigned int i = 0;
993         unsigned int to_del = 0;
994         int iy = 0;
995         s.push_back(this->root_);
996         while (s.size() > 0) {
997                 tmp = s.back();
998                 s.pop_back();
999                 for (auto ch: tmp->children()) {
1000                         if (ch != nr)
1001                                 s.push_back(ch);
1002                 }
1003                 to_del = this->nodes_.size();
1004                 #pragma omp parallel for reduction(min: to_del)
1005                 for (i = 0; i < this->nodes_.size(); i++) {
1006                         if (this->nodes_[i] == tmp)
1007                                 to_del = i;
1008                 }
1009                 if (to_del < this->nodes_.size())
1010                         this->nodes_.erase(this->nodes_.begin() + to_del);
1011                 iy = this->YI(tmp);
1012                 to_del = this->iy_[iy].size();
1013                 #pragma omp parallel  for reduction(min: to_del)
1014                 for (i = 0; i < this->iy_[iy].size(); i++) {
1015                         if (this->iy_[iy][i] == tmp)
1016                                 to_del = i;
1017                 }
1018                 if (to_del < this->iy_[iy].size())
1019                         this->iy_[iy].erase(this->iy_[iy].begin() + to_del);
1020                 this->dnodes().push_back(tmp);
1021         }
1022         this->root_ = nr;
1023         this->root_->remove_parent();
1024         return true;
1025 }
1026
1027 std::vector<RRTNode *> RRTBase::findt()
1028 {
1029         return this->findt(this->goal_);
1030 }
1031
1032 std::vector<RRTNode *> RRTBase::findt(RRTNode *n)
1033 {
1034         std::vector<RRTNode *> nodes;
1035         if (!n || !n->parent())
1036                 return nodes;
1037         while (n) {
1038                 nodes.push_back(n);
1039                 n = n->parent();
1040         }
1041         return nodes;
1042 }
1043
1044 int RRTBase::XI(RRTNode *n)
1045 {
1046         float step = (this->HMAX - this->HMIN) / IXSIZE;
1047         float index = (int) (floor(n->x() - this->HMIN) / step);
1048         if (index < 0) index = 0;
1049         if (index >= IXSIZE) index = IXSIZE - 1;
1050         return index;
1051 }
1052
1053 int RRTBase::YI(RRTNode *n)
1054 {
1055         float step = (this->VMAX - this->VMIN) / IYSIZE;
1056         float index = (int) (floor(n->y() - this->VMIN) / step);
1057         if (index < 0) index = 0;
1058         if (index >= IYSIZE) index = IYSIZE - 1;
1059         return index;
1060 }
1061
1062 // RRT Framework
1063 void RRTBase::defaultSamplingInfo()
1064 {
1065         float hcenter = (this->HMAX - this->HMIN) / 2 + this->HMIN;
1066         float hrange = (this->HMAX - this->HMIN) / 2;
1067         float vcenter = (this->VMAX - this->VMIN) / 2 + this->VMIN;
1068         float vrange = (this->VMAX - this->VMIN) / 2;
1069         this->ndx_ = std::normal_distribution<float>(hcenter, hrange);
1070         this->ndy_ = std::normal_distribution<float>(vcenter, vrange);
1071         this->ndh_ = std::normal_distribution<float>(0, 2 * M_PI);
1072 }
1073
1074 void RRTBase::setSamplingInfo(SamplingInfo si)
1075 {
1076         this->ndx_ = std::normal_distribution<float>(si.x0, si.x);
1077         this->ndy_ = std::normal_distribution<float>(si.y0, si.y);
1078         this->ndh_ = std::normal_distribution<float>(si.h0, si.h);
1079 }
1080
1081 RRTNode *RRTBase::sample()
1082 {
1083         float x = this->ndx_(this->gen_);
1084         float y = this->ndy_(this->gen_);
1085         float h = this->ndh_(this->gen_);
1086         return new RRTNode(x, y, h);
1087 }
1088
1089 float RRTBase::cost(RRTNode *init, RRTNode *goal)
1090 {
1091         return co2(init, goal);
1092 }
1093
1094 RRTNode *RRTBase::nn(RRTNode *rs)
1095 {
1096         int iy = this->YI(rs);
1097         float iy_step = (this->VMAX - this->VMIN) / IYSIZE;
1098         struct mcnn nn;
1099         nn.nn = nullptr;
1100         nn.mc = 9999;
1101         unsigned int i = 0; // vector step
1102         unsigned int j = 0; // array step
1103         int iyj = 0;
1104         while (nn.mc > j * iy_step) {
1105                 iyj = (int) (iy + j);
1106                 if (iyj >= IYSIZE)
1107                         iyj = IYSIZE - 1;
1108                 #pragma omp parallel for reduction(minn: nn)
1109                 for (i = 0; i < this->iy_[iyj].size(); i++) {
1110                         if (EDIST(this->iy_[iyj][i], rs) < nn.mc) {
1111                                 nn.mc = EDIST(this->iy_[iyj][i], rs);
1112                                 nn.nn = this->iy_[iyj][i];
1113                         }
1114                 }
1115                 if (j > 0) {
1116                         iyj = (int) (iy - j);
1117                         if (iyj < 0)
1118                                 iyj = 0;
1119                         #pragma omp parallel for reduction(minn: nn)
1120                         for (i = 0; i < this->iy_[iyj].size(); i++) {
1121                                 if (EDIST(this->iy_[iyj][i], rs) < nn.mc) {
1122                                         nn.mc = EDIST(this->iy_[iyj][i], rs);
1123                                         nn.nn = this->iy_[iyj][i];
1124                                 }
1125                         }
1126                 }
1127                 j++;
1128         }
1129         return nn.nn;
1130 }
1131
1132 std::vector<RRTNode *> RRTBase::nv(RRTNode *node, float dist)
1133 {
1134         std::vector<RRTNode *> nvs;
1135         unsigned int iy = this->YI(node);
1136         float iy_step = (this->VMAX - this->VMIN) / IYSIZE;
1137         unsigned int iy_dist = floor(dist / iy_step) + 1;
1138         unsigned int i = 0; // vector index
1139         unsigned int j = 0; // array index
1140         unsigned int jmin = 0; // minimal j index
1141         unsigned int jmax = 0; // maximal j index
1142         jmin = iy - iy_dist;
1143         jmin = (jmin > 0) ? jmin : 0;
1144         jmax = iy + iy_dist + 1;
1145         jmax = (jmax < IYSIZE) ? jmax : IYSIZE;
1146         #pragma omp parallel for reduction(merge: nvs)
1147         for (j = jmin; j < jmax; j++) {
1148                 #pragma omp parallel for reduction(merge: nvs)
1149                 for (i = 0; i < this->iy_[j].size(); i++) {
1150                         if (this->cost(this->iy_[j][i], node) < dist) {
1151                                 nvs.push_back(this->iy_[j][i]);
1152                         }
1153                 }
1154         }
1155         return nvs;
1156 }
1157
1158 std::vector<RRTNode *> RRTBase::steer(RRTNode *init, RRTNode *goal)
1159 {
1160         return st3(init, goal);
1161 }
1162
1163 std::vector<RRTNode *> RRTBase::steer(RRTNode *init, RRTNode *goal, float step)
1164 {
1165         return st3(init, goal, step);
1166 }