]> rtime.felk.cvut.cz Git - hubacji1/rrts.git/blob - src/rrts.cc
Add deinit methods
[hubacji1/rrts.git] / src / rrts.cc
1 #include <algorithm>
2 #include "rrts.h"
3
4 #include "reeds_shepp.h"
5
6 template <typename T> int sgn(T val) {
7         return (T(0) < val) - (val < T(0));
8 }
9
10 RRTNode::RRTNode()
11 {
12 }
13
14 RRTNode::RRTNode(const BicycleCar &bc) : BicycleCar(bc)
15 {
16 }
17
18 Obstacle::Obstacle()
19 {
20 }
21
22 double RRTS::elapsed()
23 {
24         std::chrono::duration<double> dt;
25         dt = std::chrono::duration_cast<std::chrono::duration<double>>(
26                 std::chrono::high_resolution_clock::now()
27                 - this->tstart_
28         );
29         this->scnt_ = dt.count();
30         return this->scnt_;
31 }
32
33 bool RRTS::should_stop()
34 {
35         // the following counters must be updated, do not comment
36         this->icnt_++;
37         this->elapsed();
38         // decide the stop conditions (maybe comment some lines)
39         if (this->icnt_ > 999) return true;
40         if (this->scnt_ > 10) return true;
41         if (this->gf()) return true;
42         //if (this->scnt_ - this->pcnt_ > 1) return true;
43         // but continue by default
44         return false;
45 }
46
47 bool RRTS::should_continue()
48 {
49         // decide the stop conditions (maybe comment some lines)
50         // it is exact opposite of `should_stop`
51         //if (this->icnt_ > 999) return false;
52         if (this->scnt_ > 10) return false;
53         if (this->gf()) return false;
54         // and reset pause counter if should continue
55         this->pcnt_ = this->scnt_;
56         return true;
57 }
58
59 void RRTS::store_node(RRTNode n)
60 {
61         this->nodes().push_back(n);
62 }
63
64 // RRT procedures
65 std::tuple<bool, unsigned int, unsigned int>
66 RRTS::collide(std::vector<std::tuple<double, double>> &poly)
67 {
68         for (auto &o: this->obstacles())
69                 if (std::get<0>(::collide(poly, o.poly())))
70                         return ::collide(poly, o.poly());
71         return std::make_tuple(false, 0, 0);
72 }
73
74 std::tuple<bool, unsigned int, unsigned int>
75 RRTS::collide_steered_from(RRTNode &f)
76 {
77         std::vector<std::tuple<double, double>> s;
78         s.push_back(std::make_tuple(f.x(), f.y()));
79         for (auto &n: this->steered()) {
80                 s.push_back(std::make_tuple(n.lfx(), n.lfy()));
81                 s.push_back(std::make_tuple(n.lrx(), n.lry()));
82                 s.push_back(std::make_tuple(n.rrx(), n.rry()));
83                 s.push_back(std::make_tuple(n.rfx(), n.rfy()));
84         }
85         auto col = this->collide(s);
86         auto strip_from = this->steered().size() - std::get<1>(col) / 4;
87         if (std::get<0>(col) && strip_from > 0) {
88                 while (strip_from-- > 0) {
89                         this->steered().pop_back();
90                 }
91                 return this->collide_steered_from(f);
92         }
93         return col;
94 }
95
96 std::tuple<bool, unsigned int, unsigned int>
97 RRTS::collide_two_nodes(RRTNode &f, RRTNode &t)
98 {
99         std::vector<std::tuple<double, double>> p;
100         p.push_back(std::make_tuple(f.lfx(), f.lfy()));
101         p.push_back(std::make_tuple(f.lrx(), f.lry()));
102         p.push_back(std::make_tuple(f.rrx(), f.rry()));
103         p.push_back(std::make_tuple(f.rfx(), f.rfy()));
104         p.push_back(std::make_tuple(t.lfx(), t.lfy()));
105         p.push_back(std::make_tuple(t.lrx(), t.lry()));
106         p.push_back(std::make_tuple(t.rrx(), t.rry()));
107         p.push_back(std::make_tuple(t.rfx(), t.rfy()));
108         return this->collide(p);
109 }
110
111 double RRTS::cost_build(RRTNode &f, RRTNode &t)
112 {
113         double cost = 0;
114         cost = sqrt(pow(t.y() - f.y(), 2) + pow(t.x() - f.x(), 2));
115         return cost;
116 }
117
118 double RRTS::cost_search(RRTNode &f, RRTNode &t)
119 {
120         double cost = 0;
121         cost = sqrt(pow(t.y() - f.y(), 2) + pow(t.x() - f.x(), 2));
122         return cost;
123 }
124
125 void RRTS::sample()
126 {
127         double x = this->ndx_(this->gen_);
128         double y = this->ndy_(this->gen_);
129         double h = this->ndh_(this->gen_);
130         this->samples().push_back(RRTNode());
131         this->samples().back().x(x);
132         this->samples().back().y(y);
133         this->samples().back().h(h);
134 }
135
136 RRTNode *RRTS::nn(RRTNode &t)
137 {
138         RRTNode *nn = &this->nodes().front();
139         double cost = this->cost_search(*nn, t);
140         for (auto &f: this->nodes()) {
141                 if (this->cost_search(f, t) < cost) {
142                         nn = &f;
143                         cost = this->cost_search(f, t);
144                 }
145         }
146         return nn;
147 }
148
149 std::vector<RRTNode *> RRTS::nv(RRTNode &t)
150 {
151         std::vector<RRTNode *> nv;
152         double cost = std::min(GAMMA(this->nodes().size()), ETA);
153         for (auto &f: this->nodes())
154                 if (this->cost_search(f, t) < cost)
155                         nv.push_back(&f);
156         return nv;
157 }
158
159 int cb_rs_steer(double q[4], void *user_data)
160 {
161         std::vector<RRTNode> *nodes = (std::vector<RRTNode> *) user_data;
162         RRTNode *ln = nullptr;
163         if (nodes->size() > 0)
164                 ln = &nodes->back();
165         nodes->push_back(RRTNode());
166         nodes->back().x(q[0]);
167         nodes->back().y(q[1]);
168         nodes->back().h(q[2]);
169         nodes->back().sp(q[3]);
170         if (nodes->back().sp() == 0)
171                 nodes->back().set_t(RRTNodeType::cusp);
172         else if (ln != nullptr && sgn(ln->sp()) != sgn(nodes->back().sp()))
173                 ln->set_t(RRTNodeType::cusp);
174         return 0;
175 }
176
177 void RRTS::steer(RRTNode &f, RRTNode &t)
178 {
179         this->steered().clear();
180         double q0[] = {f.x(), f.y(), f.h()};
181         double q1[] = {t.x(), t.y(), t.h()};
182         ReedsSheppStateSpace rsss(f.mtr());
183         rsss.sample(q0, q1, 0.5, cb_rs_steer, &this->steered());
184 }
185
186 void RRTS::join_steered(RRTNode *f)
187 {
188         while (this->steered().size() > 0) {
189                 this->store_node(this->steered().front());
190                 RRTNode *t = &this->nodes().back();
191                 t->p(f);
192                 t->c(this->cost_build(*f, *t));
193                 this->steered().erase(this->steered().begin());
194                 f = t;
195         }
196 }
197
198 bool RRTS::goal_found(RRTNode &f)
199 {
200         bool found = false;
201         for (auto &g: this->goals()) {
202                 double cost = this->cost_build(f, g);
203                 double edist = sqrt(
204                         pow(f.x() - g.x(), 2)
205                         + pow(f.y() - g.y(), 2)
206                 );
207                 double adist = std::abs(f.h() - g.h());
208                 if (edist < 0.05 && adist < M_PI / 32) {
209                         found = true;
210                         if (g.p() == nullptr || cc(f) + cost < cc(g)) {
211                                 g.p(&f);
212                                 g.c(cost);
213                         }
214                 }
215         }
216         return found;
217 }
218
219 // RRT* procedures
220 bool RRTS::connect()
221 {
222         RRTNode *t = &this->steered().front();
223         RRTNode *f = this->nn(this->samples().back());
224         double cost = this->cost_search(*f, *t);
225         for (auto n: this->nv(*t)) {
226                 if (
227                         !std::get<0>(this->collide_two_nodes(*n, *t))
228                         && this->cost_search(*n, *t) < cost
229                 ) {
230                         f = n;
231                         cost = this->cost_search(*n, *t);
232                 }
233         }
234         this->store_node(this->steered().front());
235         t = &this->nodes().back();
236         t->p(f);
237         t->c(this->cost_build(*f, *t));
238         t->set_t(RRTNodeType::connected);
239         return true;
240 }
241
242 void RRTS::rewire()
243 {
244         RRTNode *f = &this->nodes().back();
245         for (auto n: this->nv(*f)) {
246                 if (
247                         !std::get<0>(this->collide_two_nodes(*f, *n))
248                         && cc(*f) + this->cost_search(*f, *n) < cc(*n)
249                 ) {
250                         n->p(f);
251                         n->c(this->cost_build(*f, *n));
252                 }
253         }
254 }
255
256 // API
257 void RRTS::init()
258 {
259 }
260
261 void RRTS::deinit()
262 {
263         this->nodes().clear();
264         this->samples().clear();
265         this->steered().clear();
266         this->store_node(RRTNode()); // root
267         this->icnt_ = 0;
268         this->scnt_ = 0;
269         this->pcnt_ = 0;
270         this->gf_ = false;
271 }
272
273 std::vector<RRTNode *> RRTS::path()
274 {
275         std::vector<RRTNode *> path;
276         if (this->goals().size() == 0)
277                 return path;
278         RRTNode *goal = &this->goals().front();
279         for (auto &n: this->goals()) {
280                 if (
281                         n.p() != nullptr
282                         && (n.c() < goal->c() || goal->p() == nullptr)
283                 ) {
284                         goal = &n;
285                 }
286         }
287         if (goal->p() == nullptr)
288                 return path;
289         while (goal != nullptr) {
290                 path.push_back(goal);
291                 goal = goal->p();
292         }
293         std::reverse(path.begin(), path.end());
294         return path;
295 }
296
297 bool RRTS::next()
298 {
299         if (this->icnt_ == 0)
300                 this->tstart_ = std::chrono::high_resolution_clock::now();
301         bool next = true;
302         if (this->should_stop())
303                 return false;
304         this->sample();
305         this->steer(
306                 *this->nn(this->samples().back()),
307                 this->samples().back()
308         );
309         if (std::get<0>(this->collide_steered_from(
310                 *this->nn(this->samples().back())
311         )))
312                 return next;
313         if (!this->connect())
314                 return next;
315         this->rewire();
316         unsigned scnt = this->steered().size();
317         this->steered().erase(this->steered().begin());
318         this->join_steered(&this->nodes().back());
319         RRTNode *just_added = &this->nodes().back();
320         while (scnt > 0) {
321                 scnt--;
322                 for (auto &g: this->goals()) {
323                         this->steer(*just_added, g);
324                         if (std::get<0>(this->collide_steered_from(
325                                 *just_added
326                         )))
327                                 continue;
328                         this->join_steered(just_added);
329                 }
330                 this->gf(this->goal_found(this->nodes().back()));
331                 just_added = just_added->p();
332         }
333         return next;
334 }
335
336 void RRTS::set_sample(
337         double mx, double dx,
338         double my, double dy,
339         double mh, double dh
340 )
341 {
342         this->ndx_ = std::normal_distribution<double>(mx, dx);
343         this->ndy_ = std::normal_distribution<double>(my, dy);
344         this->ndh_ = std::normal_distribution<double>(mh, dh);
345 }
346
347 Json::Value RRTS::json()
348 {
349         Json::Value jvo;
350         {
351                 jvo["time"] = this->scnt();
352         }
353         {
354                 jvo["iterations"] = this->icnt();
355         }
356         {
357                 jvo["init"][0] = this->nodes().front().x();
358                 jvo["init"][1] = this->nodes().front().y();
359                 jvo["init"][2] = this->nodes().front().h();
360         }
361         {
362                 if (this->path().size() > 0) {
363                         jvo["cost"] = cc(*this->path().back());
364                         jvo["goal"][0] = this->path().back()->x();
365                         jvo["goal"][1] = this->path().back()->y();
366                         jvo["goal"][2] = this->path().back()->h();
367                 }
368         }
369         {
370                 unsigned int cu = 0;
371                 unsigned int co = 0;
372                 unsigned int pcnt = 0;
373                 for (auto n: this->path()) {
374                         jvo["path"][pcnt][0] = n->x();
375                         jvo["path"][pcnt][1] = n->y();
376                         jvo["path"][pcnt][2] = n->h();
377                         if (n->t(RRTNodeType::cusp))
378                                 cu++;
379                         if (n->t(RRTNodeType::connected))
380                                 co++;
381                         pcnt++;
382                 }
383                 jvo["cusps-in-path"] = cu;
384                 jvo["connecteds-in-path"] = co;
385         }
386         {
387                 unsigned int gcnt = 0;
388                 for (auto g: this->goals()) {
389                         jvo["goals"][gcnt][0] = g.x();
390                         jvo["goals"][gcnt][1] = g.y();
391                         jvo["goals"][gcnt][2] = g.h();
392                         gcnt++;
393                 }
394         }
395         {
396                 unsigned int ocnt = 0;
397                 for (auto o: this->obstacles()) {
398                         unsigned int ccnt = 0;
399                         for (auto c: o.poly()) {
400                                 jvo["obst"][ocnt][ccnt][0] = std::get<0>(c);
401                                 jvo["obst"][ocnt][ccnt][1] = std::get<1>(c);
402                                 ccnt++;
403                         }
404                         ocnt++;
405                 }
406         }
407         {
408                 jvo["nodes"] = (unsigned int) this->nodes().size();
409         }
410         //{
411         //        unsigned int ncnt = 0;
412         //        for (auto n: this->nodes()) {
413         //                jvo["nodes_x"][ncnt] = n.x();
414         //                jvo["nodes_y"][ncnt] = n.y();
415         //                //jvo["nodes_h"][ncnt] = n.h();
416         //                ncnt++;
417         //        }
418         //}
419         return jvo;
420 }
421
422 RRTS::RRTS()
423         : gen_(std::random_device{}())
424 {
425         this->goals().reserve(100);
426         this->nodes().reserve(4000000);
427         this->samples().reserve(1000);
428         this->steered().reserve(20000);
429         this->store_node(RRTNode()); // root
430 }
431
432 double cc(RRTNode &t)
433 {
434         RRTNode *n = &t;
435         double cost = 0;
436         while (n != nullptr) {
437                 cost += n->c();
438                 n = n->p();
439         }
440         return cost;
441 }