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