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