]> rtime.felk.cvut.cz Git - hubacji1/iamcar.git/blob - base/main.cc
Use T2 planner
[hubacji1/iamcar.git] / base / main.cc
1 /*
2 This file is part of I am car.
3
4 I am car is nree 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 <chrono>
20 #include <iostream>
21 #include <jsoncpp/json/json.h>
22 #include <pthread.h>
23 #include <signal.h>
24 #include <unistd.h>
25 #include "compile.h"
26 #include "obstacle.h"
27 #include "rrtplanner.h"
28 #include "slotplanner.h"
29 // OpenGL
30 #include <GL/gl.h>
31 #include <GL/glu.h>
32 #include <SDL2/SDL.h>
33
34 // debug
35 //#define JSONLOGEDGES
36 //#define JSONLOGSAMPLES
37
38 // choose
39 //#define USE_INTERRUPT
40 // or
41 #define USE_TMAX
42 // or
43 //#define USE_LOADF
44 // or
45 //#define USE_PTHREAD
46
47 // enable
48 //#define USE_SLOTPLANNER
49
50 // enable
51 //#define USE_SLOTPLANNER
52
53 #ifdef USE_INTERRUPT
54         #define USE_GL
55 #endif
56
57 std::chrono::high_resolution_clock::time_point TSTART_;
58 std::chrono::high_resolution_clock::time_point TEND_;
59 float TELAPSED = 0;
60 float ELAPSED = 0;
61 void TSTART() {TSTART_ = std::chrono::high_resolution_clock::now();}
62 void TEND() {
63         std::chrono::duration<float> DT_;
64         TEND_ = std::chrono::high_resolution_clock::now();
65         DT_ = std::chrono::duration_cast<std::chrono::duration<float>>(
66                 TEND_ - TSTART_
67         );
68         TELAPSED += DT_.count();
69         ELAPSED = DT_.count();
70 }
71 void TPRINT(const char *what) {
72         std::chrono::duration<float> DT_;
73         DT_ = std::chrono::duration_cast<std::chrono::duration<float>>(
74                 TEND_ - TSTART_
75         );
76         std::cerr << what << ": " << DT_.count() << std::endl;
77 }
78
79 bool run_planner = true;
80
81 SDL_Window* gw = NULL;
82 SDL_GLContext gc;
83
84 bool init();
85 bool initGL();
86
87 void hint(int)
88 {
89         run_planner = false;
90 }
91
92 #ifdef USE_PTHREAD
93 struct next_arg {
94         bool *gf;
95         T2 *p;
96 };
97
98 void *next_run(void *arg)
99 {
100         struct next_arg *na = (struct next_arg *) arg;
101         T2 *lp = (T2 *) na->p;
102         bool *gf = na->gf;
103         while (!*gf && lp->elapsed() < TMAX) {
104                 if (lp->next())
105                         *gf = true;
106                 lp->tend();
107         }
108         pthread_exit(NULL);
109         return NULL;
110 }
111 #endif
112
113 int main()
114 {
115 #ifdef USE_GL
116         init();
117 #endif
118
119         Json::Value jvi; // JSON input
120         Json::Value jvo; // JSON output
121         unsigned int i = 0;
122         unsigned int j = 0;
123         std::cin >> jvi;
124         std::string encoding = jvi.get("encoding", "UTF-8" ).asString();
125
126         PLANNER p(
127                         new RRTNode(
128                                 jvi["init"][0].asFloat(),
129                                 jvi["init"][1].asFloat(),
130                                 jvi["init"][2].asFloat()),
131                         new RRTNode(
132                                 jvi["goal"][0].asFloat(),
133                                 jvi["goal"][1].asFloat(),
134                                 jvi["goal"][2].asFloat()));
135         std::vector<CircleObstacle> co;
136         std::vector<SegmentObstacle> so;
137         for (auto o: jvi["obst"]) {
138                 if (o["circle"] != Json::nullValue) {
139                         co.push_back(CircleObstacle(
140                                                 o["circle"][0].asFloat(),
141                                                 o["circle"][1].asFloat(),
142                                                 o["circle"][2].asFloat()));
143                 }
144                 if (o["segment"] != Json::nullValue) {
145                         so.push_back(SegmentObstacle(
146                                 new RRTNode(
147                                         o["segment"][0][0].asFloat(),
148                                         o["segment"][0][1].asFloat(),
149                                         0),
150                                 new RRTNode(
151                                         o["segment"][1][0].asFloat(),
152                                         o["segment"][1][1].asFloat(),
153                                         0)));
154                         p.frame().add_bnode(so.back().init());
155                 }
156         }
157         p.link_obstacles(&co, &so);
158         p.ocost(p.root());
159         p.ocost(p.goal());
160
161         ParallelSlot ps = ParallelSlot();
162 #ifdef USE_SLOTPLANNER
163         TSTART();
164         for (auto xy: jvi["slot"]["polygon"]) {
165                 ps.slot().add_bnode(new RRTNode(
166                         xy[0].asFloat(),
167                         xy[1].asFloat()
168                 ));
169         }
170         if (ps.slot().bnodes().size() > 0)
171                 ps.fpose();
172         TEND();
173         jvo["ppse"] = ELAPSED;
174         TPRINT("ParallelSlot");
175 #endif
176         if (ps.cusp().size() > 0) {
177                 p.goal(ps.cusp().front().front());
178                 p.slot_cusp(ps.cusp().front()); // use first found solution
179                 jvo["midd"][0] = p.goal()->x();
180                 jvo["midd"][1] = p.goal()->y();
181                 jvo["midd"][2] = p.goal()->h();
182                 jvo["goal"][0] = p.slot_cusp().back()->x();
183                 jvo["goal"][1] = p.slot_cusp().back()->y();
184                 jvo["goal"][2] = p.slot_cusp().back()->h();
185         } else {
186                 jvo["goal"][0] = p.goal()->x();
187                 jvo["goal"][1] = p.goal()->y();
188                 jvo["goal"][2] = p.goal()->h();
189         }
190         TSTART();
191 #ifdef USE_LOADF
192         std::vector<RRTNode *> steered;
193         for (auto jn: jvi["traj"][0]) {
194                 steered.push_back(new RRTNode(
195                                         jn[0].asFloat(),
196                                         jn[1].asFloat(),
197                                         jn[2].asFloat(),
198                                         jn[3].asFloat(),
199                                         jn[4].asFloat()));
200         }
201         std::reverse(steered.begin(), steered.end());
202         RRTNode *pn = p.root();
203         for (auto n: steered) {
204                 if (IS_NEAR(pn, n))
205                         continue;
206                 pn->add_child(n, p.cost(pn, n));
207                 pn = n;
208                 p.glplot();
209         }
210         pn->add_child(p.goal(), p.cost(pn, p.goal()));
211         p.goal_found(true);
212         p.tlog(p.findt());
213         if (p.opt_path()) {
214                 p.tlog(p.findt());
215                 p.glplot();
216         }
217         p.glplot();
218         sleep(2);
219 #elif defined USE_INTERRUPT
220         signal(SIGINT, hint);
221         signal(SIGTERM, hint);
222         p.tstart();
223         while (run_planner) {
224                 p.next();
225                 p.tend();
226                 if (p.opt_path())
227                         p.tlog(p.findt());
228                 p.glplot();
229         }
230 #elif defined USE_TMAX
231         p.tstart();
232         p.tend();
233         while (!p.goal_found() && p.elapsed() < TMAX) {
234                 p.next();
235                 p.tend();
236                 if (p.opt_path()) {
237                         if (ps.cusp().size() > 0)
238                                 p.tlog(p.findt(p.slot_cusp().back()));
239                         else
240                                 p.tlog(p.findt());
241                 }
242         }
243 #elif defined USE_PTHREAD
244         bool gf = false;
245         RRTNode *ron = nullptr;
246         RRTNode *gon = nullptr;
247         float mc = 9999;
248         pthread_t rt; // root thread
249         pthread_t gt; // goal thread
250         pthread_t ct; // connect thread
251
252         struct next_arg ra;
253         ra.gf = &gf;
254         ra.p = &p.p_root_;
255
256         struct next_arg ga;
257         ga.gf = &gf;
258         ga.p = &p.p_goal_;
259
260         p.tstart();
261         p.p_root_.tstart();
262         p.p_goal_.tstart();
263         pthread_create(&rt, NULL, &next_run, (void *) &ra);
264         pthread_create(&gt, NULL, &next_run, (void *) &ga);
265         int tol = 0;
266         int ndl = 0;
267         bool ndone = true;
268         std::vector<RRTNode *> steered;
269         while (!gf && p.elapsed() < TMAX &&
270                         p.p_root_.nodes().size() < NOFNODES &&
271                         p.p_goal_.nodes().size() < NOFNODES) {
272                 // overlap trees
273                 ndone = true;
274                 for (int i = 0; i < IXSIZE; i++) {
275                 for (int j = 0; j < IYSIZE; j++) {
276                         if (p.p_root_.ixy_[i][j].changed() &&
277                                         p.p_goal_.ixy_[i][j].changed()) {
278 ndone = false;
279 for (auto rn: p.p_root_.ixy_[i][j].nodes()) {
280 for (auto gn: p.p_goal_.ixy_[i][j].nodes()) {
281         if (rn->ccost() + gn->ccost() < mc &&
282                         IS_NEAR(rn, gn)) {
283                 gf = true;
284                 p.goal_found(true);
285                 ron = rn;
286                 gon = gn;
287                 mc = rn->ccost() + gn->ccost();
288         }
289         //// TRY TO STEER
290         //steered.clear();
291         //steered = p.steer(rn, gn);
292         //for (unsigned int k = 0; k < steered.size() - 1; k++)
293         //        steered[k]->add_child(steered[k + 1], 1);
294         //if (p.collide(
295         //                steered[0],
296         //                steered[steered.size() - 1])) {
297         //        for (auto n: steered)
298         //                delete n;
299         //        continue;
300         //}
301         //if (steered[steered.size() - 1]->ccost() +
302         //                rn->ccost() +
303         //                gn->ccost() < mc) {
304         //        gf = true;
305         //        p.goal_found(true);
306         //        ron = rn;
307         //        gon = gn;
308         //        mc = steered[steered.size() - 1]->ccost() +
309         //                rn->ccost() +
310         //                gn->ccost();
311         //}
312         //for (auto n: steered)
313         //        delete n;
314         //p.tend();
315         //if (p.elapsed() >= TMAX)
316         //        goto escapeloop;
317         //// END OF STEER
318 }}
319                         }
320                         tol++;
321                         if (ndone)
322                                 ndl++;
323                         p.tend();
324                         if (p.elapsed() >= TMAX)
325                                 goto escapeloop;
326                 }}
327                 // end of overlap trees
328                 p.tend();
329         }
330 escapeloop:
331         pthread_join(rt, NULL);
332         pthread_join(gt, NULL);
333         float nodo = ((float) ndl / (float) tol);
334         std::cerr << "nothing done is " << 100.0 * nodo;
335         std::cerr << "%" << std::endl;
336         //std::cerr << "rgf is " << p.p_root_.goal_found() << std::endl;
337         //std::cerr << "ggf is " << p.p_goal_.goal_found() << std::endl;
338         //std::cerr << "cgf is " << p.goal_found() << std::endl;
339         //if (p.goal_found()) {
340         //        steered.clear();
341         //        steered = p.steer(ron, gon);
342         //        for (auto ns: steered) {
343         //                p.nodes().push_back(ns);
344         //                p.add_ixy(ns);
345         //                ron->add_child(ns, p.cost(ron, ns));
346         //                ron = ns;
347         //        }
348         //        mc = ron->ccost() + gon->ccost();
349         //}
350         if (p.p_root_.goal_found() && p.p_root_.goal()->ccost() < mc) {
351                 ron = p.p_root_.goal()->parent();
352                 gon = p.p_root_.goal();
353                 mc = p.p_root_.goal()->ccost();
354         }
355         if (p.p_goal_.goal_found() && p.p_goal_.goal()->ccost() < mc) {
356                 ron = p.p_goal_.goal();
357                 gon = p.p_goal_.goal()->parent();
358                 mc = p.p_goal_.goal()->ccost();
359         }
360         p.root()->remove_parent();  // needed if p.p_goal_.goal_found()
361         p.root()->ccost(0);
362         p.goal()->children().clear();
363         // connect trees
364         if (gf) {
365         while (gon != p.goal()) {
366                 p.p_root_.nodes().push_back(new RRTNode(
367                                 gon->x(),
368                                 gon->y(),
369                                 gon->h()));
370                 ron->add_child(
371                                 p.p_root_.nodes().back(),
372                                 p.p_root_.cost(
373                                                 ron,
374                                                 p.p_root_.nodes().back()));
375                 ron = p.p_root_.nodes().back();
376                 gon = gon->parent();
377         }
378         ron->add_child(p.goal(), p.p_root_.cost(ron, p.goal()));
379         }
380         // end of connect trees
381         if (gf)
382                 p.tlog(p.findt());
383         if (p.opt_path())
384                 p.tlog(p.findt());
385 #endif
386         TEND();
387         TPRINT("RRT");
388         jvo["rrte"] = ELAPSED;
389 #ifdef JSONLOGEDGES
390         p.logr(p.root());
391 #endif
392
393         // statistics to error output
394         std::cerr << "TELAPSED is " << TELAPSED << std::endl;
395         std::cerr << "Elapsed is " << p.elapsed() << std::endl;
396         std::cerr << "Goal found is " << p.goal_found() << std::endl;
397         std::cerr << "#nodes is " << p.nodes().size() << std::endl;
398         std::cerr << "#samples is " << p.samples().size() << std::endl;
399         std::cerr << "`tlog` size is " << p.tlog().size() << std::endl;
400         std::cerr << "trajectories costs:" << std::endl;
401         for (j = 0; j < p.clog().size(); j++)
402                 std::cerr << "- " << p.clog()[j] << std::endl;
403         std::cerr << "RRT #nodes:" << std::endl;
404         for (j = 0; j < p.nlog().size(); j++)
405                 std::cerr << "- " << p.nlog()[j] << std::endl;
406         std::cerr << "trajectories seconds:" << std::endl;
407         for (j = 0; j < p.slog().size(); j++)
408                 std::cerr << "- " << p.slog()[j] << std::endl;
409         std::cerr << "RRT edges (from root) log size: " << p.rlog().size();
410         std::cerr << std::endl;
411         for (auto edges: p.rlog())
412                 std::cerr << "- " << edges.size() << std::endl;
413
414         // JSON output
415         jvo["elap"] = TELAPSED;
416 #ifdef USE_PTHREAD
417         jvo["nodo"][0] = nodo;
418 #endif
419         // log cost
420         for (j = 0; j < p.clog().size(); j++)
421                 jvo["cost"][j] = p.clog()[j];
422         // log #nodes
423         for (j = 0; j < p.nlog().size(); j++)
424                 jvo["node"][j] = p.nlog()[j];
425         // log seconds
426         for (j = 0; j < p.slog().size(); j++)
427                 jvo["secs"][j] = p.slog()[j];
428         // log traj
429         i = 0;
430         j = 0;
431         for (auto traj: p.tlog()) {
432                 i = 0;
433                 for (auto n: traj) {
434                         jvo["traj"][j][i][0] = n->x();
435                         jvo["traj"][j][i][1] = n->y();
436                         jvo["traj"][j][i][2] = n->h();
437                         jvo["traj"][j][i][3] = n->t();
438                         jvo["traj"][j][i][4] = n->s();
439                         i++;
440                 }
441                 j++;
442         }
443 #ifdef JSONLOGEDGES
444         i = 0;
445         j = 0;
446         for (auto edges: p.rlog()) {
447                 j = 0;
448                 for (auto e: edges) {
449                         jvo["edge"][i][j][0][0] = e->init()->x();
450                         jvo["edge"][i][j][0][1] = e->init()->y();
451                         jvo["edge"][i][j][0][2] = e->init()->h();
452                         jvo["edge"][i][j][1][0] = e->goal()->x();
453                         jvo["edge"][i][j][1][1] = e->goal()->y();
454                         jvo["edge"][i][j][1][2] = e->goal()->h();
455                         j++;
456                 }
457                 i++;
458         }
459 #endif
460 #ifdef JSONLOGSAMPLES
461         i = 0;
462         j = 0;
463         for (auto s: p.samples()) {
464                 jvo["samp"][j][0] = s->x();
465                 jvo["samp"][j][1] = s->y();
466                 jvo["samp"][j][2] = s->h();
467                 j++;
468         }
469 #endif
470         // print output
471         std::cout << jvo << std::endl;
472
473 #ifdef USE_GL
474         SDL_DestroyWindow(gw);
475         SDL_Quit();
476 #endif
477
478         // free mem
479         for (auto o: so) {
480                 delete o.init();
481                 delete o.goal();
482         }
483         return 0;
484 }
485
486 bool init()
487 {
488         if (SDL_Init(SDL_INIT_VIDEO) < 0) {
489                 std::cerr << "SDL could not initialize! SDL_Error: ";
490                 std::cerr << SDL_GetError();
491                 std::cerr << std::endl;
492                 return false;
493         }
494         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
495         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
496         gw = SDL_CreateWindow(
497                         "I am car",
498                         SDL_WINDOWPOS_UNDEFINED,
499                         SDL_WINDOWPOS_UNDEFINED,
500                         SCREEN_WIDTH,
501                         SCREEN_HEIGHT,
502                         SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
503         if (gw == NULL) {
504                 std::cerr << "Window could not be created! SDL_Error: ";
505                 std::cerr << SDL_GetError();
506                 std::cerr << std::endl;
507                 return false;
508         }
509         gc = SDL_GL_CreateContext(gw);
510         if (gc == NULL) {
511                 std::cerr << "OpenGL context couldn't be created! SDL Error: ";
512                 std::cerr << SDL_GetError();
513                 std::cerr << std::endl;
514                 return false;
515         }
516         if (SDL_GL_SetSwapInterval(1) < 0) {
517                 std::cerr << "Warning: Unable to set VSync! SDL Error: ";
518                 std::cerr << SDL_GetError();
519                 std::cerr << std::endl;
520                 return false;
521         }
522         if (!initGL()) {
523                 std::cerr << "Unable to initialize OpenGL!";
524                 std::cerr << std::endl;
525                 return false;
526         }
527         return true;
528 }
529
530 bool initGL()
531 {
532         GLenum error = GL_NO_ERROR;
533         glMatrixMode(GL_PROJECTION);
534         glLoadIdentity();
535         error = glGetError();
536         if (error != GL_NO_ERROR) {
537                 std::cerr << "Error initializing OpenGL! ";
538                 std::cerr << gluErrorString(error);
539                 std::cerr << std::endl;
540                 return false;
541         }
542         glMatrixMode(GL_MODELVIEW);
543         glLoadIdentity();
544         error = glGetError();
545         if (error != GL_NO_ERROR) {
546                 std::cerr << "Error initializing OpenGL! ";
547                 std::cerr << gluErrorString(error);
548                 std::cerr << std::endl;
549                 return false;
550         }
551         glClearColor(1, 1, 1, 1);
552         error = glGetError();
553         if (error != GL_NO_ERROR) {
554                 std::cerr << "Error initializing OpenGL! ";
555                 std::cerr << gluErrorString(error);
556                 std::cerr << std::endl;
557                 return false;
558         }
559         return true;
560 }