]> rtime.felk.cvut.cz Git - hubacji1/iamcar.git/blob - base/main.cc
422e3308ad572ecb0b803a4927875fe50c67346e
[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         }
187 #ifdef USE_SLOTPLANNER
188         TSTART();
189         if (ps.slot().bnodes().size() > 0)
190                 ps.fip(co, so);
191         TEND();
192         jvo["ppse"] = ELAPSED;
193         TPRINT("ParallelSlot");
194 #endif
195         if (ps.slot().bnodes().size() > 0) {
196                 ps.setAll();
197                 p.samplingInfo_ = ps.getSamplingInfo();
198                 p.useSamplingInfo_ = true;
199         }
200         p.goals(ps.goals());
201         if (ps.cusp().size() > 0) {
202                 p.goal(ps.getMidd());
203                 p.slot_cusp(ps.cusp().front()); // use first found solution
204                 jvo["midd"][0] = p.goal()->x();
205                 jvo["midd"][1] = p.goal()->y();
206                 jvo["midd"][2] = p.goal()->h();
207                 jvo["goal"][0] = p.slot_cusp().back()->x();
208                 jvo["goal"][1] = p.slot_cusp().back()->y();
209                 jvo["goal"][2] = p.slot_cusp().back()->h();
210         } else {
211                 jvo["goal"][0] = p.goal()->x();
212                 jvo["goal"][1] = p.goal()->y();
213                 jvo["goal"][2] = p.goal()->h();
214         }
215         TSTART();
216         std::cerr << "Slot Info:" << std::endl;
217         if (ps.slotSide() == LEFT)
218                 std::cerr << "- LEFT" << std::endl;
219         else
220                 std::cerr << "- RIGHT" << std::endl;
221         if (ps.slotType() == PARALLEL)
222                 std::cerr << "- PARALLEL" << std::endl;
223         else
224                 std::cerr << "- PERPENDICULAR" << std::endl;
225 #ifdef USE_LOADF
226         std::vector<RRTNode *> steered;
227         for (auto jn: jvi["traj"][0]) {
228                 steered.push_back(new RRTNode(
229                                         jn[0].asFloat(),
230                                         jn[1].asFloat(),
231                                         jn[2].asFloat(),
232                                         jn[3].asFloat(),
233                                         jn[4].asFloat()));
234         }
235         std::reverse(steered.begin(), steered.end());
236         RRTNode *pn = p.root();
237         for (auto n: steered) {
238                 if (IS_NEAR(pn, n))
239                         continue;
240                 pn->add_child(n, p.cost(pn, n));
241                 pn = n;
242                 p.glplot();
243         }
244         pn->add_child(p.goal(), p.cost(pn, p.goal()));
245         p.goal_found(true);
246         p.tlog(p.findt());
247         if (p.opt_path()) {
248                 p.tlog(p.findt());
249                 p.glplot();
250         }
251         p.glplot();
252         sleep(2);
253 #elif defined USE_INTERRUPT
254         signal(SIGINT, hint);
255         signal(SIGTERM, hint);
256         p.tstart();
257         while (run_planner) {
258                 p.next();
259                 p.tend();
260                 if (p.opt_path())
261                         p.tlog(p.findt());
262                 p.glplot();
263         }
264 #elif defined USE_TMAX
265         p.tstart();
266         p.tend();
267         while (!p.goal_found() && p.elapsed() < TMAX) {
268                 p.next();
269                 p.tend();
270                 if (p.opt_path()) {
271                         p.tlog(p.findt());
272                 }
273         }
274 #elif defined USE_PTHREAD
275         bool gf = false;
276         RRTNode *ron = nullptr;
277         RRTNode *gon = nullptr;
278         float mc = 9999;
279         pthread_t rt; // root thread
280         pthread_t gt; // goal thread
281         pthread_t ct; // connect thread
282
283         struct next_arg ra;
284         ra.gf = &gf;
285         ra.p = &p.p_root_;
286
287         struct next_arg ga;
288         ga.gf = &gf;
289         ga.p = &p.p_goal_;
290
291         p.tstart();
292         p.p_root_.tstart();
293         p.p_goal_.tstart();
294         pthread_create(&rt, NULL, &next_run, (void *) &ra);
295         pthread_create(&gt, NULL, &next_run, (void *) &ga);
296         int tol = 0;
297         int ndl = 0;
298         bool ndone = true;
299         while (!gf && p.elapsed() < TMAX &&
300                         p.p_root_.nodes().size() < NOFNODES &&
301                         p.p_goal_.nodes().size() < NOFNODES) {
302                 // overlap trees
303                 ndone = true;
304                 for (int i = 0; i < IXSIZE; i++) {
305                 for (int j = 0; j < IYSIZE; j++) {
306                         if (p.p_root_.ixy_[i][j].changed() &&
307                                         p.p_goal_.ixy_[i][j].changed()) {
308 ndone = false;
309 for (auto rn: p.p_root_.ixy_[i][j].nodes()) {
310 for (auto gn: p.p_goal_.ixy_[i][j].nodes()) {
311         if (rn->ccost() + gn->ccost() < mc &&
312                         IS_NEAR(rn, gn)) {
313                 gf = true;
314                 p.goal_found(true);
315                 ron = rn;
316                 gon = gn;
317                 mc = rn->ccost() + gn->ccost();
318         }
319 }}
320                         }
321                         tol++;
322                         if (ndone)
323                                 ndl++;
324                         p.tend();
325                         if (p.elapsed() >= TMAX)
326                                 goto escapeloop;
327                 }}
328                 // end of overlap trees
329                 p.tend();
330         }
331 escapeloop:
332         pthread_join(rt, NULL);
333         pthread_join(gt, NULL);
334         float nodo = ((float) ndl / (float) tol);
335         std::cerr << "nothing done is " << 100.0 * nodo;
336         std::cerr << "%" << std::endl;
337         //std::cerr << "rgf is " << p.p_root_.goal_found() << std::endl;
338         //std::cerr << "ggf is " << p.p_goal_.goal_found() << std::endl;
339         //std::cerr << "cgf is " << p.goal_found() << std::endl;
340         if (p.p_root_.goal_found() && p.p_root_.goal()->ccost() < mc) {
341                 ron = p.p_root_.goal()->parent();
342                 gon = p.p_root_.goal();
343                 mc = p.p_root_.goal()->ccost();
344         }
345         if (p.p_goal_.goal_found() && p.p_goal_.goal()->ccost() < mc) {
346                 ron = p.p_goal_.goal();
347                 gon = p.p_goal_.goal()->parent();
348                 mc = p.p_goal_.goal()->ccost();
349         }
350         p.root()->remove_parent();  // needed if p.p_goal_.goal_found()
351         p.root()->ccost(0);
352         p.goal()->children().clear();
353         // connect trees
354         if (gf) {
355         while (gon != p.goal()) {
356                 p.p_root_.nodes().push_back(new RRTNode(
357                                 gon->x(),
358                                 gon->y(),
359                                 gon->h()));
360                 ron->add_child(
361                                 p.p_root_.nodes().back(),
362                                 p.p_root_.cost(
363                                                 ron,
364                                                 p.p_root_.nodes().back()));
365                 ron = p.p_root_.nodes().back();
366                 gon = gon->parent();
367         }
368         ron->add_child(p.goal(), p.p_root_.cost(ron, p.goal()));
369         }
370         // end of connect trees
371         if (gf)
372                 p.tlog(p.findt());
373         if (p.opt_path())
374                 p.tlog(p.findt());
375 #endif
376         TEND();
377         TPRINT("RRT");
378         jvo["rrte"] = ELAPSED;
379 #ifdef JSONLOGEDGES
380         p.logr(p.root());
381 #endif
382
383         // statistics to error output
384         std::cerr << "TELAPSED is " << TELAPSED << std::endl;
385         std::cerr << "Elapsed is " << p.elapsed() << std::endl;
386         std::cerr << "Goal found is " << p.goal_found() << std::endl;
387         std::cerr << "#nodes is " << p.nodes().size() << std::endl;
388         std::cerr << "#samples is " << p.samples().size() << std::endl;
389         std::cerr << "`tlog` size is " << p.tlog().size() << std::endl;
390         std::cerr << "trajectories costs:" << std::endl;
391         for (j = 0; j < p.clog().size(); j++)
392                 std::cerr << "- " << p.clog()[j] << std::endl;
393         std::cerr << "RRT #nodes:" << std::endl;
394         for (j = 0; j < p.nlog().size(); j++)
395                 std::cerr << "- " << p.nlog()[j] << std::endl;
396         std::cerr << "trajectories seconds:" << std::endl;
397         for (j = 0; j < p.slog().size(); j++)
398                 std::cerr << "- " << p.slog()[j] << std::endl;
399         std::cerr << "RRT edges (from root) log size: " << p.rlog().size();
400         std::cerr << std::endl;
401         for (auto edges: p.rlog())
402                 std::cerr << "- " << edges.size() << std::endl;
403
404         // JSON output
405         jvo["elap"] = TELAPSED;
406 #ifdef USE_PTHREAD
407         jvo["nodo"][0] = nodo;
408 #endif
409         // log cost
410         for (j = 0; j < p.clog().size(); j++)
411                 jvo["cost"][j] = p.clog()[j];
412         // log #nodes
413         for (j = 0; j < p.nlog().size(); j++)
414                 jvo["node"][j] = p.nlog()[j];
415         // log seconds
416         for (j = 0; j < p.slog().size(); j++)
417                 jvo["secs"][j] = p.slog()[j];
418         // log traj
419         i = 0;
420         j = 0;
421         for (auto traj: p.tlog()) {
422                 i = 0;
423                 for (auto n: traj) {
424                         jvo["traj"][j][i][0] = n->x();
425                         jvo["traj"][j][i][1] = n->y();
426                         jvo["traj"][j][i][2] = n->h();
427                         jvo["traj"][j][i][3] = n->t();
428                         jvo["traj"][j][i][4] = n->s();
429                         i++;
430                 }
431                 j++;
432         }
433 #ifdef JSONLOGEDGES
434         i = 0;
435         j = 0;
436         for (auto edges: p.rlog()) {
437                 j = 0;
438                 for (auto e: edges) {
439                         jvo["edge"][i][j][0][0] = e->init()->x();
440                         jvo["edge"][i][j][0][1] = e->init()->y();
441                         jvo["edge"][i][j][0][2] = e->init()->h();
442                         jvo["edge"][i][j][1][0] = e->goal()->x();
443                         jvo["edge"][i][j][1][1] = e->goal()->y();
444                         jvo["edge"][i][j][1][2] = e->goal()->h();
445                         j++;
446                 }
447                 i++;
448         }
449 #endif
450 #ifdef JSONLOGSAMPLES
451         i = 0;
452         j = 0;
453         for (auto s: p.samples()) {
454                 jvo["samp"][j][0] = s->x();
455                 jvo["samp"][j][1] = s->y();
456                 jvo["samp"][j][2] = s->h();
457                 j++;
458         }
459 #endif
460         // print output
461         std::cout << jvo << std::endl;
462
463 #if USE_GL > 0
464         SDL_DestroyWindow(gw);
465         SDL_Quit();
466 #endif
467
468         // free mem
469         for (auto o: so) {
470                 delete o.init();
471                 delete o.goal();
472         }
473         return 0;
474 }
475
476 #if USE_GL > 0
477 bool init()
478 {
479         if (SDL_Init(SDL_INIT_VIDEO) < 0) {
480                 std::cerr << "SDL could not initialize! SDL_Error: ";
481                 std::cerr << SDL_GetError();
482                 std::cerr << std::endl;
483                 return false;
484         }
485         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
486         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
487         gw = SDL_CreateWindow(
488                         "I am car",
489                         SDL_WINDOWPOS_UNDEFINED,
490                         SDL_WINDOWPOS_UNDEFINED,
491                         SCREEN_WIDTH,
492                         SCREEN_HEIGHT,
493                         SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
494         if (gw == NULL) {
495                 std::cerr << "Window could not be created! SDL_Error: ";
496                 std::cerr << SDL_GetError();
497                 std::cerr << std::endl;
498                 return false;
499         }
500         gc = SDL_GL_CreateContext(gw);
501         if (gc == NULL) {
502                 std::cerr << "OpenGL context couldn't be created! SDL Error: ";
503                 std::cerr << SDL_GetError();
504                 std::cerr << std::endl;
505                 return false;
506         }
507         if (SDL_GL_SetSwapInterval(1) < 0) {
508                 std::cerr << "Warning: Unable to set VSync! SDL Error: ";
509                 std::cerr << SDL_GetError();
510                 std::cerr << std::endl;
511                 return false;
512         }
513         if (!initGL()) {
514                 std::cerr << "Unable to initialize OpenGL!";
515                 std::cerr << std::endl;
516                 return false;
517         }
518         return true;
519 }
520
521 bool initGL()
522 {
523         GLenum error = GL_NO_ERROR;
524         glMatrixMode(GL_PROJECTION);
525         glLoadIdentity();
526         error = glGetError();
527         if (error != GL_NO_ERROR) {
528                 std::cerr << "Error initializing OpenGL! ";
529                 std::cerr << gluErrorString(error);
530                 std::cerr << std::endl;
531                 return false;
532         }
533         glMatrixMode(GL_MODELVIEW);
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         glClearColor(1, 1, 1, 1);
543         error = glGetError();
544         if (error != GL_NO_ERROR) {
545                 std::cerr << "Error initializing OpenGL! ";
546                 std::cerr << gluErrorString(error);
547                 std::cerr << std::endl;
548                 return false;
549         }
550         return true;
551 }
552 #endif