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