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