]> git.mxchange.org Git - flightgear.git/blob - utils/TerraSync/terrasync.cxx
Merge commit 'refs/merge-requests/14' of git://gitorious.org/fg/flightgear into next
[flightgear.git] / utils / TerraSync / terrasync.cxx
1 // terrasync.cxx -- "JIT" scenery fetcher
2 //
3 // Written by Curtis Olson, started November 2002.
4 //
5 // Copyright (C) 2002  Curtis L. Olson  - http://www.flightgear.org/~curt
6 // Copyright (C) 2008  Alexander R. Perry <alex.perry@ieee.org>
7 //
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 //
22 // $Id$
23
24 #ifdef HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27
28 #ifdef HAVE_WINDOWS_H
29 #include <windows.h>
30 #endif
31
32 #ifdef __MINGW32__
33 #include <time.h>
34 #include <unistd.h>
35 #elif defined(_MSC_VER)
36 #include <io.h>
37 #endif
38
39 #include <stdlib.h>             // atoi() atof() abs() system()
40 #include <signal.h>             // signal()
41
42 #include <simgear/compiler.h>
43
44 #include <iostream>
45 #include <fstream>
46 #include <string>
47 #include <deque>
48 #include <map>
49
50 #include <simgear/io/raw_socket.hxx>
51 #include <simgear/bucket/newbucket.hxx>
52 #include <simgear/misc/sg_path.hxx>
53
54 #ifdef HAVE_SVN_CLIENT_H
55 #  ifdef HAVE_LIBSVN_CLIENT_1
56 #    include <svn_auth.h>
57 #    include <svn_client.h>
58 #    include <svn_cmdline.h>
59 #    include <svn_pools.h>
60 #  else
61 #    undef HAVE_SVN_CLIENT_H
62 #  endif
63 #endif
64
65 using namespace std;
66
67 const char* source_base = NULL;
68 const char* svn_base =
69   "http://terrascenery.googlecode.com/svn/trunk/data/Scenery";
70 const char* rsync_base = "scenery.flightgear.org::Scenery";
71 const char* dest_base = "terrasyncdir";
72 const char* rsync_cmd = 
73     "rsync --verbose --archive --delete --perms --owner --group";
74
75 #ifdef HAVE_SVN_CLIENT_H
76 bool use_svn = true;
77 #else
78 bool use_svn = false;
79 const char* svn_cmd = "svn checkout";
80 #endif
81
82 // display usage
83 static void usage( const string& prog ) {
84     cout << 
85 "Usage:  terrasync [options]\n"
86 "Options:  \n"
87 " -d <dest>       destination directory [required]\n"
88 " -R              transport using pipe to rsync\n"
89 " -S              transport using built-in svn\n"
90 " -p <port>       listen on UDP port [default: 5501]\n"
91 " -s <source>     source base [default: '']\n"
92 " -pid <pidfile>  write PID to file\n"
93 " -v              be more verbose\n"
94 ;
95
96 #ifdef HAVE_SVN_CLIENT_H
97     cout << "    (defaults to the built in subversion)" << endl;
98 #else
99     cout << "    (defaults to rsync, using external commands)" << endl;
100 #endif
101
102   cout << "\nExample:\n"
103 "pid=$(cat $pidfile 2>/dev/null)\n"
104 "if test -n \"$pid\" && kill -0 $pid ; then\n"
105 "    echo \"terrasync already running: $pid\"\n"
106 "else\n"
107 "    nice /games/sport/fgs/utils/TerraSync/terrasync         \\\n"
108 "      -v -pid $pidfile -S -p 5500 -d /games/orig/terrasync &\n"
109 "fi" << endl;
110
111 }
112
113 deque<string> waitingTiles;
114 typedef map<string,time_t> CompletedTiles;
115 CompletedTiles completedTiles;
116 simgear::Socket theSocket;
117
118 #ifdef HAVE_SVN_CLIENT_H
119
120 // Things we need for doing subversion checkout - often
121 apr_pool_t *mysvn_pool = NULL;
122 svn_client_ctx_t *mysvn_ctx = NULL;
123 svn_opt_revision_t *mysvn_rev = NULL;
124 svn_opt_revision_t *mysvn_rev_peg = NULL;
125
126 static const svn_version_checklist_t mysvn_checklist[] = {
127     { "svn_subr",   svn_subr_version },
128     { "svn_client", svn_client_version },
129     { NULL, NULL }
130 };
131
132 // Configure our subversion session
133 int mysvn_setup(void) {
134     // Are we already prepared?
135     if (mysvn_pool) return EXIT_SUCCESS;
136     // No, so initialize svn internals generally
137 #ifdef _MSC_VER
138     // there is a segfault when providing an error stream.
139     //  Apparently, calling setvbuf with a nul buffer is
140     //  not supported under msvc 7.1 ( code inside svn_cmdline_init )
141     if (svn_cmdline_init("terrasync", 0) != EXIT_SUCCESS)
142         return EXIT_FAILURE;
143 #else
144     if (svn_cmdline_init("terrasync", stderr) != EXIT_SUCCESS)
145         return EXIT_FAILURE;
146 #endif
147     apr_pool_t *pool;
148     apr_pool_create(&pool, NULL);
149     svn_error_t *err = NULL;
150     SVN_VERSION_DEFINE(mysvn_version);
151     err = svn_ver_check_list(&mysvn_version, mysvn_checklist);
152     if (err)
153         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
154     err = svn_ra_initialize(pool);
155     if (err)
156         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
157     char *config_dir = NULL;
158     err = svn_config_ensure(config_dir, pool);
159     if (err)
160         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
161     err = svn_client_create_context(&mysvn_ctx, pool);
162     if (err)
163         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
164     err = svn_config_get_config(&(mysvn_ctx->config),
165         config_dir, pool);
166     if (err)
167         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
168     svn_config_t *cfg;
169     cfg = ( svn_config_t*) apr_hash_get(
170         mysvn_ctx->config,
171         SVN_CONFIG_CATEGORY_CONFIG,
172         APR_HASH_KEY_STRING);
173     if (err)
174         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
175     svn_auth_baton_t *ab;
176     err = svn_cmdline_setup_auth_baton(&ab,
177         TRUE, NULL, NULL, config_dir, TRUE, cfg,
178         mysvn_ctx->cancel_func, mysvn_ctx->cancel_baton, pool);
179     if (err)
180         return svn_cmdline_handle_exit_error(err, pool, "terrasync: ");
181     mysvn_ctx->auth_baton = ab;
182     mysvn_ctx->conflict_func = NULL;
183     mysvn_ctx->conflict_baton = NULL;
184     // Now our magic revisions
185     mysvn_rev = (svn_opt_revision_t*) apr_palloc(pool, 
186         sizeof(svn_opt_revision_t));
187     if (!mysvn_rev)
188         return EXIT_FAILURE;
189     mysvn_rev_peg = (svn_opt_revision_t*) apr_palloc(pool, 
190         sizeof(svn_opt_revision_t));
191     if (!mysvn_rev_peg)
192         return EXIT_FAILURE;
193     mysvn_rev->kind = svn_opt_revision_head;
194     mysvn_rev_peg->kind = svn_opt_revision_unspecified;
195     // Success if we got this far
196     mysvn_pool = pool;
197     return EXIT_SUCCESS;
198 }
199
200 #endif
201
202 // sync one directory tree
203 void sync_tree(const char* dir) {
204     int rc;
205     char command[512];
206     SGPath path( dest_base );
207
208     path.append( dir );
209     rc = path.create_dir( 0755 );
210     if (rc) {
211         cout << "Return code = " << rc << endl;
212         exit(1);
213     }
214
215     if (use_svn) {
216 #ifdef HAVE_SVN_CLIENT_H
217         cout << dir << " ... ";
218         cout.flush();
219         char dest_base_dir[512];
220         snprintf( command, 512,
221             "%s/%s", source_base, dir);
222         snprintf( dest_base_dir, 512,
223             "%s/%s", dest_base, dir);
224         svn_error_t *err = NULL;
225         if (mysvn_setup() != EXIT_SUCCESS)
226             exit(1);
227         apr_pool_t *subpool = svn_pool_create(mysvn_pool);
228         err = svn_client_checkout3(NULL,
229             command,
230             dest_base_dir,
231             mysvn_rev_peg,
232             mysvn_rev,
233             svn_depth_infinity,
234             0,
235             0,
236             mysvn_ctx,
237             subpool);
238         if (err) {
239             // Report errors from the checkout attempt
240             cout << "failed: " << endl
241                  << err->message << endl;
242             svn_error_clear(err);
243             return;
244         } else {
245             cout << "done" << endl;
246         }
247         svn_pool_destroy(subpool);
248         return;
249 #else
250
251         snprintf( command, 512,
252             "%s %s/%s %s/%s", svn_cmd,
253             source_base, dir,
254             dest_base, dir );
255 #endif
256     } else {
257         snprintf( command, 512,
258             "%s %s/%s/ %s/%s/", rsync_cmd,
259             source_base, dir,
260             dest_base, dir );
261     }
262     cout << command << endl;
263     rc = system( command );
264     if (rc) {
265         cout << "Return code = " << rc << endl;
266         if (rc == 5120) exit(1);
267     }
268 }
269
270 #if defined(_MSC_VER) || defined(__MINGW32__)
271 typedef void (__cdecl * sighandler_t)(int);
272 #elif defined( __APPLE__ )
273 typedef sig_t sighandler_t;
274 #endif
275
276 bool terminating = false;
277 sighandler_t prior_signal_handlers[32];
278 int termination_triggering_signals[] = {
279 #if defined(_MSC_VER) || defined(__MINGW32__)
280     SIGINT, SIGILL, SIGFPE, SIGSEGV, SIGTERM, SIGBREAK, SIGABRT,
281 #else
282     SIGHUP, SIGINT, SIGQUIT, SIGKILL, SIGTERM,
283 #endif
284     0};  // zero terminated
285
286 void terminate_request_handler(int param) {
287     char msg[] = "\nReceived signal XX, intend to exit soon.\n"
288          "repeat the signal to force immediate termination.\n";
289     msg[17] = '0' + param / 10;
290     msg[18] = '0' + param % 10;
291     write(1, msg, sizeof(msg) - 1);
292     terminating = true;
293     signal(param, prior_signal_handlers[param]);
294     theSocket.close();
295 }
296
297
298 const int nowhere = -9999;
299
300
301 // parse message
302 static void parse_message( const string &msg, int *lat, int *lon ) {
303     double dlat, dlon;
304     string text = msg;
305
306     // find GGA string and advance to start of lat
307     string::size_type pos = text.find( "$GPGGA" );
308     if ( pos == string::npos )
309     {
310         *lat = nowhere;
311         *lon = nowhere;
312         return;
313     }
314     string tmp = text.substr( pos + 7 );
315     pos = tmp.find( "," );
316     tmp = tmp.substr( pos + 1 );
317     // cout << "-> " << tmp << endl;
318
319     // find lat then advance to start of hemisphere
320     pos = tmp.find( "," );
321     string lats = tmp.substr( 0, pos );
322     dlat = atof( lats.c_str() ) / 100.0;
323     tmp = tmp.substr( pos + 1 );
324
325     // find N/S hemisphere and advance to start of lon
326     if ( tmp.substr( 0, 1 ) == "S" ) {
327         dlat = -dlat;
328     }
329     pos = tmp.find( "," );
330     tmp = tmp.substr( pos + 1 );
331
332     // find lon
333     pos = tmp.find( "," );
334     string lons = tmp.substr( 0, pos );
335     dlon = atof( lons.c_str() ) / 100.0;
336     tmp = tmp.substr( pos + 1 );
337
338     // find E/W hemisphere and advance to start of lon
339     if ( tmp.substr( 0, 1 ) == "W" ) {
340         dlon = -dlon;
341     }
342
343     if ( dlat < 0 ) {
344         *lat = (int)dlat - 1;
345     } else {
346         *lat = (int)dlat;
347     }
348
349     if ( dlon < 0 ) {
350         *lon = (int)dlon - 1;
351     } else {
352         *lon = (int)dlon;
353     }
354
355     if ((dlon == 0) && (dlat == 0)) {
356       *lon = nowhere;
357       *lat = nowhere;
358     }
359 }
360
361
362 // sync area
363 static void sync_area( int lat, int lon ) {
364     if ( lat < -90 || lat > 90 || lon < -180 || lon > 180 )
365         return;
366     char NS, EW;
367     int baselat, baselon;
368
369     if ( lat < 0 ) {
370         int base = (int)(lat / 10);
371         if ( lat == base * 10 ) {
372             baselat = base * 10;
373         } else {
374             baselat = (base - 1) * 10;
375         }
376         NS = 's';
377     } else {
378         baselat = (int)(lat / 10) * 10;
379         NS = 'n';
380     }
381     if ( lon < 0 ) {
382         int base = (int)(lon / 10);
383         if ( lon == base * 10 ) {
384             baselon = base * 10;
385         } else {
386             baselon = (base - 1) * 10;
387         }
388         EW = 'w';
389     } else {
390         baselon = (int)(lon / 10) * 10;
391         EW = 'e';
392     }
393
394     const char* terrainobjects[3] = { "Terrain", "Objects", 0 };
395     
396     for (const char** tree = &terrainobjects[0]; *tree; tree++) {
397         char dir[512];
398         snprintf( dir, 512, "%s/%c%03d%c%02d/%c%03d%c%02d",
399                 *tree,
400                 EW, abs(baselon), NS, abs(baselat),
401                 EW, abs(lon), NS, abs(lat) );
402         waitingTiles.push_back( dir );
403     }
404 }
405
406
407 // sync areas
408 static void sync_areas( int lat, int lon, int lat_dir, int lon_dir ) {
409     // do current 1x1 degree area first
410     sync_area( lat, lon );
411
412     if ( lat_dir == 0 && lon_dir == 0 ) {
413         // now do surrounding 8 1x1 degree areas.
414         for ( int i = lat - 1; i <= lat + 1; ++i ) {
415             for ( int j = lon - 1; j <= lon + 1; ++j ) {
416                 if ( i != lat || j != lon ) {
417                     sync_area( i, j );
418                 }
419             }
420         }
421     } else {
422         if ( lat_dir != 0 ) {
423             sync_area( lat + lat_dir, lon );
424             sync_area( lat + lat_dir, lon - 1 );
425             sync_area( lat + lat_dir, lon + 1 );
426         }
427         if ( lon_dir != 0 ) {
428             sync_area( lat, lon + lon_dir );
429             sync_area( lat - 1, lon + lon_dir );
430             sync_area( lat + 1, lon + lon_dir );
431         }
432     }
433 }
434
435 void getWaitingTile() {
436     while ( !waitingTiles.empty() ) {
437         CompletedTiles::iterator ii =
438             completedTiles.find( waitingTiles.front() );
439         time_t now = time(0);
440         if ( ii == completedTiles.end() || ii->second + 600 < now ) {
441             sync_tree(waitingTiles.front().c_str());
442             completedTiles[ waitingTiles.front() ] = now;
443             waitingTiles.pop_front();
444             break;
445         }
446         waitingTiles.pop_front();
447     }
448 }
449
450 int main( int argc, char **argv ) {
451     int port = 5501;
452     char host[256] = "localhost";
453     bool testing = false;
454     bool do_checkout(true);
455     int verbose(0);
456     const char* pidfn = "";
457
458     // parse arguments
459     int i = 1;
460     while ( i < argc ) {
461         if ( (string)argv[i] == "-p" ) {
462             ++i;
463             port = atoi( argv[i] );
464         } else if ( string(argv[i]).find("-pid") == 0 ) {
465             ++i;
466             pidfn = argv[i];
467             cout << "pidfn: " << pidfn << endl;
468         } else if ( (string)argv[i] == "-s" ) {
469             ++i;
470             source_base = argv[i];
471         } else if ( (string)argv[i] == "-d" ) {
472             ++i;
473             dest_base = argv[i];
474         } else if ( (string)argv[i] == "-R" ) {
475             use_svn = false;
476         } else if ( (string)argv[i] == "-S" ) {
477             use_svn = true;
478         } else if ( (string)argv[i] == "-v" ) {
479             verbose++;
480         } else if ( (string)argv[i] == "-T" ) {
481             testing = true;
482         } else if ( (string)argv[i] == "-h" ) {
483             usage( argv[0] );
484             exit(0);
485         } else {
486             cerr << "Unrecognized verbiage '" << argv[i] << "'" << endl;
487             usage( argv[0] );
488             exit(-1);        
489         }
490         ++i;
491     }
492
493     if (*pidfn) {
494       ofstream pidstream;
495       pidstream.open(pidfn);
496       if (!pidstream.good()) {
497         cerr << "Cannot open pid file '" << pidfn << "': ";
498         perror(0);
499         exit(2);
500       }
501       pidstream << getpid() << endl;
502       pidstream.close();
503     }
504
505     // Use the appropriate default for the "-s" flag
506     if (source_base == NULL) {
507         if (use_svn)
508             source_base = svn_base;
509         else
510             source_base = rsync_base;
511     }
512     
513     // Must call this before any other net stuff
514     simgear::Socket::initSockets();
515
516     if ( ! theSocket.open( false ) ) {  // open a UDP socket
517         printf("error opening socket\n");
518         return -1;
519     }
520
521     if ( theSocket.bind( host, port ) == -1 ) {
522         printf("error binding to port %d\n", port);
523         return -1;
524     }
525
526     char msg[256];
527     int maxlen = 256;
528     int len;
529     int lat, lon;
530     int last_lat = nowhere;
531     int last_lon = nowhere;
532     bool recv_msg = false;
533
534     char synced_other;
535     if (do_checkout) {
536         for ( synced_other = 'K'; synced_other <= 'Z'; synced_other++ ) {
537             char dir[512];
538             snprintf( dir, 512, "Airports/%c", synced_other );
539             waitingTiles.push_back( dir );
540         }
541         for ( synced_other = 'A'; synced_other <= 'J'; synced_other++ ) {
542             char dir[512];
543             snprintf( dir, 512, "Airports/%c", synced_other );
544             waitingTiles.push_back( dir );
545         }
546         if ( use_svn ) {
547             waitingTiles.push_back( "Models" );
548         }
549     }
550
551
552     for (int* sigp=termination_triggering_signals; *sigp; sigp++) {
553         prior_signal_handlers[*sigp] =
554             signal(*sigp, *terminate_request_handler);
555         if (verbose) cout << "Intercepted signal " << *sigp << endl;
556     }
557
558     while ( !terminating ) {
559         // main loop
560         recv_msg = false;
561         if ( testing ) {
562             // No FGFS communications
563             lat = 37;
564             lon = -123;
565             recv_msg = (lat != last_lat) || (lon != last_lon);
566         } else {
567             if (verbose && waitingTiles.empty()) {
568                 cout << "Idle; waiting for FlightGear position\n";
569             }
570             theSocket.setBlocking(waitingTiles.empty());
571             len = theSocket.recv(msg, maxlen, 0);
572             if (len >= 0) {
573                 msg[len] = '\0';
574                 recv_msg = true;
575                 if (verbose) cout << "recv length: " << len << endl;
576                 parse_message( msg, &lat, &lon );
577             }
578         }
579
580         if ( recv_msg ) {
581              // Ignore messages where the location does not change
582              if ( lat != last_lat || lon != last_lon ) {
583                 cout << "pos in msg = " << lat << "," << lon << endl;
584                 deque<string> oldRequests;
585                 oldRequests.swap( waitingTiles );
586                 int lat_dir, lon_dir, dist;
587                 if ( last_lat == nowhere || last_lon == nowhere ) {
588                     lat_dir = lon_dir = 0;
589                 } else {
590                     dist = lat - last_lat;
591                     if ( dist != 0 ) {
592                         lat_dir = dist / abs(dist);
593                     } else {
594                         lat_dir = 0;
595                     }
596                     dist = lon - last_lon;
597                     if ( dist != 0 ) {
598                         lon_dir = dist / abs(dist);
599                     } else {
600                         lon_dir = 0;
601                     }
602                 }
603                 cout << "lat = " << lat << " lon = " << lon << endl;
604                 cout << "lat_dir = " << lat_dir << "  "
605                      << "lon_dir = " << lon_dir << endl;
606                 sync_areas( lat, lon, lat_dir, lon_dir );
607                 while ( !oldRequests.empty() ) {
608                     waitingTiles.push_back( oldRequests.front() );
609                     oldRequests.pop_front();
610                 }
611                 last_lat = lat;
612                 last_lon = lon;
613             }
614         }
615
616         // No messages inbound, so process some pending work
617         else if ( !waitingTiles.empty() ) {
618             getWaitingTile();
619         }
620
621         else if ( testing ) {
622             terminating = true;
623         } else
624
625         #ifdef _WIN32
626                 Sleep(1000);
627 #else
628                 sleep(1);
629 #endif
630     } // while !terminating
631         
632     return 0;
633 }