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