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