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