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