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