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