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