]> rtime.felk.cvut.cz Git - hubacji1/iamcar.git/blob - base/main.cc
Fix negative cost of final path
[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 <iostream>
20 #include <jsoncpp/json/json.h>
21 #include <pthread.h>
22 #include <signal.h>
23 #include <unistd.h>
24 #include "compile.h"
25 #include "obstacle.h"
26 #include "rrtplanner.h"
27 // OpenGL
28 #include <GL/gl.h>
29 #include <GL/glu.h>
30 #include <SDL2/SDL.h>
31
32 // debug
33 //#define JSONLOGEDGES
34 //#define JSONLOGSAMPLES
35
36 // choose
37 //#define USE_INTERRUPT
38 // or
39 //#define USE_TMAX
40 // or
41 //#define USE_LOADF
42 // or
43 #define USE_PTHREAD
44
45 #ifdef USE_INTERRUPT
46         #define USE_GL
47 #endif
48
49 bool run_planner = true;
50
51 SDL_Window* gw = NULL;
52 SDL_GLContext gc;
53
54 bool init();
55 bool initGL();
56
57 void hint(int)
58 {
59         run_planner = false;
60 }
61
62 #ifdef USE_PTHREAD
63 struct next_arg {
64         bool *gf;
65         T2 *p;
66 };
67
68 void *next_run(void *arg)
69 {
70         struct next_arg *na = (struct next_arg *) arg;
71         T2 *lp = (T2 *) na->p;
72         bool *gf = na->gf;
73         while (!*gf && lp->elapsed() < TMAX) {
74                 if (lp->next())
75                         *gf = true;
76                 lp->tend();
77         }
78         pthread_exit(NULL);
79         return NULL;
80 }
81 #endif
82
83 int main()
84 {
85 #ifdef USE_GL
86         init();
87 #endif
88
89         Json::Value jvi; // JSON input
90         Json::Value jvo; // JSON output
91         unsigned int i = 0;
92         unsigned int j = 0;
93         std::cin >> jvi;
94         std::string encoding = jvi.get("encoding", "UTF-8" ).asString();
95
96         PLANNER p(
97                         new RRTNode(
98                                 jvi["init"][0].asFloat(),
99                                 jvi["init"][1].asFloat(),
100                                 jvi["init"][2].asFloat()),
101                         new RRTNode(
102                                 jvi["goal"][0].asFloat(),
103                                 jvi["goal"][1].asFloat(),
104                                 jvi["goal"][2].asFloat()));
105         std::vector<CircleObstacle> co;
106         std::vector<SegmentObstacle> so;
107         for (auto o: jvi["obst"]) {
108                 if (o["circle"] != Json::nullValue) {
109                         co.push_back(CircleObstacle(
110                                                 o["circle"][0].asFloat(),
111                                                 o["circle"][1].asFloat(),
112                                                 o["circle"][2].asFloat()));
113                 }
114                 if (o["segment"] != Json::nullValue) {
115                         so.push_back(SegmentObstacle(
116                                 new RRTNode(
117                                         o["segment"][0][0].asFloat(),
118                                         o["segment"][0][1].asFloat(),
119                                         0),
120                                 new RRTNode(
121                                         o["segment"][1][0].asFloat(),
122                                         o["segment"][1][1].asFloat(),
123                                         0)));
124                 }
125         }
126         p.link_obstacles(&co, &so);
127         p.ocost(p.root());
128         p.ocost(p.goal());
129
130 #ifdef USE_LOADF
131         std::vector<RRTNode *> steered;
132         for (auto jn: jvi["traj"][0]) {
133                 steered.push_back(new RRTNode(
134                                         jn[0].asFloat(),
135                                         jn[1].asFloat(),
136                                         jn[2].asFloat(),
137                                         jn[3].asFloat(),
138                                         jn[4].asFloat()));
139         }
140         std::reverse(steered.begin(), steered.end());
141         RRTNode *pn = p.root();
142         for (auto n: steered) {
143                 if (IS_NEAR(pn, n))
144                         continue;
145                 pn->add_child(n, p.cost(pn, n));
146                 pn = n;
147                 p.glplot();
148         }
149         pn->add_child(p.goal(), p.cost(pn, p.goal()));
150         p.goal_found(true);
151         p.tlog(p.findt());
152         if (p.opt_path()) {
153                 p.tlog(p.findt());
154                 p.glplot();
155         }
156         p.glplot();
157         sleep(2);
158 #elif defined USE_INTERRUPT
159         signal(SIGINT, hint);
160         signal(SIGTERM, hint);
161         p.tstart();
162         while (run_planner) {
163                 p.next();
164                 p.tend();
165                 if (p.opt_path())
166                         p.tlog(p.findt());
167                 p.glplot();
168         }
169 #elif defined USE_TMAX
170         p.tstart();
171         p.tend();
172         while (!p.goal_found() && p.elapsed() < TMAX) {
173                 p.next();
174                 p.tend();
175                 if (p.opt_path())
176                         p.tlog(p.findt());
177         }
178 #elif defined USE_PTHREAD
179         bool gf = false;
180         RRTNode *ron = nullptr;
181         RRTNode *gon = nullptr;
182         float mc = 9999;
183         pthread_t rt; // root thread
184         pthread_t gt; // goal thread
185         pthread_t ct; // connect thread
186
187         struct next_arg ra;
188         ra.gf = &gf;
189         ra.p = &p.p_root_;
190
191         struct next_arg ga;
192         ga.gf = &gf;
193         ga.p = &p.p_goal_;
194
195         p.tstart();
196         p.p_root_.tstart();
197         p.p_goal_.tstart();
198         pthread_create(&rt, NULL, &next_run, (void *) &ra);
199         pthread_create(&gt, NULL, &next_run, (void *) &ga);
200         while (!gf && p.elapsed() < TMAX &&
201                         p.p_root_.nodes().size() < NOFNODES &&
202                         p.p_goal_.nodes().size() < NOFNODES) {
203                 // overlap trees
204                 for (int i = 0; i < IXSIZE; i++) {
205                 for (int j = 0; j < IYSIZE; j++) {
206                         if (p.p_root_.ixy_[i][j].changed() &&
207                                         p.p_goal_.ixy_[i][j].changed()) {
208 for (auto rn: p.p_root_.ixy_[i][j].nodes()) {
209 for (auto gn: p.p_goal_.ixy_[i][j].nodes()) {
210         if (rn->ccost() + gn->ccost() < mc &&
211                         IS_NEAR(rn, gn)) {
212                 gf = true;
213                 p.goal_found(true);
214                 ron = rn;
215                 gon = gn;
216                 mc = rn->ccost() + gn->ccost();
217         }
218 }}
219                         }
220                 }}
221                 // end of overlap trees
222                 p.tend();
223         }
224         pthread_join(rt, NULL);
225         pthread_join(gt, NULL);
226         if (p.p_root_.goal_found() && p.p_root_.goal()->ccost() < mc) {
227                 ron = p.p_root_.goal()->parent();
228                 gon = p.p_root_.goal();
229                 mc = p.p_root_.goal()->ccost();
230         }
231         if (p.p_goal_.goal_found() && p.p_goal_.goal()->ccost() < mc) {
232                 ron = p.p_goal_.goal();
233                 gon = p.p_goal_.goal()->parent();
234                 mc = p.p_goal_.goal()->ccost();
235         }
236         p.root()->remove_parent();  // needed if p.p_goal_.goal_found()
237         p.root()->ccost(0);
238         p.goal()->children().clear();
239         // connect trees
240         while (gon != p.goal()) {
241                 p.p_root_.nodes().push_back(new RRTNode(
242                                 gon->x(),
243                                 gon->y(),
244                                 gon->h()));
245                 ron->add_child(
246                                 p.p_root_.nodes().back(),
247                                 p.p_root_.cost(
248                                                 ron,
249                                                 p.p_root_.nodes().back()));
250                 ron = p.p_root_.nodes().back();
251                 gon = gon->parent();
252         }
253         ron->add_child(p.goal(), p.p_root_.cost(ron, p.goal()));
254         // end of connect trees
255         if (gf)
256                 p.tlog(p.findt());
257         if (p.opt_path())
258                 p.tlog(p.findt());
259 #endif
260 #ifdef JSONLOGEDGES
261         p.logr(p.root());
262 #endif
263
264         // statistics to error output
265         std::cerr << "Elapsed is " << p.elapsed() << std::endl;
266         std::cerr << "Goal found is " << p.goal_found() << std::endl;
267         std::cerr << "#nodes is " << p.nodes().size() << std::endl;
268         std::cerr << "#samples is " << p.samples().size() << std::endl;
269         std::cerr << "`tlog` size is " << p.tlog().size() << std::endl;
270         std::cerr << "trajectories costs:" << std::endl;
271         for (j = 0; j < p.clog().size(); j++)
272                 std::cerr << "- " << p.clog()[j] << std::endl;
273         std::cerr << "RRT #nodes:" << std::endl;
274         for (j = 0; j < p.nlog().size(); j++)
275                 std::cerr << "- " << p.nlog()[j] << std::endl;
276         std::cerr << "trajectories seconds:" << std::endl;
277         for (j = 0; j < p.slog().size(); j++)
278                 std::cerr << "- " << p.slog()[j] << std::endl;
279         std::cerr << "RRT edges (from root) log size: " << p.rlog().size();
280         std::cerr << std::endl;
281         for (auto edges: p.rlog())
282                 std::cerr << "- " << edges.size() << std::endl;
283
284         // JSON output
285         jvo["elap"] = p.elapsed();
286         // log cost
287         for (j = 0; j < p.clog().size(); j++)
288                 jvo["cost"][j] = p.clog()[j];
289         // log #nodes
290         for (j = 0; j < p.nlog().size(); j++)
291                 jvo["node"][j] = p.nlog()[j];
292         // log seconds
293         for (j = 0; j < p.slog().size(); j++)
294                 jvo["secs"][j] = p.slog()[j];
295         // log traj
296         i = 0;
297         j = 0;
298         for (auto traj: p.tlog()) {
299                 i = 0;
300                 for (auto n: traj) {
301                         jvo["traj"][j][i][0] = n->x();
302                         jvo["traj"][j][i][1] = n->y();
303                         jvo["traj"][j][i][2] = n->h();
304                         jvo["traj"][j][i][3] = n->t();
305                         jvo["traj"][j][i][4] = n->s();
306                         i++;
307                 }
308                 j++;
309         }
310 #ifdef JSONLOGEDGES
311         i = 0;
312         j = 0;
313         for (auto edges: p.rlog()) {
314                 j = 0;
315                 for (auto e: edges) {
316                         jvo["edge"][i][j][0][0] = e->init()->x();
317                         jvo["edge"][i][j][0][1] = e->init()->y();
318                         jvo["edge"][i][j][0][2] = e->init()->h();
319                         jvo["edge"][i][j][1][0] = e->goal()->x();
320                         jvo["edge"][i][j][1][1] = e->goal()->y();
321                         jvo["edge"][i][j][1][2] = e->goal()->h();
322                         j++;
323                 }
324                 i++;
325         }
326 #endif
327 #ifdef JSONLOGSAMPLES
328         i = 0;
329         j = 0;
330         for (auto s: p.samples()) {
331                 jvo["samp"][j][0] = s->x();
332                 jvo["samp"][j][1] = s->y();
333                 jvo["samp"][j][2] = s->h();
334                 j++;
335         }
336 #endif
337         // print output
338         std::cout << jvo << std::endl;
339
340 #ifdef USE_GL
341         SDL_DestroyWindow(gw);
342         SDL_Quit();
343 #endif
344
345         // free mem
346         for (auto o: so) {
347                 delete o.init();
348                 delete o.goal();
349         }
350         return 0;
351 }
352
353 bool init()
354 {
355         if (SDL_Init(SDL_INIT_VIDEO) < 0) {
356                 std::cerr << "SDL could not initialize! SDL_Error: ";
357                 std::cerr << SDL_GetError();
358                 std::cerr << std::endl;
359                 return false;
360         }
361         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
362         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
363         gw = SDL_CreateWindow(
364                         "I am car",
365                         SDL_WINDOWPOS_UNDEFINED,
366                         SDL_WINDOWPOS_UNDEFINED,
367                         SCREEN_WIDTH,
368                         SCREEN_HEIGHT,
369                         SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
370         if (gw == NULL) {
371                 std::cerr << "Window could not be created! SDL_Error: ";
372                 std::cerr << SDL_GetError();
373                 std::cerr << std::endl;
374                 return false;
375         }
376         gc = SDL_GL_CreateContext(gw);
377         if (gc == NULL) {
378                 std::cerr << "OpenGL context couldn't be created! SDL Error: ";
379                 std::cerr << SDL_GetError();
380                 std::cerr << std::endl;
381                 return false;
382         }
383         if (SDL_GL_SetSwapInterval(1) < 0) {
384                 std::cerr << "Warning: Unable to set VSync! SDL Error: ";
385                 std::cerr << SDL_GetError();
386                 std::cerr << std::endl;
387                 return false;
388         }
389         if (!initGL()) {
390                 std::cerr << "Unable to initialize OpenGL!";
391                 std::cerr << std::endl;
392                 return false;
393         }
394         return true;
395 }
396
397 bool initGL()
398 {
399         GLenum error = GL_NO_ERROR;
400         glMatrixMode(GL_PROJECTION);
401         glLoadIdentity();
402         error = glGetError();
403         if (error != GL_NO_ERROR) {
404                 std::cerr << "Error initializing OpenGL! ";
405                 std::cerr << gluErrorString(error);
406                 std::cerr << std::endl;
407                 return false;
408         }
409         glMatrixMode(GL_MODELVIEW);
410         glLoadIdentity();
411         error = glGetError();
412         if (error != GL_NO_ERROR) {
413                 std::cerr << "Error initializing OpenGL! ";
414                 std::cerr << gluErrorString(error);
415                 std::cerr << std::endl;
416                 return false;
417         }
418         glClearColor(1, 1, 1, 1);
419         error = glGetError();
420         if (error != GL_NO_ERROR) {
421                 std::cerr << "Error initializing OpenGL! ";
422                 std::cerr << gluErrorString(error);
423                 std::cerr << std::endl;
424                 return false;
425         }
426         return true;
427 }