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