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