Debian Codegraph @

src/Navaids/NavDataCache.cxx

raw symbols SCIP
1
2 /*
3 * SPDX-FileCopyrightText: (C) 2012 James Turner <[email protected]>
4 * SPDX_FileComment: Defins a unified binary cache for navigation data, parsed from text/XMl sources
5 * SPDX-License-Identifier: GPL-2.0-or-later
6 */
7
8 #include "config.h"
9
10 #include "NavDataCache.hxx"
11
12 // std
13 #include <cstddef> // for std::size_t
14 #include <map>
15 #include <cstring> // for memcoy
16 #include <cassert>
17 #include <stdint.h> // for int64_t
18 #include <sstream> // for std::ostringstream
19 #include <mutex>
20 #include <utility>
21 #include <vector>
22
23 #ifdef SYSTEM_SQLITE
24 // the standard sqlite3.h doesn't give a way to set SQLITE_UINT64_TYPE,
25 // so we have to hope sizeof(int64_t) matches sizeof(sqlite3_int64).
26 // otherwise things will go bad quickly.
27 #include "sqlite3.h"
28 #else
29 // to ensure compatability between sqlite3_int64 and PositionedID,
30 // force the type used by sqlite to match PositionedID explicitly
31 #define SQLITE_INT64_TYPE int64_t
32 #define SQLITE_UINT64_TYPE uint64_t
33
34 #include "fg_sqlite3.h"
35 #endif
36
37 // SimGear
38 #include <simgear/bucket/newbucket.hxx>
39 #include <simgear/debug/logstream.hxx>
40 #include <simgear/io/sg_file.hxx>
41 #include <simgear/misc/sg_dir.hxx>
42 #include <simgear/misc/sg_path.hxx>
43 #include <simgear/misc/strutils.hxx>
44 #include <simgear/sg_inlines.h>
45 #include <simgear/structure/exception.hxx>
46 #include <simgear/threads/SGThread.hxx>
47
48 #include "CacheSchema.h"
49 #include "PositionedOctree.hxx"
50 #include "fix.hxx"
51 #include "markerbeacon.hxx"
52 #include "navrecord.hxx"
53 #include "poidb.hxx"
54 #include <ATC/CommStation.hxx>
55 #include <Airports/airport.hxx>
56 #include <Airports/apt_loader.hxx>
57 #include <Airports/gnnode.hxx>
58 #include <Airports/parking.hxx>
59 #include <Airports/runways.hxx>
60 #include <GUI/MessageBox.hxx>
61 #include <Main/MultipleInstanceLock.hxx>
62 #include <Main/fg_props.hxx>
63 #include <Main/globals.hxx>
64 #include <Main/options.hxx>
65 #include <Main/sentryIntegration.hxx>
66 #include <Navaids/airways.hxx>
67 #include <Navaids/fixlist.hxx>
68 #include <Navaids/navdb.hxx>
69
70 using std::string;
71
72 #define SG_NAVCACHE SG_NAVAID
73 //#define LAZY_OCTREE_UPDATES 1
74
75 namespace {
76
77 const int MAX_RETRIES = 10;
78
79 const int CACHE_SIZE_KBYTES= 32 * 1024;
80
81 // bind a std::string to a sqlite statement. The std::string must live the
82 // entire duration of the statement execution - do not pass a temporary
83 // std::string, or the compiler may delete it, freeing the C-string storage,
84 // and causing subtle memory corruption bugs!
85 void sqlite_bind_stdstring(sqlite3_stmt* stmt, int value, const std::string& s)
86 {
87 sqlite3_bind_text(stmt, value, s.c_str(), s.length(), SQLITE_STATIC);
88 }
89
90 // variant of the above, which does not care about the lifetime of the
91 // passed std::string
92 void sqlite_bind_temp_stdstring(sqlite3_stmt* stmt, int value, const std::string& s)
93 {
94 sqlite3_bind_text(stmt, value, s.c_str(), s.length(), SQLITE_TRANSIENT);
95 }
96
97 typedef sqlite3_stmt* sqlite3_stmt_ptr;
98
99 void f_distanceCartSqrFunction(sqlite3_context* ctx, int argc, sqlite3_value* argv[])
100 {
101 if (argc != 6) {
102 return;
103 }
104
105 SGVec3d posA(sqlite3_value_double(argv[0]),
106 sqlite3_value_double(argv[1]),
107 sqlite3_value_double(argv[2]));
108
109 SGVec3d posB(sqlite3_value_double(argv[3]),
110 sqlite3_value_double(argv[4]),
111 sqlite3_value_double(argv[5]));
112 sqlite3_result_double(ctx, distSqr(posA, posB));
113 }
114
115
116 static string cleanRunwayNo(const string& aRwyNo)
117 {
118 if (aRwyNo[0] == 'x') {
119 return string(); // no ident for taxiways
120 }
121
122 string result(aRwyNo);
123 // canonicalise runway ident to two digits and one optional uppercase letter
124 if ((aRwyNo.size() == 1) || !isdigit(aRwyNo[1])) {
125 result = "0" + aRwyNo;
126 }
127
128 // trim off trailing garbage
129 if (result.size() > 2) {
130 char suffix = toupper(result[2]);
131 if (suffix == 'X') {
132 result = result.substr(0, 2);
133 }
134 }
135
136 return result;
137 }
138
139 class AbandonCacheException : public sg_exception
140 {
141 public:
142 AbandonCacheException() : sg_exception("Cache build cancelled", {}, {}, false)
143 {
144 }
145 };
146
147 } // anonymous namespace
148
149 namespace flightgear
150 {
151
152 /**
153 * Thread encapsulating a cache rebuild. This is not used to parallelise
154 * the rebuild - we must still wait until completion before doing other
155 * startup, since many things rely on a complete cache. The thread is used
156 * so we don't block the main event loop for an unacceptable duration,
157 * which causes 'not responding' / spinning beachballs on Windows & Mac
158 */
159 class RebuildThread : public SGThread
160 {
161 public:
162 RebuildThread(NavDataCache* cache) : _cache(cache)
163 {
164 auto exl = ExclusiveInstanceLock::instance();
165 if (exl) {
166 exl->updateReason("navcache-rebuild");
167 }
168 }
169
170 ~RebuildThread()
171 {
172 join();
173 }
174
175 bool isFinished() const
176 {
177 std::lock_guard<std::mutex> g(_lock);
178 return _isFinished;
179 }
180
181 void run() override
182 {
183 SGTimeStamp st;
184 st.stamp();
185 _cache->doRebuild();
186 SG_LOG(SG_NAVCACHE, SG_INFO, "cache rebuild took:" << st.elapsedMSec() << "msec");
187
188 std::lock_guard<std::mutex> g(_lock);
189 _isFinished = true;
190 _phase = NavDataCache::REBUILD_DONE;
191 }
192
193 NavDataCache::RebuildPhase currentPhase() const
194 {
195 NavDataCache::RebuildPhase ph;
196 std::lock_guard<std::mutex> g(_lock);
197 ph = _phase;
198 return ph;
199 }
200
201 unsigned int completionPercent() const
202 {
203 unsigned int perc = 0;
204 std::lock_guard<std::mutex> g(_lock);
205 perc = _completionPercent;
206 return perc;
207 }
208
209 void setProgress(NavDataCache::RebuildPhase ph, unsigned int percent)
210 {
211 std::lock_guard<std::mutex> g(_lock);
212 _phase = ph;
213 _completionPercent = percent;
214 }
215
216 private:
217 NavDataCache* _cache;
218 NavDataCache::RebuildPhase _phase = NavDataCache::REBUILD_UNKNOWN;
219 unsigned int _completionPercent = 0;
220 mutable std::mutex _lock;
221 bool _isFinished = false;
222 };
223
224 ////////////////////////////////////////////////////////////////////////////
225
226 typedef std::map<PositionedID, FGPositionedRef> PositionedCache;
227
228 class AirportTower : public FGPositioned
229 {
230 public:
231 AirportTower(PositionedID& guid, PositionedID airport,
232 const string& ident, const SGGeod& pos) :
233 FGPositioned(guid, FGPositioned::TOWER, ident, pos)
234 {
235 SG_UNUSED(airport);
236 }
237 };
238
239 // useful for debugging 'hanging' queries: look for a statement
240 // which starts but never completes
241 #if 0
242 int traceCallback(unsigned int traceCode, void* ctx, void* p, void* x)
243 {
244 if (traceCode == SQLITE_TRACE_STMT) {
245 SG_LOG(SG_NAVCACHE, SG_WARN, "step:" << p << " text=" << (char*)x);
246 }
247 else if (traceCode == SQLITE_TRACE_PROFILE) {
248 int64_t* nanoSecs = (int64_t*)x;
249 SG_LOG(SG_NAVCACHE, SG_WARN, "profile:" << p << " took " << *nanoSecs);
250 }
251
252 return 0;
253 }
254 #endif
255
256 class NavDataCache::NavDataCachePrivate
257 {
258 public:
259 NavDataCachePrivate(const SGPath& p, NavDataCache* o) :
260 outer(o),
261 db(nullptr),
262 path(p),
263 readOnly(false),
264 cacheHits(0),
265 cacheMisses(0),
266 transactionLevel(0),
267 transactionAborted(false)
268 {
269 }
270
271 ~NavDataCachePrivate()
272 {
273 close();
274 }
275
276 void init()
277 {
278 SG_LOG(SG_NAVCACHE, SG_INFO, "NavCache at:" << path);
279
280 readOnly = fgGetBool("/sim/fghome-readonly", false);
281 SG_LOG(SG_NAVCACHE, SG_INFO, "NavCache read-only flags is:" << readOnly);
282
283 if (!readOnly && !path.canWrite()) {
284 throw sg_exception("Nav-cache file is not writeable");
285 }
286
287 int openFlags = readOnly ? SQLITE_OPEN_READONLY :
288 (SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);
289 std::string pathUtf8 = path.utf8Str();
290 int result = sqlite3_open_v2(pathUtf8.c_str(), &db, openFlags, NULL);
291 if (result == SQLITE_MISUSE) {
292 // docs state sqlite3_errmsg may not work in this case
293 SG_LOG(SG_NAVCACHE, SG_WARN, "Failed to open DB at " << path << ": misuse of Sqlite API");
294 throw sg_exception("Navcache failed to open: Sqlite API misuse");
295 } else if (result != SQLITE_OK) {
296 std::string errMsg = sqlite3_errmsg(db);
297 SG_LOG(SG_NAVCACHE, SG_WARN, "Failed to open DB at " << path << " with error:\n\t" << errMsg);
298 throw sg_exception("Navcache failed to open:" + errMsg);
299 }
300
301 if (!readOnly && (sqlite3_db_readonly(db, nullptr) != 0)) {
302 throw sg_exception("Nav-cache file opened but is not writeable");
303 }
304
305 // enable tracing for debugging stuck queries
306 // sqlite3_trace_v2(db, SQLITE_TRACE_STMT | SQLITE_TRACE_PROFILE, traceCallback, this);
307
308 sqlite3_stmt_ptr checkTables =
309 prepare("SELECT count(*) FROM sqlite_master WHERE name='properties'");
310
311 sqlite3_create_function(db, "distanceCartSqr", 6, SQLITE_ANY, NULL,
312 f_distanceCartSqrFunction, NULL, NULL);
313
314 execSelect(checkTables);
315 bool didCreate = false;
316 if (!readOnly && (sqlite3_column_int(checkTables, 0) == 0)) {
317 SG_LOG(SG_NAVCACHE, SG_INFO, "will create tables");
318 initTables();
319 didCreate = true;
320 }
321
322 reset(checkTables);
323
324 initTemporaryTables();
325
326 readPropertyQuery = prepare("SELECT value FROM properties WHERE key=?");
327 writePropertyQuery = prepare("INSERT INTO properties (key, value) VALUES (?,?)");
328 clearProperty = prepare("DELETE FROM properties WHERE key=?1");
329
330 if (didCreate) {
331 writeIntProperty("schema-version", SCHEMA_VERSION);
332 } else {
333 int schemaVersion = outer->readIntProperty("schema-version");
334 if (schemaVersion != SCHEMA_VERSION) {
335 SG_LOG(SG_NAVCACHE, SG_INFO, "Navcache schema mismatch, will rebuild");
336 throw sg_exception("Navcache schema has changed", {}, {}, false);
337 }
338 }
339
340 // see http://www.sqlite.org/pragma.html#pragma_cache_size
341 // for the details, small cache would cause thrashing.
342 std::ostringstream q;
343 q << "PRAGMA cache_size=-" << CACHE_SIZE_KBYTES << ";";
344 runSQL(q.str());
345 prepareQueries();
346 }
347
348 void close()
349 {
350 for (sqlite3_stmt_ptr stmt : prepared) {
351 sqlite3_finalize(stmt);
352 }
353 prepared.clear();
354 sqlite3_close(db);
355 }
356
357 void checkCacheFile()
358 {
359 SG_LOG(SG_NAVCACHE, SG_INFO, "running DB integrity check");
360 SGTimeStamp st;
361 st.stamp();
362
363 sqlite3_stmt_ptr stmt = prepare("PRAGMA quick_check(1)");
364 if (!execSelect(stmt)) {
365 throw sg_exception("DB integrity check failed to run");
366 }
367
368 string v = (char*) sqlite3_column_text(stmt, 0);
369 if (v != "ok") {
370 throw sg_exception("DB integrity check returned:" + v);
371 }
372
373 SG_LOG(SG_NAVCACHE, SG_INFO, "NavDataCache integrity check took:" << st.elapsedMSec());
374 finalize(stmt);
375 }
376
377 bool isCachedFileModified(const SGPath& path, bool verbose);
378 void findDatFiles(NavDataCache::DatFileType datFileType);
379 bool areDatFilesModified(
380 NavDataCache::DatFileType datFileType,
381 bool verbose);
382
383
384 sqlite3_stmt_ptr prepareSQL(const std::string& sql)
385 {
386 sqlite3_stmt_ptr stmt;
387 int result = sqlite3_prepare_v2(db, sql.c_str(), sql.length(), &stmt, nullptr);
388 int retries = 0;
389 int retryMSec = 1;
390
391 while (result == SQLITE_BUSY) {
392 if (retries > MAX_RETRIES) {
393 break;
394 }
395
396 ++retries;
397 SGTimeStamp::sleepForMSec(retryMSec);
398 retryMSec = retryMSec << 1; // double each time
399 // try again
400 result = sqlite3_prepare_v2(db, sql.c_str(), sql.length(), &stmt, nullptr);
401 }
402
403 if (result == SQLITE_OK) {
404 return stmt; // common case, all good
405 }
406
407 string errMsg;
408 if (result == SQLITE_MISUSE) {
409 errMsg = "Sqlite API abuse";
410 SG_LOG(SG_NAVCACHE, SG_ALERT, "Sqlite API abuse");
411 } else {
412 errMsg = sqlite3_errmsg(db);
413 SG_LOG(SG_NAVCACHE, SG_ALERT, "Sqlite error:" << errMsg << " running:\n\t" << sql);
414 }
415
416 throw sg_exception("Sqlite error:" + errMsg, sql);
417 }
418
419 void runSQL(const string& sql)
420 {
421 sqlite3_stmt_ptr stmt = prepareSQL(sql);
422 try {
423 execSelect(stmt);
424 } catch (sg_exception&) {
425 sqlite3_finalize(stmt);
426 throw; // re-throw
427 }
428
429 sqlite3_finalize(stmt);
430 }
431
432 sqlite3_stmt_ptr prepare(const string& sql)
433 {
434 sqlite3_stmt_ptr stmt = prepareSQL(sql);
435 prepared.push_back(stmt);
436 return stmt;
437 }
438
439 void finalize(sqlite3_stmt_ptr s)
440 {
441 StmtVec::iterator it = std::find(prepared.begin(), prepared.end(), s);
442 if (it == prepared.end()) {
443 throw sg_exception("Finalising statement that was not prepared");
444 }
445
446 prepared.erase(it);
447 sqlite3_finalize(s);
448 }
449
450 void reset(sqlite3_stmt_ptr stmt)
451 {
452 assert(stmt);
453 if (sqlite3_reset(stmt) != SQLITE_OK) {
454 string errMsg = sqlite3_errmsg(db);
455 SG_LOG(SG_NAVCACHE, SG_ALERT, "Sqlite error resetting:" << errMsg);
456 throw sg_exception("Sqlite error resetting:" + errMsg, sqlite3_sql(stmt));
457 }
458 }
459
460 bool execSelect(sqlite3_stmt_ptr stmt)
461 {
462 return stepSelect(stmt);
463 }
464
465 bool stepSelect(sqlite3_stmt_ptr stmt)
466 {
467 if (abandonCache)
468 throw AbandonCacheException{};
469
470 int retries = 0;
471 int result;
472 int retryMSec = 10;
473
474 while (retries < MAX_RETRIES) {
475 result = sqlite3_step(stmt);
476 if (result == SQLITE_ROW) {
477 return true; // at least one result row
478 }
479
480 if (result == SQLITE_DONE) {
481 return false; // no result rows
482 }
483
484 if (result != SQLITE_BUSY) {
485 break;
486 }
487
488 SG_LOG(SG_NAVCACHE, SG_ALERT, "NavCache contention on select, will retry:" << retries);
489 SGTimeStamp::sleepForMSec(retryMSec);
490 retryMSec *= 2; // double the back-off time, each time
491 } // of retry loop for DB locked
492
493 if (retries >= MAX_RETRIES) {
494 SG_LOG(SG_NAVCACHE, SG_ALERT, "exceeded maximum number of SQLITE_BUSY retries");
495 return false;
496 }
497
498 string errMsg;
499 if (result == SQLITE_MISUSE) {
500 errMsg = "Sqlite API abuse";
501 SG_LOG(SG_NAVCACHE, SG_ALERT, "Sqlite API abuse");
502 } else {
503 errMsg = sqlite3_errmsg(db);
504 SG_LOG(SG_NAVCACHE, SG_ALERT, "Sqlite error:" << errMsg << " (" << result
505 << ") while running:\n\t" << sqlite3_sql(stmt));
506 }
507
508 throw sg_exception("Sqlite error:" + errMsg, sqlite3_sql(stmt));
509 }
510
511 void execSelect1(sqlite3_stmt_ptr stmt)
512 {
513 if (!execSelect(stmt)) {
514 SG_LOG(SG_NAVCACHE, SG_WARN, "empty SELECT running:\n\t" << sqlite3_sql(stmt));
515 flightgear::sentryReportException("empty SELECT running:" + std::string{sqlite3_sql(stmt)});
516 throw sg_exception("no results returned for select", sqlite3_sql(stmt));
517 }
518 }
519
520 sqlite3_int64 execInsert(sqlite3_stmt_ptr stmt)
521 {
522 execSelect(stmt);
523 sqlite3_int64 rowid = sqlite3_last_insert_rowid(db);
524 reset(stmt);
525 return rowid;
526 }
527
528 void execUpdate(sqlite3_stmt_ptr stmt)
529 {
530 execSelect(stmt);
531 reset(stmt);
532 }
533
534 void initTables()
535 {
536 string_list commands = simgear::strutils::split(SCHEMA_SQL, ";");
537 for (std::string sql : commands) {
538 if (sql.empty()) {
539 continue;
540 }
541
542 runSQL(sql);
543 } // of commands in scheme loop
544 }
545
546 void initTemporaryTables()
547 {
548 const auto commands = simgear::strutils::split(TEMPORARY_SCHEMA_SQL, ";");
549 for (auto sql : commands) {
550 if (sql.empty()) {
551 continue;
552 }
553
554 runSQL(sql);
555 } // of commands in scheme loop
556 }
557
558 void prepareQueries()
559 {
560 writePropertyMulti = prepare("INSERT INTO properties (key, value) VALUES(?1,?2)");
561
562 beginTransactionStmt = prepare("BEGIN");
563 commitTransactionStmt = prepare("COMMIT");
564 rollbackTransactionStmt = prepare("ROLLBACK");
565
566
567 #define POSITIONED_COLS "guid, type, ident, name, airport, lon, lat, elev_m, octree_node"
568 #define AND_TYPED "AND type>=?2 AND type <=?3"
569 statCacheCheck = prepare("SELECT stamp, sha FROM stat_cache WHERE path=?");
570 stampFileCache = prepare("INSERT OR REPLACE INTO stat_cache "
571 "(path, stamp, sha) VALUES (?,?, ?)");
572
573 loadPositioned = prepare("SELECT " POSITIONED_COLS " FROM all_positioned WHERE guid=?");
574 loadAirportStmt = prepare("SELECT scenery_path, has_metar FROM airport WHERE rowid=?");
575 loadNavaid = prepare("SELECT range_nm, freq, multiuse, runway, colocated FROM navaid WHERE rowid=?");
576 loadCommStation = prepare("SELECT freq_khz, range_nm FROM comm WHERE rowid=?");
577 loadRunwayStmt = prepare("SELECT heading, length_ft, width_m, surface, displaced_threshold,"
578 "stopway, reciprocal, ils FROM runway WHERE rowid=?1");
579
580 getAirportItems = prepare("SELECT guid FROM all_positioned WHERE airport=?1 " AND_TYPED);
581
582
583 setAirportMetar = prepare("UPDATE airport SET has_metar=?2 WHERE rowid="
584 "(SELECT rowid FROM positioned WHERE ident=?1 AND type>=?3 AND type <=?4)");
585 sqlite3_bind_int(setAirportMetar, 3, FGPositioned::AIRPORT);
586 sqlite3_bind_int(setAirportMetar, 4, FGPositioned::SEAPORT);
587
588 setRunwayReciprocal = prepare("UPDATE runway SET reciprocal=?2 WHERE rowid=?1");
589 setRunwayILS = prepare("UPDATE runway SET ils=?2 WHERE rowid=?1");
590 setNavaidColocated = prepare("UPDATE navaid SET colocated=?2 WHERE rowid=?1");
591
592 insertPositionedQuery = prepare("INSERT INTO positioned "
593 "(type, ident, name, airport, lon, lat, elev_m, octree_node, "
594 "cart_x, cart_y, cart_z)"
595 " VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)");
596
597 insertTempPosQuery = prepare("INSERT INTO temp_positioned "
598 "(rowid, type, ident, name, lon, lat, elev_m, "
599 "cart_x, cart_y, cart_z)"
600 " VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)");
601
602 updatePosition = prepare("UPDATE positioned SET lon=?2, lat=?3, elev_m=?4, octree_node=?5, "
603 "cart_x=?6, cart_y=?7, cart_z=?8 WHERE rowid=?1");
604 updateTempPos = prepare("UPDATE temp_positioned SET lon=?2, lat=?3, elev_m=?4, octree_node=?5, "
605 "cart_x=?6, cart_y=?7, cart_z=?8 WHERE rowid=?1");
606
607 insertAirport = prepare("INSERT INTO airport (rowid, scenery_path, has_metar) VALUES (?, ?, ?)");
608 insertNavaid = prepare("INSERT INTO navaid (rowid, freq, range_nm, multiuse, runway, colocated)"
609 " VALUES (?1, ?2, ?3, ?4, ?5, ?6)");
610
611 insertCommStation = prepare("INSERT INTO comm (rowid, freq_khz, range_nm)"
612 " VALUES (?, ?, ?)");
613 insertRunway = prepare("INSERT INTO runway "
614 "(rowid, heading, length_ft, width_m, surface, displaced_threshold, stopway, reciprocal)"
615 " VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)");
616 runwayLengthFtQuery = prepare("SELECT length_ft FROM runway WHERE rowid=?1");
617
618 removePositionedQuery = prepare("DELETE FROM positioned WHERE rowid=?1");
619 removeTempPosQuery = prepare("DELETE FROM temp_positioned WHERE rowid=?1");
620
621 // query statement
622 findClosestWithIdent = prepare("SELECT guid FROM all_positioned WHERE ident=?1 " AND_TYPED " ORDER BY distanceCartSqr(cart_x, cart_y, cart_z, ?4, ?5, ?6)");
623
624 findCommByFreq = prepare("SELECT positioned.rowid FROM positioned, comm WHERE "
625 "positioned.rowid=comm.rowid AND freq_khz=?1 "
626 AND_TYPED " ORDER BY distanceCartSqr(cart_x, cart_y, cart_z, ?4, ?5, ?6)");
627
628 findNavsByFreq = prepare("SELECT positioned.rowid FROM positioned, navaid WHERE "
629 "positioned.rowid=navaid.rowid "
630 "AND navaid.freq=?1 " AND_TYPED
631 " ORDER BY distanceCartSqr(cart_x, cart_y, cart_z, ?4, ?5, ?6)");
632
633 findNavsByFreqNoPos = prepare("SELECT positioned.rowid FROM positioned, navaid WHERE "
634 "positioned.rowid=navaid.rowid AND freq=?1 " AND_TYPED);
635
636 findNavaidForRunway = prepare("SELECT positioned.rowid FROM positioned, navaid WHERE "
637 "positioned.rowid=navaid.rowid AND runway=?1 AND type=?2");
638
639 // for an octree branch, return the child octree nodes which exist,
640 // described as a bit-mask
641 getOctreeChildren = prepare("SELECT children FROM octree WHERE rowid=?1");
642
643 #ifdef LAZY_OCTREE_UPDATES
644 updateOctreeChildren = prepare("UPDATE octree SET children=?2 WHERE rowid=?1");
645 #else
646 // mask the new child value into the existing one
647 updateOctreeChildren = prepare("UPDATE octree SET children=(?2 | children) WHERE rowid=?1");
648 #endif
649
650 // define a new octree node (with no children)
651 insertOctree = prepare("INSERT INTO octree (rowid, children) VALUES (?1, 0)");
652
653 getOctreeLeafChildren = prepare("SELECT rowid, type FROM positioned WHERE octree_node=?1");
654
655 searchAirports = prepare("SELECT ident, name FROM positioned WHERE (name LIKE ?1 OR ident LIKE ?1) " AND_TYPED
656 // prioritize entries with matching ICAO
657 " ORDER BY (ident LIKE ?1) DESC");
658 sqlite3_bind_int(searchAirports, 2, FGPositioned::AIRPORT);
659 sqlite3_bind_int(searchAirports, 3, FGPositioned::SEAPORT);
660
661 getAllAirports = prepare("SELECT ident, name FROM positioned WHERE type>=?1 AND type <=?2");
662 sqlite3_bind_int(getAllAirports, 1, FGPositioned::AIRPORT);
663 sqlite3_bind_int(getAllAirports, 2, FGPositioned::SEAPORT);
664
665
666 getAirportItemByIdent = prepare("SELECT guid FROM all_positioned WHERE airport=?1 AND ident=?2 AND type=?3");
667
668 findAirportRunway = prepare("SELECT airport, rowid FROM positioned WHERE ident=?2 AND type=?3 AND airport="
669 "(SELECT rowid FROM positioned WHERE type=?4 AND ident=?1)");
670 sqlite3_bind_int(findAirportRunway, 3, FGPositioned::RUNWAY);
671 sqlite3_bind_int(findAirportRunway, 4, FGPositioned::AIRPORT);
672
673 // three-way join to get the navaid ident and runway ident in a single select.
674 // we're joining positioned to itself by the navaid runway, with the complication
675 // that we need to join the navaids table to get the runway ID.
676 // we also need to filter by type to excluse glideslope (GS) matches
677 findILS = prepare("SELECT nav.rowid FROM positioned AS nav, positioned AS rwy, navaid WHERE "
678 "nav.ident=?1 AND nav.airport=?2 AND rwy.ident=?3 "
679 "AND rwy.rowid = navaid.runway AND navaid.rowid=nav.rowid "
680 "AND (nav.type=?4 OR nav.type=?5)");
681
682 sqlite3_bind_int(findILS, 4, FGPositioned::ILS);
683 sqlite3_bind_int(findILS, 5, FGPositioned::LOC);
684
685 // airways
686 findAirwayNet = prepare("SELECT rowid FROM airway WHERE network=?1 AND ident=?2");
687 findAirway = prepare("SELECT rowid FROM airway WHERE ident=?1");
688 loadAirway = prepare("SELECT ident, network FROM airway WHERE rowid=?1");
689 insertAirway = prepare("INSERT INTO airway (ident, network) "
690 "VALUES (?1, ?2)");
691
692 insertAirwayEdge = prepare("INSERT INTO airway_edge (network, airway, a, b) "
693 "VALUES (?1, ?2, ?3, ?4)");
694
695 isPosInAirway = prepare("SELECT rowid FROM airway_edge WHERE network=?1 AND (a=?2 OR b=?2)");
696
697 airwayEdgesFrom = prepare("SELECT airway, b FROM airway_edge WHERE network=?1 AND a=?2");
698 airwayEdgesTo = prepare("SELECT airway, a FROM airway_edge WHERE network=?1 AND b=?2");
699 airwayEdges = prepare("SELECT a, b FROM airway_edge WHERE airway=?1");
700 }
701
702 void writeIntProperty(const string& key, int value)
703 {
704 if (!readOnly){
705 sqlite_bind_stdstring(clearProperty, 1, key);
706 execUpdate(clearProperty);
707
708 sqlite_bind_stdstring(writePropertyQuery, 1, key);
709 sqlite3_bind_int(writePropertyQuery, 2, value);
710 execUpdate(writePropertyQuery);
711 }
712 }
713
714
715 FGPositioned* loadById(sqlite_int64 rowId, sqlite3_int64& aptId);
716
717 FGAirport* loadAirport(sqlite_int64 rowId,
718 FGPositioned::Type ty,
719 const string& id, const string& name, const SGGeod& pos)
720 {
721 sqlite3_bind_int64(loadAirportStmt, 1, rowId);
722 execSelect1(loadAirportStmt);
723 SGPath sceneryPath{(char *) sqlite3_column_text(loadAirportStmt, 0)};
724 bool hasMetar = (sqlite3_column_int(loadAirportStmt, 1) > 0);
725 reset(loadAirportStmt);
726
727 return new FGAirport(rowId, id, pos, name, hasMetar, ty,
728 std::move(sceneryPath));
729 }
730
731 FGRunwayBase* loadRunway(sqlite3_int64 rowId, FGPositioned::Type ty,
732 const string& id, const SGGeod& pos, PositionedID apt)
733 {
734 sqlite3_bind_int(loadRunwayStmt, 1, rowId);
735 execSelect1(loadRunwayStmt);
736
737 double heading = sqlite3_column_double(loadRunwayStmt, 0);
738 double lengthM = sqlite3_column_int(loadRunwayStmt, 1);
739 double widthM = sqlite3_column_double(loadRunwayStmt, 2);
740 int surface = sqlite3_column_int(loadRunwayStmt, 3);
741
742 if (ty == FGPositioned::TAXIWAY) {
743 reset(loadRunwayStmt);
744 return new FGTaxiway(rowId, id, pos, heading, lengthM, widthM, surface, apt);
745 } else if (ty == FGPositioned::HELIPAD) {
746 reset(loadRunwayStmt);
747 return new FGHelipad(rowId, apt, id, pos, heading, lengthM, widthM, surface);
748 } else {
749 double displacedThreshold = sqlite3_column_double(loadRunwayStmt, 4);
750 double stopway = sqlite3_column_double(loadRunwayStmt, 5);
751 PositionedID reciprocal = sqlite3_column_int64(loadRunwayStmt, 6);
752 PositionedID ils = sqlite3_column_int64(loadRunwayStmt, 7);
753 FGRunway* r = new FGRunway(rowId, apt, id, pos, heading, lengthM, widthM,
754 displacedThreshold, stopway, surface);
755
756 if (reciprocal > 0) {
757 r->setReciprocalRunway(reciprocal);
758 }
759
760 if (ils > 0) {
761 r->setILS(ils);
762 }
763
764 reset(loadRunwayStmt);
765 return r;
766 }
767 }
768
769 CommStation* loadComm(sqlite3_int64 rowId, FGPositioned::Type ty,
770 const string& id, const string& name,
771 const SGGeod& pos,
772 PositionedID airport)
773 {
774 SG_UNUSED(id);
775
776 sqlite3_bind_int64(loadCommStation, 1, rowId);
777 execSelect1(loadCommStation);
778
779 int range = sqlite3_column_int(loadCommStation, 0);
780 int freqKhz = sqlite3_column_int(loadCommStation, 1);
781 reset(loadCommStation);
782
783 CommStation* c = new CommStation(rowId, name, ty, pos, freqKhz, range);
784 c->setAirport(airport);
785 return c;
786 }
787
788 FGPositioned* loadNav(sqlite3_int64 rowId,
789 FGPositioned::Type ty, const string& id,
790 const string& name, const SGGeod& pos)
791 {
792 sqlite3_bind_int64(loadNavaid, 1, rowId);
793 execSelect1(loadNavaid);
794
795 PositionedID runway = sqlite3_column_int64(loadNavaid, 3);
796 // marker beacons are light-weight
797 if ((ty == FGPositioned::OM) || (ty == FGPositioned::IM) ||
798 (ty == FGPositioned::MM))
799 {
800 reset(loadNavaid);
801 return new FGMarkerBeaconRecord(rowId, ty, runway, pos);
802 }
803
804 int rangeNm = sqlite3_column_int(loadNavaid, 0),
805 freq = sqlite3_column_int(loadNavaid, 1);
806 double mulituse = sqlite3_column_double(loadNavaid, 2);
807 PositionedID colocated = sqlite3_column_int64(loadNavaid, 4);
808 reset(loadNavaid);
809
810 FGNavRecord* n =
811 (ty == FGPositioned::MOBILE_TACAN)
812 ? new FGMobileNavRecord
813 (rowId, ty, id, name, pos, freq, rangeNm, mulituse, runway)
814 : new FGNavRecord
815 (rowId, ty, id, name, pos, freq, rangeNm, mulituse, runway);
816
817 if (colocated)
818 n->setColocatedDME(colocated);
819
820 return n;
821 }
822
823 PositionedID insertPositioned(FGPositioned::Type ty, const string& ident,
824 const string& name, const SGGeod& pos, PositionedID apt,
825 bool spatialIndex)
826 {
827 if (abandonCache)
828 throw AbandonCacheException{};
829
830 SGVec3d cartPos(SGVec3d::fromGeod(pos));
831
832 sqlite3_bind_int(insertPositionedQuery, 1, ty);
833 sqlite_bind_stdstring(insertPositionedQuery, 2, ident);
834 sqlite_bind_stdstring(insertPositionedQuery, 3, name);
835 sqlite3_bind_int64(insertPositionedQuery, 4, apt);
836 sqlite3_bind_double(insertPositionedQuery, 5, pos.getLongitudeDeg());
837 sqlite3_bind_double(insertPositionedQuery, 6, pos.getLatitudeDeg());
838 sqlite3_bind_double(insertPositionedQuery, 7, pos.getElevationM());
839
840 if (spatialIndex) {
841 Octree::Leaf* octreeLeaf = Octree::globalPersistentOctree()->findLeafForPos(cartPos);
842 assert(intersects(octreeLeaf->bbox(), cartPos));
843 sqlite3_bind_int64(insertPositionedQuery, 8, octreeLeaf->guid());
844 } else {
845 sqlite3_bind_null(insertPositionedQuery, 8);
846 }
847
848 sqlite3_bind_double(insertPositionedQuery, 9, cartPos.x());
849 sqlite3_bind_double(insertPositionedQuery, 10, cartPos.y());
850 sqlite3_bind_double(insertPositionedQuery, 11, cartPos.z());
851
852 PositionedID r = execInsert(insertPositionedQuery);
853 return r;
854 }
855
856
857 PositionedID insertTemporaryPositioned(PositionedID guid, FGPositioned::Type ty, const string& ident,
858 const string& name, const SGGeod& pos,
859 bool spatialIndex)
860 {
861 if (abandonCache)
862 throw AbandonCacheException{};
863
864 SGVec3d cartPos(SGVec3d::fromGeod(pos));
865
866 sqlite3_bind_int64(insertTempPosQuery, 1, guid);
867 sqlite3_bind_int(insertTempPosQuery, 2, ty);
868 sqlite_bind_stdstring(insertTempPosQuery, 3, ident);
869 sqlite_bind_stdstring(insertTempPosQuery, 4, name);
870 sqlite3_bind_double(insertTempPosQuery, 5, pos.getLongitudeDeg());
871 sqlite3_bind_double(insertTempPosQuery, 6, pos.getLatitudeDeg());
872 sqlite3_bind_double(insertTempPosQuery, 7, pos.getElevationM());
873 sqlite3_bind_double(insertTempPosQuery, 8, cartPos.x());
874 sqlite3_bind_double(insertTempPosQuery, 9, cartPos.y());
875 sqlite3_bind_double(insertTempPosQuery, 10, cartPos.z());
876
877 execInsert(insertTempPosQuery);
878
879 // insert into the transient octree
880 Octree::Leaf* octreeLeaf = Octree::globalTransientOctree()->findLeafForPos(cartPos);
881 octreeLeaf->insertChild(ty, guid);
882
883 return guid;
884 }
885
886 FGPositionedList findAllByString(const string& s, const string& column,
887 FGPositioned::Filter* filter, bool exact)
888 {
889 string query = s;
890 if (!exact) query += "%";
891
892 // build up SQL query text
893 string matchTerm = exact ? "=?1" : " LIKE ?1";
894 string sql = "SELECT guid FROM all_positioned WHERE " + column + matchTerm;
895 if (filter) {
896 sql += " " AND_TYPED;
897 }
898
899 // find or prepare a suitable statement frrm the SQL
900 sqlite3_stmt_ptr stmt = findByStringDict[sql];
901 if (!stmt) {
902 stmt = prepare(sql);
903 findByStringDict[sql] = stmt;
904 }
905
906 sqlite_bind_stdstring(stmt, 1, query);
907 if (filter) {
908 sqlite3_bind_int(stmt, 2, filter->minType());
909 sqlite3_bind_int(stmt, 3, filter->maxType());
910 }
911
912 std::vector<PositionedID> guids;
913 // Run the prepared SQL statement
914 while (stepSelect(stmt)) {
915 guids.push_back(sqlite3_column_int64(stmt, 0));
916 }
917
918 // This must be done *before* outer->loadById(), otherwise the same
919 // prepared SQL statement could be executed reentrantly from there.
920 reset(stmt);
921
922 FGPositionedList result;
923 for (const auto guid: guids) {
924 FGPositioned* pos = outer->loadById(guid);
925 if (!filter || filter->pass(pos)) {
926 result.push_back(pos);
927 }
928 }
929
930 return result;
931 }
932
933 PositionedIDVec selectIds(sqlite3_stmt_ptr query)
934 {
935 PositionedIDVec result;
936 while (stepSelect(query)) {
937 result.push_back(sqlite3_column_int64(query, 0));
938 }
939 reset(query);
940 return result;
941 }
942
943 double runwayLengthFt(PositionedID rwy)
944 {
945 sqlite3_bind_int64(runwayLengthFtQuery, 1, rwy);
946 execSelect1(runwayLengthFtQuery);
947 double length = sqlite3_column_double(runwayLengthFtQuery, 0);
948 reset(runwayLengthFtQuery);
949 return length;
950 }
951
952 void flushDeferredOctreeUpdates()
953 {
954 for (Octree::Branch* nd : deferredOctreeUpdates) {
955 sqlite3_bind_int64(updateOctreeChildren, 1, nd->guid());
956 sqlite3_bind_int(updateOctreeChildren, 2, nd->childMask());
957 execUpdate(updateOctreeChildren);
958 }
959
960 deferredOctreeUpdates.clear();
961 }
962
963 void removePositioned(PositionedID rowid)
964 {
965 auto stmt = rowid < 0 ? removeTempPosQuery : removePositionedQuery;
966 sqlite3_bind_int64(stmt, 1, rowid);
967 execUpdate(stmt);
968 reset(stmt);
969 }
970
971 NavDataCache* outer;
972 sqlite3* db;
973 SGPath path;
974 bool readOnly;
975
976 // flag set during shutdown: allows us to abandon queries, etc
977 // if exit is requested during a rebuild.
978 bool abandonCache = false;
979
980
981 /// the actual cache of ID -> instances. This holds an owning reference,
982 /// so once items are in the cache they will never be deleted until
983 /// the cache drops its reference
984 PositionedCache cache;
985 unsigned int cacheHits, cacheMisses;
986
987 /**
988 * record the levels of open transaction objects we have
989 */
990 unsigned int transactionLevel;
991 bool transactionAborted;
992 sqlite3_stmt_ptr beginTransactionStmt, commitTransactionStmt, rollbackTransactionStmt;
993
994 std::map<DatFileType, NavDataCache::DatFilesGroupInfo> datFilesInfo;
995 SGPath metarDatPath,
996 carrierDatPath, airwayDatPath;
997
998 sqlite3_stmt_ptr readPropertyQuery, writePropertyQuery,
999 stampFileCache, statCacheCheck,
1000 loadAirportStmt, loadCommStation, loadPositioned, loadNavaid,
1001 loadRunwayStmt;
1002 sqlite3_stmt_ptr writePropertyMulti, clearProperty;
1003
1004 sqlite3_stmt_ptr insertPositionedQuery, insertAirport, insertTower, insertRunway,
1005 insertCommStation, insertNavaid;
1006 sqlite3_stmt_ptr insertTempPosQuery;
1007 sqlite3_stmt_ptr setAirportMetar, setRunwayReciprocal, setRunwayILS, setNavaidColocated,
1008 updatePosition, updateTempPos;
1009 sqlite3_stmt_ptr removePositionedQuery, removeTempPosQuery;
1010
1011 sqlite3_stmt_ptr findClosestWithIdent;
1012 // octree (spatial index) related queries
1013 sqlite3_stmt_ptr getOctreeChildren, insertOctree, updateOctreeChildren,
1014 getOctreeLeafChildren;
1015
1016 sqlite3_stmt_ptr searchAirports, getAllAirports;
1017 sqlite3_stmt_ptr findCommByFreq, findNavsByFreq,
1018 findNavsByFreqNoPos, findNavaidForRunway;
1019 sqlite3_stmt_ptr getAirportItems, getAirportItemByIdent;
1020 sqlite3_stmt_ptr findAirportRunway,
1021 findILS;
1022
1023 sqlite3_stmt_ptr runwayLengthFtQuery;
1024
1025 // airways
1026 sqlite3_stmt_ptr findAirway, findAirwayNet, insertAirwayEdge,
1027 isPosInAirway, airwayEdgesFrom, airwayEdgesTo,
1028 insertAirway, airwayEdges;
1029 sqlite3_stmt_ptr loadAirway;
1030
1031 // since there's many permutations of ident/name queries, we create
1032 // them programtically, but cache the exact query by its raw SQL once
1033 // used.
1034 std::map<string, sqlite3_stmt_ptr> findByStringDict;
1035
1036 typedef std::vector<sqlite3_stmt_ptr> StmtVec;
1037 StmtVec prepared;
1038
1039 std::set<Octree::Branch*> deferredOctreeUpdates;
1040
1041 // if we're performing a rebuild, the thread that is doing the work.
1042 // otherwise, NULL
1043 std::unique_ptr<RebuildThread> rebuilder;
1044
1045 // transient rowIDs (not actually present in the on-disk DB, only in our
1046 // in-memory cache / temporary table) start at this value and count down
1047 PositionedID nextTransientId = -1000;
1048 };
1049
1050 //////////////////////////////////////////////////////////////////////
1051
1052 FGPositioned* NavDataCache::NavDataCachePrivate::loadById(sqlite3_int64 rowid,
1053 sqlite3_int64& aptId)
1054 {
1055 if (abandonCache)
1056 throw AbandonCacheException{};
1057
1058 sqlite3_bind_int64(loadPositioned, 1, rowid);
1059 execSelect1(loadPositioned);
1060
1061 assert(rowid == sqlite3_column_int64(loadPositioned, 0));
1062 FGPositioned::Type ty = (FGPositioned::Type)sqlite3_column_int(loadPositioned, 1);
1063
1064 PositionedID prowid = static_cast<PositionedID>(rowid);
1065 string ident = (char*)sqlite3_column_text(loadPositioned, 2);
1066 string name = (char*)sqlite3_column_text(loadPositioned, 3);
1067 aptId = sqlite3_column_int64(loadPositioned, 4);
1068 double lon = sqlite3_column_double(loadPositioned, 5);
1069 double lat = sqlite3_column_double(loadPositioned, 6);
1070 double elev = sqlite3_column_double(loadPositioned, 7);
1071 SGGeod pos = SGGeod::fromDegM(lon, lat, elev);
1072
1073 reset(loadPositioned);
1074
1075 switch (ty) {
1076 case FGPositioned::AIRPORT:
1077 case FGPositioned::SEAPORT:
1078 case FGPositioned::HELIPORT:
1079 return loadAirport(rowid, ty, ident, name, pos);
1080
1081 case FGPositioned::TOWER:
1082 return new AirportTower(prowid, aptId, ident, pos);
1083
1084 case FGPositioned::RUNWAY:
1085 case FGPositioned::HELIPAD:
1086 case FGPositioned::TAXIWAY:
1087 return loadRunway(rowid, ty, ident, pos, aptId);
1088
1089 case FGPositioned::LOC:
1090 case FGPositioned::VOR:
1091 case FGPositioned::GS:
1092 case FGPositioned::ILS:
1093 case FGPositioned::NDB:
1094 case FGPositioned::OM:
1095 case FGPositioned::MM:
1096 case FGPositioned::IM:
1097 case FGPositioned::DME:
1098 case FGPositioned::TACAN:
1099 case FGPositioned::MOBILE_TACAN:
1100 return loadNav(rowid, ty, ident, name, pos);
1101
1102 case FGPositioned::FIX:
1103 return new FGFix(rowid, ident, pos);
1104
1105 case FGPositioned::WAYPOINT:
1106 case FGPositioned::COUNTRY:
1107 case FGPositioned::CITY:
1108 case FGPositioned::TOWN:
1109 case FGPositioned::VILLAGE:
1110 case FGPositioned::VISUAL_REPORTING_POINT: {
1111 FGPositioned* wpt = new POI(rowid, ty, ident, pos, name);
1112 return wpt;
1113 }
1114
1115 case FGPositioned::FREQ_GROUND:
1116 case FGPositioned::FREQ_TOWER:
1117 case FGPositioned::FREQ_ATIS:
1118 case FGPositioned::FREQ_AWOS:
1119 case FGPositioned::FREQ_APP_DEP:
1120 case FGPositioned::FREQ_ENROUTE:
1121 case FGPositioned::FREQ_CLEARANCE:
1122 case FGPositioned::FREQ_UNICOM:
1123 return loadComm(rowid, ty, ident, name, pos, aptId);
1124
1125 default:
1126 return NULL;
1127 }
1128 }
1129
1130 bool NavDataCache::NavDataCachePrivate::isCachedFileModified(const SGPath& path, bool verbose)
1131 {
1132 if (!path.exists()) {
1133 throw sg_exception(
1134 "NavCache: missing file '" + path.utf8Str() + "'",
1135 string("NavDataCache::NavDataCachePrivate::isCachedFileModified()"));
1136 }
1137
1138 sqlite_bind_temp_stdstring(statCacheCheck, 1, path.realpath().utf8Str());
1139 sgDebugPriority logLevel = verbose ? SG_WARN : SG_DEBUG;
1140 if (!execSelect(statCacheCheck)) {
1141 SG_LOG(SG_NAVCACHE, logLevel, "NavCache: (re-)build required because '" <<
1142 path.utf8Str() << "' is not in the cache");
1143 reset(statCacheCheck);
1144 return true;
1145 }
1146
1147 time_t modtime = sqlite3_column_int64(statCacheCheck, 0);
1148 time_t delta = std::labs(modtime - path.modTime());
1149 if (delta == 0) {
1150 SG_LOG(SG_NAVCACHE, SG_DEBUG, "NavCache: modtime matches, no rebuild required for " << path);
1151 reset(statCacheCheck);
1152 return false;
1153 }
1154
1155 const std::string shaHash{(char*)sqlite3_column_text(statCacheCheck, 1)};
1156 SGFile f(path);
1157 const auto fileHash = f.computeHash();
1158 const auto isModified = (fileHash != shaHash);
1159 reset(statCacheCheck);
1160
1161 if (!isModified) {
1162 // the mode time check failed, but the hashes matched. Let's update our modtime so we
1163 // don't compute the hash until the mod-time changes again.
1164 SG_LOG(SG_NAVCACHE, logLevel, "NavCache: " << path << " has changed modtime but contents are unchanged, re-setting cahced mod-time");
1165 outer->stampCacheFile(path, fileHash);
1166 }
1167
1168 return isModified;
1169 }
1170
1171 // Find the list of $scenery_path/NavData/<type>/*.dat[.gz] files found
1172 // inside scenery paths, plus the default file for the given type (e.g.,
1173 // $FG_ROOT/Airports/apt.dat.gz for the 'apt' type).
1174 // Also compute the total size of all these files (in bytes), which is useful
1175 // for progress information.
1176 // The result is stored in the datFilesInfo field.
1177 void NavDataCache::NavDataCachePrivate::findDatFiles(
1178 NavDataCache::DatFileType datFileType)
1179 {
1180 NavDataCache::DatFilesGroupInfo result;
1181 result.datFileType = datFileType;
1182 result.totalSize = 0;
1183
1184 // we don't always add FG_ROOT/Scenery to the path list. But if it exists,
1185 // we want to pick up NavData files from it, since we have shipped
1186 // scenery (for BIKF) which uses newer data than the default files
1187 // in Airports/
1188 auto paths = globals->get_fg_scenery();
1189 const auto fgrootScenery = globals->get_fg_root() / "Scenery";
1190 if (fgrootScenery.exists()) {
1191 auto it = std::find(paths.begin(), paths.end(), fgrootScenery);
1192 if (it == paths.end()) {
1193 paths.push_back(fgrootScenery);
1194 }
1195 }
1196
1197 for (const auto& path: paths) {
1198 if (! path.isDir()) {
1199 SG_LOG(SG_NAVCACHE, SG_WARN, path <<
1200 ": given as a scenery path, but is not a directory");
1201 continue;
1202 }
1203
1204 const SGPath datFilesDir =
1205 path / "NavData" / NavDataCache::datTypeStr[datFileType];
1206
1207 if (datFilesDir.isDir()) {
1208 // Deterministic because the return value of simgear::Dir::children() is
1209 // already sorted
1210 const PathList files = simgear::Dir(datFilesDir).children(
1211 simgear::Dir::TYPE_FILE | simgear::Dir::NO_DOT_OR_DOTDOT);
1212
1213 for (const auto& f : files) {
1214 const std::string name = f.file();
1215 if (simgear::strutils::ends_with(name, ".dat") ||
1216 simgear::strutils::ends_with(name, ".dat.gz")) {
1217 result.paths.push_back({f, path});
1218 result.totalSize += f.sizeInBytes();
1219 }
1220 }
1221 }
1222 } // of loop over the list of scenery paths
1223
1224 // Add the default file (e.g., $FG_ROOT/Airports/apt.dat.gz), at least for
1225 // now
1226 SGPath defaultDatFile(globals->get_fg_root());
1227 defaultDatFile.append(NavDataCache::defaultDatFile[datFileType]);
1228 if ((result.paths.empty() || result.paths.back().datPath != defaultDatFile) &&
1229 defaultDatFile.isFile()) {
1230 result.paths.push_back({defaultDatFile, globals->get_fg_root()});
1231 result.totalSize += defaultDatFile.sizeInBytes();
1232 }
1233
1234 datFilesInfo[datFileType] = result;
1235 }
1236
1237 // Compare:
1238 // - the list of dat files given by 'datFilesGroupInfo';
1239 // - the list obtained from the record with key '<type>.dat files' of the
1240 // NavDataCache 'properties' table, where <type> is one of 'apt', 'metar',
1241 // 'fix', 'poi', etc..
1242 //
1243 // This comparison is sensitive to the number and order of the files,
1244 // their respective SGPath::realpath() and SGPath::modTime().
1245 bool NavDataCache::NavDataCachePrivate::areDatFilesModified(
1246 NavDataCache::DatFileType datFileType,
1247 bool verbose)
1248 {
1249 // 'apt' or 'metar' or 'fix' or...
1250 const NavDataCache::DatFilesGroupInfo& datFilesGroupInfo =
1251 datFilesInfo[datFileType];
1252 const string datTypeStr =
1253 NavDataCache::datTypeStr[datFileType];
1254 const string_list cachedFiles = outer->readOrderedStringListProperty(
1255 datTypeStr + ".dat files", SGPath::pathListSep);
1256 const auto& datFiles = datFilesGroupInfo.paths;
1257 auto datFilesIt = datFiles.cbegin();
1258 string_list::const_iterator cachedFilesIt = cachedFiles.begin();
1259 // Same logic as in NavDataCachePrivate::isCachedFileModified()
1260 sgDebugPriority logLevel = verbose ? SG_WARN : SG_DEBUG;
1261
1262 if (cachedFilesIt == cachedFiles.end() && datFilesIt != datFiles.end()) {
1263 SG_LOG(SG_NAVCACHE, logLevel,
1264 "NavCache: rebuild required for " << datTypeStr << ".dat files "
1265 "(no file in cache, but " << datFiles.size() << " such file" <<
1266 (datFiles.size() > 1 ? "s" : "") << " found in scenery paths)");
1267 return true;
1268 }
1269
1270 while (datFilesIt != datFiles.end()) {
1271 const SGPath& path = (datFilesIt++)->datPath;
1272
1273 if (!path.exists()) {
1274 throw sg_exception(
1275 "NavCache: non-existent file '" + path.utf8Str() + "'",
1276 string("NavDataCache::NavDataCachePrivate::areDatFilesModified()"));
1277 }
1278
1279 if (cachedFilesIt == cachedFiles.end()) {
1280 SG_LOG(SG_NAVCACHE, logLevel,
1281 "NavCache: rebuild required for " << datTypeStr << ".dat files "
1282 "(less files in cache than in scenery paths)");
1283 return true;
1284 } else {
1285 string cachedFile = *(cachedFilesIt++);
1286 string fileOnDisk = path.realpath().utf8Str();
1287
1288 if (cachedFile != fileOnDisk || isCachedFileModified(path, verbose)) {
1289 // isCachedFileModified() does all the logging, so we only have to
1290 // tell what is happening in case that method was not called.
1291 if (cachedFile != fileOnDisk) {
1292 SG_LOG(SG_NAVCACHE, logLevel,
1293 "NavCache: rebuild required because '" << cachedFile <<
1294 "' (in cache) != '" << fileOnDisk << "' (on disk)");
1295 }
1296 return true;
1297 }
1298 }
1299 } // of loop over the elements of 'datFiles'
1300
1301 if (cachedFilesIt != cachedFiles.end()) {
1302 SG_LOG(SG_NAVCACHE, logLevel,
1303 "NavCache: rebuild required for " << datTypeStr << ".dat files "
1304 "(more files in cache than in scenery paths)");
1305 return true;
1306 }
1307
1308 SG_LOG(SG_NAVCACHE, SG_DEBUG,
1309 "NavCache: no rebuild required for " << datTypeStr << ".dat files");
1310 return false;
1311 }
1312
1313
1314 // NavDataCache's static member variables
1315 static NavDataCache* static_instance = nullptr;
1316
1317 const string NavDataCache::datTypeStr[] = {
1318 string("apt"),
1319 string("metar"),
1320 string("awy"),
1321 string("nav"),
1322 string("fix"),
1323 string("poi"),
1324 string("carrier"),
1325 string("TACAN_freq")
1326 };
1327
1328 const string NavDataCache::defaultDatFile[] = {
1329 string("Airports/apt.dat.gz"),
1330 string("Airports/metar.dat.gz"),
1331 string("Navaids/awy.dat.gz"),
1332 string("Navaids/nav.dat.gz"),
1333 string("Navaids/fix.dat.gz"),
1334 string("Navaids/poi.dat.gz"),
1335 string("Navaids/carrier.dat.gz"),
1336 string("Navaids/TACAN_freq.dat.gz")
1337 };
1338
1339 NavDataCache::NavDataCache()
1340 {
1341 SGPath homePath(globals->get_fg_home());
1342
1343 std::ostringstream os;
1344 string_list versionParts = simgear::strutils::split(VERSION, ".");
1345 if (versionParts.size() < 2) {
1346 os << "navdata.cache";
1347 } else {
1348 os << "navdata_" << versionParts[0] << "_" << versionParts[1] << ".cache";
1349 }
1350
1351 SGPath dbPath = homePath / os.str();
1352 dbPath.set_cached(false);
1353
1354 const auto readOnly = fgGetBool("/sim/fghome-readonly", false);
1355 if (readOnly && !dbPath.exists()) {
1356 flightgear::fatalMessageBoxThenExit(
1357 "Missing navigation cache",
1358 "Unable to open navigation cache in read-only mode. Please run FlightGear in normal (writeable) mode at least once to create the cache file.",
1359 "No navigation data was found at: " + dbPath.utf8Str() + "");
1360 }
1361
1362 const int MAX_TRIES = readOnly ? 1 : 3;
1363 // permit additional DB connections from the same process
1364 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
1365
1366 for (int t=0; t < MAX_TRIES; ++t) {
1367 try {
1368 d.reset(new NavDataCachePrivate(dbPath, this));
1369 d->init();
1370 //d->checkCacheFile();
1371 // reached this point with no exception, success
1372 break;
1373 } catch (sg_exception& e) {
1374 SG_LOG(SG_NAVCACHE, t == 0 ? SG_WARN : SG_ALERT, "NavCache: init failed:" << e.what()
1375 << " (attempt " << t << ")");
1376
1377 if (t == (MAX_TRIES - 1)) {
1378 // final attempt still failed, we are busted
1379 flightgear::fatalMessageBoxThenExit(
1380 "Unable to open navigation cache",
1381 std::string("The navigation data cache could not be opened:")
1382 + e.getMessage(), e.getOrigin());
1383 }
1384
1385 d.reset();
1386
1387 // only wipe the existing if not readonly
1388 if (dbPath.exists() && !readOnly) {
1389 bool ok = dbPath.remove();
1390 if (!ok) {
1391 SG_LOG(SG_NAVCACHE, SG_ALERT, "NavCache: failed to remove previous cache file");
1392 flightgear::fatalMessageBoxThenExit(
1393 "Unable to re-create navigation cache",
1394 "Attempting to remove the old cache failed.",
1395 "Location: " + dbPath.utf8Str());
1396 }
1397 }
1398 }
1399 } // of retry loop
1400
1401 // Update d->aptDatFilesInfo, d->metarDatPath, d->navDatPath, etc.
1402 updateListsOfDatFiles();
1403 }
1404
1405 NavDataCache::~NavDataCache()
1406 {
1407 assert(static_instance == this);
1408
1409 if (d->rebuilder) {
1410 addSentryBreadcrumb("shutting down cache with rebuild active", "info");
1411 // setting thsi will cause DB operations to throw the special
1412 // AbandonCache exception, and hence cause the rebuild thread to
1413 // exit pretty quickly, so the join() won't take too long.
1414 d->abandonCache = true;
1415 d->rebuilder.reset(); // will the destructor which does a join()
1416 addSentryBreadcrumb("abandoned rebuild scuessfully", "info");
1417 }
1418
1419
1420 // ensure we wip the airports cache too, or we'll get out
1421 // of sync during tests
1422 FGAirport::clearAirportsCache();
1423
1424 static_instance = nullptr;
1425 d.reset();
1426 }
1427
1428 NavDataCache* NavDataCache::createInstance()
1429 {
1430 assert(static_instance == nullptr);
1431 static_instance = new NavDataCache;
1432 return static_instance;
1433 }
1434
1435 NavDataCache* NavDataCache::instance()
1436 {
1437 return static_instance;
1438 }
1439
1440 void NavDataCache::shutdown()
1441 {
1442 if (static_instance) {
1443 delete static_instance;
1444 // destructor will clear static_instance pointer
1445 }
1446 }
1447
1448 // Update the lists of dat files used for NavCache freshness checking and
1449 // rebuilding.
1450 void NavDataCache::updateListsOfDatFiles() {
1451 // All $scenery_path/NavData/apt/*.dat[.gz] files found inside scenery
1452 // paths, plus $FG_ROOT/Airports/apt.dat.gz (order matters).
1453 d->findDatFiles(DATFILETYPE_APT);
1454
1455 // All $scenery_path/NavData/{nav,fix}/*.dat[.gz] files found inside scenery
1456 // paths, plus $FG_ROOT/Navaids/{nav,fix}.dat.gz (order matters).
1457 d->findDatFiles(DATFILETYPE_NAV);
1458 d->findDatFiles(DATFILETYPE_FIX);
1459 d->findDatFiles(DATFILETYPE_POI);
1460
1461 // These ones are still managed the "old" way (no search through scenery
1462 // paths).
1463 d->metarDatPath = SGPath(globals->get_fg_root());
1464 d->metarDatPath.append("Airports/metar.dat.gz");
1465
1466 // d->poiDatPath = SGPath(globals->get_fg_root());
1467 // d->poiDatPath.append("Navaids/poi.dat.gz");
1468
1469 d->carrierDatPath = SGPath(globals->get_fg_root());
1470 d->carrierDatPath.append("Navaids/carrier_nav.dat.gz");
1471
1472 d->airwayDatPath = SGPath(globals->get_fg_root());
1473 d->airwayDatPath.append("Navaids/awy.dat.gz");
1474 }
1475
1476 const NavDataCache::DatFilesGroupInfo&
1477 NavDataCache::getDatFilesInfo(DatFileType datFileType) const
1478 {
1479 auto iter = d->datFilesInfo.find(datFileType);
1480 if (iter == d->datFilesInfo.end()) {
1481 throw sg_error("NavCache: requesting info about the list of " +
1482 datTypeStr[datFileType] + " dat files, however this is not "
1483 "implemented yet!");
1484 }
1485 return iter->second;
1486 }
1487
1488 bool NavDataCache::isRebuildRequired()
1489 {
1490 if (d->readOnly) {
1491 return false;
1492 }
1493
1494 const auto environmentOverride = std::getenv("FG_NAVCACHE_REBUILD");
1495 bool dontRebuildFlag = false;
1496 if (environmentOverride) {
1497 if (!strcmp(environmentOverride, "0")) {
1498 dontRebuildFlag = true;
1499 }
1500
1501 if (!strcmp(environmentOverride, "1")) {
1502 SG_LOG(SG_NAVCACHE, SG_MANDATORY_INFO, "NavCache: forcing rebuild becuase FG_NAVCACHE_REBUILD=1");
1503 return true;
1504 }
1505 }
1506
1507 if (flightgear::Options::sharedInstance()->isOptionSet("restore-defaults")) {
1508 SG_LOG(SG_NAVCACHE, SG_INFO, "NavCache: restore-defaults requested, will rebuild cache");
1509 return true;
1510 }
1511
1512 if (d->areDatFilesModified(DATFILETYPE_APT, true) ||
1513 d->isCachedFileModified(d->metarDatPath, true) ||
1514 d->areDatFilesModified(DATFILETYPE_NAV, true) ||
1515 d->areDatFilesModified(DATFILETYPE_FIX, true) ||
1516 d->isCachedFileModified(d->carrierDatPath, true) ||
1517 d->areDatFilesModified(DATFILETYPE_POI, true) ||
1518 d->isCachedFileModified(d->airwayDatPath, true))
1519 {
1520 if (dontRebuildFlag) {
1521 SG_LOG(SG_NAVCACHE, SG_ALERT, "NavCache: skipping rebuild because FG_NAVCACHE_REBUILD=0");
1522 SG_LOG(SG_NAVCACHE, SG_ALERT, "!! Navigation and airport data will be incorrect !!");
1523 return false;
1524 } else {
1525 SG_LOG(SG_NAVCACHE, SG_INFO, "NavCache: main cache rebuild required");
1526 return true;
1527 }
1528 }
1529
1530 SG_LOG(SG_NAVCACHE, SG_INFO, "NavCache: no main cache rebuild required");
1531 return false;
1532 }
1533
1534 NavDataCache::RebuildPhase NavDataCache::rebuild()
1535 {
1536 if (!d->rebuilder.get()) {
1537 d->rebuilder.reset(new RebuildThread(this));
1538 d->rebuilder->start();
1539 }
1540
1541 // poll the rebuild thread
1542 RebuildPhase phase = d->rebuilder->currentPhase();
1543 if (phase == REBUILD_DONE) {
1544 d->rebuilder.reset(); // all done!
1545 }
1546 return phase;
1547 }
1548
1549 unsigned int NavDataCache::rebuildPhaseCompletionPercentage() const
1550 {
1551 if (!d->rebuilder.get()) {
1552 return 0;
1553 }
1554
1555 return d->rebuilder->completionPercent();
1556 }
1557
1558 void NavDataCache::setRebuildPhaseProgress(RebuildPhase ph, unsigned int percent)
1559 {
1560 if (!d->rebuilder.get()) {
1561 return;
1562 }
1563
1564 d->rebuilder->setProgress(ph, percent);
1565 }
1566
1567 void NavDataCache::loadDatFiles(
1568 DatFileType type,
1569 std::function<void(const SceneryLocation&, std::size_t, std::size_t)> loader)
1570 {
1571 SGTimeStamp st;
1572 const string typeStr = datTypeStr[type];
1573 string_list datFiles;
1574 const NavDataCache::DatFilesGroupInfo datFilesInfo = getDatFilesInfo(type);
1575 const SceneryLocationList sceneryLocations = datFilesInfo.paths;
1576 std::size_t bytesReadSoFar = 0;
1577
1578 st.stamp();
1579 for (const auto& scLoc : sceneryLocations) {
1580 const string path = scLoc.datPath.realpath().utf8Str();
1581 datFiles.push_back(path);
1582 SG_LOG(SG_GENERAL, SG_INFO,
1583 "Loading " + typeStr + ".dat file: '" << std::move(path) << "'");
1584 loader(scLoc, bytesReadSoFar, datFilesInfo.totalSize);
1585 bytesReadSoFar += scLoc.datPath.sizeInBytes();
1586 stampCacheFile(scLoc.datPath); // this uses the realpath() of the file
1587 }
1588
1589 // Store the list of .dat files we have loaded
1590 writeOrderedStringListProperty(typeStr + ".dat files", datFiles,
1591 SGPath::pathListSep);
1592 SG_LOG(SG_NAVCACHE, SG_INFO,
1593 typeStr + ".dat files load took: " <<
1594 st.elapsedMSec());
1595 }
1596
1597 void NavDataCache::doRebuild()
1598 {
1599 rebuildInProgress = true;
1600
1601 try {
1602 d->close(); // completely close the sqlite object
1603 d->path.remove(); // remove the file on disk
1604 d->init(); // start again from scratch
1605
1606 // initialise the root octree node
1607 d->runSQL("INSERT INTO octree (rowid, children) VALUES (1, 0)");
1608
1609 SGTimeStamp st;
1610 {
1611 Transaction txn(this);
1612 APTLoader aptLoader;
1613 FixesLoader fixesLoader;
1614 NavLoader navLoader;
1615
1616 using namespace std::placeholders; // for _1, _2, _3...
1617
1618 loadDatFiles(DATFILETYPE_APT,
1619 std::bind(&APTLoader::readAptDatFile, &aptLoader, _1, _2, _3));
1620
1621 st.stamp();
1622 setRebuildPhaseProgress(REBUILD_UNKNOWN);
1623 SG_LOG(SG_NAVCACHE, SG_DEBUG, "Processing airports");
1624 aptLoader.loadAirports(); // load airport data into the NavCache
1625 SG_LOG(SG_NAVCACHE, SG_INFO,
1626 "processing airports took:" <<
1627 st.elapsedMSec());
1628
1629 setRebuildPhaseProgress(REBUILD_UNKNOWN);
1630 metarDataLoad(d->metarDatPath);
1631 stampCacheFile(d->metarDatPath);
1632
1633 loadDatFiles(DATFILETYPE_FIX,
1634 std::bind(&FixesLoader::loadFixes, &fixesLoader, _1, _2, _3));
1635 loadDatFiles(DATFILETYPE_NAV,
1636 std::bind(&NavLoader::loadNav, &navLoader, _1, _2, _3));
1637
1638 setRebuildPhaseProgress(REBUILD_UNKNOWN);
1639 st.stamp();
1640 txn.commit();
1641 SG_LOG(SG_NAVCACHE, SG_INFO, "stage 1 commit took:" << st.elapsedMSec());
1642 }
1643
1644 {
1645 Transaction txn(this);
1646 POILoader poisLoader;
1647
1648 using namespace std::placeholders; // for _1, _2, _3...
1649
1650 st.stamp();
1651 loadDatFiles(DATFILETYPE_POI,
1652 std::bind(&POILoader::loadPOIs, &poisLoader, _1, _2, _3));
1653
1654 SG_LOG(SG_NAVCACHE, SG_INFO, "poi.dat load took:" << st.elapsedMSec());
1655
1656 setRebuildPhaseProgress(REBUILD_UNKNOWN);
1657 st.stamp();
1658 txn.commit();
1659 SG_LOG(SG_NAVCACHE, SG_INFO, "POI commit took:" << st.elapsedMSec());
1660 }
1661
1662 {
1663 Transaction txn(this);
1664 NavLoader navLoader;
1665 navLoader.loadCarrierNav(d->carrierDatPath);
1666 stampCacheFile(d->carrierDatPath);
1667
1668 st.stamp();
1669 Airway::loadAWYDat(d->airwayDatPath);
1670 stampCacheFile(d->airwayDatPath);
1671 SG_LOG(SG_NAVCACHE, SG_INFO, "awy.dat load took:" << st.elapsedMSec());
1672
1673 d->flushDeferredOctreeUpdates();
1674
1675 string sceneryPaths = SGPath::join(globals->get_fg_scenery(), ";");
1676 writeStringProperty("scenery_paths", sceneryPaths);
1677
1678 st.stamp();
1679 txn.commit();
1680 SG_LOG(SG_NAVCACHE, SG_INFO, "final commit took:" << st.elapsedMSec());
1681
1682 }
1683
1684 } catch (sg_exception& e) {
1685 SG_LOG(SG_NAVCACHE, SG_ALERT, "caught exception rebuilding navCache:" << e.what());
1686 }
1687
1688 rebuildInProgress = false;
1689 }
1690
1691 int NavDataCache::readIntProperty(const string& key)
1692 {
1693 sqlite_bind_stdstring(d->readPropertyQuery, 1, key);
1694 int result = 0;
1695
1696 if (d->execSelect(d->readPropertyQuery)) {
1697 result = sqlite3_column_int(d->readPropertyQuery, 0);
1698 } else {
1699 SG_LOG(SG_NAVCACHE, SG_WARN, "readIntProperty: unknown:" << key);
1700 }
1701
1702 d->reset(d->readPropertyQuery);
1703 return result;
1704 }
1705
1706 double NavDataCache::readDoubleProperty(const string& key)
1707 {
1708 sqlite_bind_stdstring(d->readPropertyQuery, 1, key);
1709 double result = 0.0;
1710 if (d->execSelect(d->readPropertyQuery)) {
1711 result = sqlite3_column_double(d->readPropertyQuery, 0);
1712 } else {
1713 SG_LOG(SG_NAVCACHE, SG_WARN, "readDoubleProperty: unknown:" << key);
1714 }
1715
1716 d->reset(d->readPropertyQuery);
1717 return result;
1718 }
1719
1720 string NavDataCache::readStringProperty(const string& key)
1721 {
1722 sqlite_bind_stdstring(d->readPropertyQuery, 1, key);
1723 string result;
1724 if (d->execSelect(d->readPropertyQuery)) {
1725 result = (char*) sqlite3_column_text(d->readPropertyQuery, 0);
1726 } else {
1727 SG_LOG(SG_NAVCACHE, SG_WARN, "readStringProperty: unknown:" << key);
1728 }
1729
1730 d->reset(d->readPropertyQuery);
1731 return result;
1732 }
1733
1734 void NavDataCache::writeIntProperty(const string& key, int value)
1735 {
1736 d->writeIntProperty(key, value);
1737 }
1738
1739 void NavDataCache::writeStringProperty(const string& key, const string& value)
1740 {
1741 if (!isReadOnly()) {
1742 sqlite_bind_stdstring(d->clearProperty, 1, key);
1743 d->execUpdate(d->clearProperty);
1744
1745 sqlite_bind_stdstring(d->writePropertyQuery, 1, key);
1746 sqlite_bind_stdstring(d->writePropertyQuery, 2, value);
1747 d->execUpdate(d->writePropertyQuery);
1748 }
1749 }
1750
1751 void NavDataCache::writeDoubleProperty(const string& key, const double& value)
1752 {
1753 if (!isReadOnly()) {
1754 sqlite_bind_stdstring(d->clearProperty, 1, key);
1755 d->execUpdate(d->clearProperty);
1756
1757 sqlite_bind_stdstring(d->writePropertyQuery, 1, key);
1758 sqlite3_bind_double(d->writePropertyQuery, 2, value);
1759 d->execUpdate(d->writePropertyQuery);
1760 }
1761 }
1762
1763 string_list NavDataCache::readStringListProperty(const string& key)
1764 {
1765 sqlite_bind_stdstring(d->readPropertyQuery, 1, key);
1766 string_list result;
1767 while (d->stepSelect(d->readPropertyQuery)) {
1768 result.push_back((char*) sqlite3_column_text(d->readPropertyQuery, 0));
1769 }
1770 d->reset(d->readPropertyQuery);
1771
1772 return result;
1773 }
1774
1775 void NavDataCache::writeStringListProperty(const string& key, const string_list& values)
1776 {
1777 if (!isReadOnly()) {
1778 sqlite_bind_stdstring(d->clearProperty, 1, key);
1779 d->execUpdate(d->clearProperty);
1780
1781 for (string value : values) {
1782 sqlite_bind_stdstring(d->writePropertyMulti, 1, key);
1783 sqlite_bind_stdstring(d->writePropertyMulti, 2, value);
1784 d->execInsert(d->writePropertyMulti);
1785 }
1786 }
1787 }
1788
1789 string_list NavDataCache::readOrderedStringListProperty(const string& key,
1790 const char* separator)
1791 {
1792 string_list l = simgear::strutils::split(readStringProperty(key), separator);
1793 assert(!l.empty());
1794 // See comment in writeOrderedStringListProperty()
1795 l.pop_back();
1796
1797 return l;
1798 }
1799
1800 void NavDataCache::writeOrderedStringListProperty(const string& key,
1801 const string_list& values,
1802 const char* separator)
1803 {
1804 string s;
1805
1806 // If values == {a, b, c}, we'll write this string to the property:
1807 //
1808 // a + separator + b + separator + c + separator
1809 //
1810 // When this is split around 'separator' after reading back the property
1811 // value, we'll obtain an extraneous empty element after 'c' that should be
1812 // discarded. This last separator allows correct write-read round-trip when
1813 // 'values' is empty.
1814 if (!values.empty()) {
1815 s = simgear::strutils::join(values, separator) + string(separator);
1816 }
1817
1818 writeStringProperty(key, s);
1819 }
1820
1821 bool NavDataCache::isCachedFileModified(const SGPath& path) const
1822 {
1823 return d->isCachedFileModified(path, false);
1824 }
1825
1826 void NavDataCache::stampCacheFile(const SGPath& path, const std::string& sha)
1827 {
1828 if (!isReadOnly()){
1829 sqlite_bind_temp_stdstring(d->stampFileCache, 1, path.realpath().utf8Str());
1830 sqlite3_bind_int64(d->stampFileCache, 2, path.modTime());
1831
1832 if (sha.empty()) {
1833 SGFile f(path);
1834 sqlite_bind_temp_stdstring(d->stampFileCache, 3, f.computeHash());
1835 } else {
1836 sqlite_bind_temp_stdstring(d->stampFileCache, 3, sha);
1837 }
1838 d->execInsert(d->stampFileCache);
1839 }
1840 }
1841
1842 void NavDataCache::beginTransaction()
1843 {
1844 if (d->transactionLevel == 0) {
1845 d->transactionAborted = false;
1846 d->stepSelect(d->beginTransactionStmt);
1847 sqlite3_reset(d->beginTransactionStmt);
1848 }
1849
1850 ++d->transactionLevel;
1851 }
1852
1853 void NavDataCache::commitTransaction()
1854 {
1855 assert(d->transactionLevel > 0);
1856 if (--d->transactionLevel == 0) {
1857 // if a nested transaction aborted, we might end up here, but must
1858 // still abort the entire transaction. That's bad, but safer than
1859 // committing.
1860 sqlite3_stmt_ptr q = d->transactionAborted ? d->rollbackTransactionStmt : d->commitTransactionStmt;
1861
1862 int retries = 0;
1863 int result;
1864 while (retries < MAX_RETRIES) {
1865 result = sqlite3_step(q);
1866 if (result == SQLITE_DONE) {
1867 break;
1868 }
1869
1870 // see http://www.sqlite.org/c3ref/get_autocommit.html for a hint
1871 // what's going on here: autocommit in inactive inside BEGIN, so if
1872 // it's active, the DB was rolled-back
1873 if (sqlite3_get_autocommit(d->db)) {
1874 SG_LOG(SG_NAVCACHE, SG_ALERT, "commit: was rolled back!" << retries);
1875 flightgear::sentryReportException("DB commit was rolled back");
1876 d->transactionAborted = true;
1877 break;
1878 }
1879
1880 if (result != SQLITE_BUSY) {
1881 break;
1882 }
1883
1884 SGTimeStamp::sleepForMSec(++retries * 100);
1885 SG_LOG(SG_NAVCACHE, SG_ALERT, "NavCache contention on commit, will retry:" << retries);
1886 } // of retry loop for DB busy
1887
1888 string errMsg;
1889 if (result != SQLITE_DONE) {
1890 errMsg = sqlite3_errmsg(d->db);
1891 flightgear::sentryReportException("DB error:" + errMsg + " running " + std::string{sqlite3_sql(q)});
1892 SG_LOG(SG_NAVCACHE, SG_ALERT, "Sqlite error:" << errMsg << " for " << result
1893 << " while running:\n\t" << sqlite3_sql(q));
1894 }
1895
1896 sqlite3_reset(q);
1897 }
1898 }
1899
1900 void NavDataCache::abortTransaction()
1901 {
1902 SG_LOG(SG_NAVCACHE, SG_WARN, "NavCache: aborting transaction");
1903 flightgear::sentryReportException("DB aborting transactino");
1904
1905 assert(d->transactionLevel > 0);
1906 if (--d->transactionLevel == 0) {
1907 d->stepSelect(d->rollbackTransactionStmt);
1908 sqlite3_reset(d->rollbackTransactionStmt);
1909 }
1910
1911 d->transactionAborted = true;
1912 }
1913
1914 void NavDataCache::clearDynamicPositioneds()
1915 {
1916 std::for_each(d->cache.begin(), d->cache.end(), [](PositionedCache::value_type& v) {
1917 if (v.second->type() == FGPositioned::MOBILE_TACAN) {
1918 auto mobile = fgpositioned_cast<FGMobileNavRecord>(v.second);
1919 mobile->clearVehicle();
1920 }
1921 });
1922 }
1923
1924 FGPositionedRef NavDataCache::loadById(PositionedID rowid)
1925 {
1926 if (!d || (rowid == 0)) {
1927 return {};
1928 };
1929
1930 PositionedCache::iterator it = d->cache.find(rowid);
1931 if (it != d->cache.end()) {
1932 d->cacheHits++;
1933 return it->second; // cache hit
1934 }
1935
1936 sqlite3_int64 aptId;
1937 FGPositionedRef pos = d->loadById(rowid, aptId);
1938 if (rebuildInProgress) {
1939 // Do not cache and apply ILS adjustment while rebuilding the cache.
1940 // The adjustment process requires all ILS navaids to be present,
1941 // which is not true during the cache rebuild.
1942 return pos;
1943 }
1944 d->cache.insert(it, PositionedCache::value_type(rowid, pos));
1945 d->cacheMisses++;
1946
1947 // when we loaded an ILS, we must apply per-airport changes
1948 if ((pos->type() == FGPositioned::ILS) && (aptId > 0)) {
1949 FGAirport* apt = FGPositioned::loadById<FGAirport>(aptId);
1950 apt->validateILSData();
1951 }
1952
1953 return pos;
1954 }
1955
1956 PositionedID NavDataCache::insertAirport(FGPositioned::Type ty, const string& ident,
1957 const string& name,
1958 const SGPath& sceneryPath)
1959 {
1960 const string sceneryPath_str = sceneryPath.utf8Str();
1961 // airports have their pos computed based on the avergae runway centres
1962 // so the pos isn't available immediately. Pass a dummy pos and avoid
1963 // doing spatial indexing until later
1964 sqlite3_int64 rowId = d->insertPositioned(ty, ident, name, SGGeod(),
1965 0 /* airport */,
1966 false /* spatial index */);
1967
1968 sqlite3_bind_int64(d->insertAirport, 1, rowId);
1969 sqlite_bind_stdstring(d->insertAirport, 2, sceneryPath_str);
1970 d->execInsert(d->insertAirport);
1971
1972 return rowId;
1973 }
1974
1975 void NavDataCache::updatePosition(PositionedID item, const SGGeod &pos)
1976 {
1977 const bool isTemporary = (item < 0);
1978 SGVec3d cartPos(SGVec3d::fromGeod(pos));
1979 auto it = d->cache.find(item);
1980
1981 // transient item, update the transient octree : this is much easier than the
1982 // persistent octree case (see logic below) becuase we know the tree is fully
1983 // loaded, and there's no DB table to keep in sync; we just update the in-memory
1984 // leaves once we found them.
1985 if (isTemporary) {
1986 assert(it != d->cache.end()); // transient item must existing in the in-memory cache
1987
1988 SGVec3d oldCartPos(SGVec3d::fromGeod(it->second->geod()));
1989 const auto ty = it->second->type();
1990
1991 Octree::Leaf* oldOctreeLeaf = Octree::globalTransientOctree()->findLeafForPos(oldCartPos);
1992 Octree::Leaf* newOctreeLeaf = Octree::globalTransientOctree()->findLeafForPos(cartPos);
1993
1994 // commonly the octree leaf won't change, so check for that
1995 if (oldOctreeLeaf != newOctreeLeaf) {
1996 oldOctreeLeaf->removeChild(item);
1997 newOctreeLeaf->insertChild(ty, item);
1998 }
1999
2000 it->second->modifyPosition(pos);
2001 }
2002
2003
2004 if (it != d->cache.end()) {
2005 d->cache[item]->modifyPosition(pos);
2006 }
2007
2008 auto stmt = isTemporary ? d->updateTempPos : d->updatePosition;
2009 sqlite3_bind_int(stmt, 1, item);
2010 sqlite3_bind_double(stmt, 2, pos.getLongitudeDeg());
2011 sqlite3_bind_double(stmt, 3, pos.getLatitudeDeg());
2012 sqlite3_bind_double(stmt, 4, pos.getElevationM());
2013
2014 if (!isTemporary) {
2015 // bug 905; the octree leaf may change here, but the leaf may already be
2016 // loaded, and caching its children. (Either the old or new leaf!). Worse,
2017 // we may be called here as a result of loading one of those leaf's children.
2018 // instead of dealing with all those possibilites, such as modifying
2019 // the in-memory leaf's STL child container, we simply leave the runtime
2020 // structures alone. This is fine providing items do no move very far, since
2021 // all the spatial searches ultimately use the items' real cartesian position,
2022 // which was updated above.
2023 Octree::Leaf* octreeLeaf = Octree::globalPersistentOctree()->findLeafForPos(cartPos);
2024 sqlite3_bind_int64(stmt, 5, octreeLeaf->guid());
2025 }
2026
2027 sqlite3_bind_double(stmt, 6, cartPos.x());
2028 sqlite3_bind_double(stmt, 7, cartPos.y());
2029 sqlite3_bind_double(stmt, 8, cartPos.z());
2030
2031
2032 d->execUpdate(stmt);
2033 }
2034
2035 void NavDataCache::insertTower(PositionedID airportId, const SGGeod& pos)
2036 {
2037 d->insertPositioned(FGPositioned::TOWER, string(), string(),
2038 pos, airportId, true /* spatial index */);
2039 }
2040
2041 PositionedID
2042 NavDataCache::insertRunway(FGPositioned::Type ty, const string& ident,
2043 const SGGeod& pos, PositionedID apt,
2044 double heading, double length, double width, double displacedThreshold,
2045 double stopway, int markings, int approach, int tdz, int reil,
2046 int surfaceCode, int shoulder_code, float smoothness, int center_lights,
2047 int edge_lights, int distance_remaining)
2048 {
2049 // only runways are spatially indexed; don't bother indexing taxiways
2050 // or pavements
2051 bool spatialIndex = ( ty == FGPositioned::RUNWAY || ty == FGPositioned::HELIPAD);
2052
2053 sqlite3_int64 rowId = d->insertPositioned(ty, cleanRunwayNo(ident), "", pos, apt,
2054 spatialIndex);
2055 sqlite3_bind_int64(d->insertRunway, 1, rowId);
2056 sqlite3_bind_double(d->insertRunway, 2, heading);
2057 sqlite3_bind_double(d->insertRunway, 3, length);
2058 sqlite3_bind_double(d->insertRunway, 4, width);
2059 sqlite3_bind_int(d->insertRunway, 5, surfaceCode);
2060 sqlite3_bind_double(d->insertRunway, 6, displacedThreshold);
2061 sqlite3_bind_double(d->insertRunway, 7, stopway);
2062 sqlite3_bind_int(d->insertRunway, 8, markings);
2063 sqlite3_bind_int(d->insertRunway, 9, approach);
2064 sqlite3_bind_int(d->insertRunway, 10, tdz);
2065 sqlite3_bind_int(d->insertRunway, 11, reil);
2066 sqlite3_bind_int(d->insertRunway, 12, shoulder_code);
2067 sqlite3_bind_double(d->insertRunway, 13, smoothness);
2068 sqlite3_bind_int(d->insertRunway, 14, center_lights);
2069 sqlite3_bind_int(d->insertRunway, 15, edge_lights);
2070 sqlite3_bind_int(d->insertRunway, 16, distance_remaining);
2071
2072 return d->execInsert(d->insertRunway);
2073 }
2074
2075 PositionedID
2076 NavDataCache::insertRunway(FGPositioned::Type ty, const string& ident,
2077 const SGGeod& pos, PositionedID apt,
2078 double heading, double length, double width, double displacedThreshold,
2079 double stopway, int surfaceCode)
2080 {
2081 return insertRunway(ty, ident, pos, apt,
2082 heading, length, width, displacedThreshold,
2083 stopway, 0, 0, 0, 0,
2084 surfaceCode, 0, 0.0f, 0, 0, 0);
2085 }
2086
2087 void NavDataCache::setRunwayReciprocal(PositionedID runway, PositionedID recip)
2088 {
2089 sqlite3_bind_int64(d->setRunwayReciprocal, 1, runway);
2090 sqlite3_bind_int64(d->setRunwayReciprocal, 2, recip);
2091 d->execUpdate(d->setRunwayReciprocal);
2092
2093 // and the opposite direction too!
2094 sqlite3_bind_int64(d->setRunwayReciprocal, 2, runway);
2095 sqlite3_bind_int64(d->setRunwayReciprocal, 1, recip);
2096 d->execUpdate(d->setRunwayReciprocal);
2097 }
2098
2099 void NavDataCache::setRunwayILS(PositionedID runway, PositionedID ils)
2100 {
2101 sqlite3_bind_int64(d->setRunwayILS, 1, runway);
2102 sqlite3_bind_int64(d->setRunwayILS, 2, ils);
2103 d->execUpdate(d->setRunwayILS);
2104
2105 // and the in-memory one
2106 if (d->cache.find(runway) != d->cache.end()) {
2107 FGRunway* instance = (FGRunway*) d->cache[runway].ptr();
2108 instance->setILS(ils);
2109 }
2110 }
2111
2112 PositionedID
2113 NavDataCache::insertNavaid(FGPositioned::Type ty, const string& ident,
2114 const string& name, const SGGeod& pos,
2115 int freq, int range, double multiuse,
2116 PositionedID apt, PositionedID runway)
2117 {
2118 bool spatialIndex = true;
2119 if (ty == FGPositioned::MOBILE_TACAN) {
2120 spatialIndex = false;
2121 }
2122
2123 sqlite3_int64 rowId = d->insertPositioned(ty, ident, name, pos, apt,
2124 spatialIndex);
2125 sqlite3_bind_int64(d->insertNavaid, 1, rowId);
2126 sqlite3_bind_int(d->insertNavaid, 2, freq);
2127 sqlite3_bind_int(d->insertNavaid, 3, range);
2128 sqlite3_bind_double(d->insertNavaid, 4, multiuse);
2129 sqlite3_bind_int64(d->insertNavaid, 5, runway);
2130 sqlite3_bind_int64(d->insertNavaid, 6, 0);
2131 return d->execInsert(d->insertNavaid);
2132 }
2133
2134 void NavDataCache::setNavaidColocated(PositionedID navaid, PositionedID colocatedDME)
2135 {
2136 // Update DB entries...
2137 sqlite3_bind_int64(d->setNavaidColocated, 1, navaid);
2138 sqlite3_bind_int64(d->setNavaidColocated, 2, colocatedDME);
2139 d->execUpdate(d->setNavaidColocated);
2140
2141 // ...and the in-memory copy of the navrecord
2142 if (d->cache.find(navaid) != d->cache.end()) {
2143 FGNavRecord* rec = (FGNavRecord*) d->cache[navaid].get();
2144 rec->setColocatedDME(colocatedDME);
2145 }
2146 }
2147
2148 PositionedID NavDataCache::insertCommStation(FGPositioned::Type ty,
2149 const string& name, const SGGeod& pos, int freq, int range,
2150 PositionedID apt)
2151 {
2152 sqlite3_int64 rowId = d->insertPositioned(ty, "", name, pos, apt, true);
2153 sqlite3_bind_int64(d->insertCommStation, 1, rowId);
2154 sqlite3_bind_int(d->insertCommStation, 2, freq);
2155 sqlite3_bind_int(d->insertCommStation, 3, range);
2156 return d->execInsert(d->insertCommStation);
2157 }
2158
2159 PositionedID NavDataCache::createPOI(FGPositioned::Type ty, const std::string& ident, const SGGeod& aPos,
2160 const std::string& name, bool isTransient)
2161 {
2162 if (isTransient) {
2163 return d->insertTemporaryPositioned(createTransientID(), ty, ident, name, aPos,
2164 true /* spatial index */);
2165 } else {
2166 return d->insertPositioned(ty, ident, name, aPos, 0,
2167 true /* spatial index */);
2168 }
2169
2170 }
2171
2172 bool NavDataCache::removePOI(FGPositionedRef ref)
2173 {
2174 const bool isTemporary = ref->guid() < 0;
2175 // remove from the octree if temporary.
2176 if (isTemporary) {
2177 auto octreeLeaf = Octree::globalTransientOctree()->findLeafForPos(ref->cart());
2178 octreeLeaf->removeChild(ref->guid());
2179 }
2180
2181 d->removePositioned(ref->guid());
2182
2183 auto it = d->cache.find(ref->guid());
2184 d->cache.erase(it);
2185
2186 return true;
2187 }
2188
2189 void NavDataCache::setAirportMetar(const string& icao, bool hasMetar)
2190 {
2191 sqlite_bind_stdstring(d->setAirportMetar, 1, icao);
2192 sqlite3_bind_int(d->setAirportMetar, 2, hasMetar);
2193 d->execUpdate(d->setAirportMetar);
2194 }
2195
2196 //------------------------------------------------------------------------------
2197 FGPositionedList NavDataCache::findAllWithIdent( const string& s,
2198 FGPositioned::Filter* filter,
2199 bool exact )
2200 {
2201 return d->findAllByString(s, "ident", filter, exact);
2202 }
2203
2204 //------------------------------------------------------------------------------
2205 FGPositionedList NavDataCache::findAllWithName( const string& s,
2206 FGPositioned::Filter* filter,
2207 bool exact )
2208 {
2209 return d->findAllByString(s, "name", filter, exact);
2210 }
2211
2212 //------------------------------------------------------------------------------
2213 FGPositionedRef NavDataCache::findClosestWithIdent( const string& aIdent,
2214 const SGGeod& aPos,
2215 FGPositioned::Filter* aFilter )
2216 {
2217 sqlite_bind_stdstring(d->findClosestWithIdent, 1, aIdent);
2218 if (aFilter) {
2219 sqlite3_bind_int(d->findClosestWithIdent, 2, aFilter->minType());
2220 sqlite3_bind_int(d->findClosestWithIdent, 3, aFilter->maxType());
2221 } else { // full type range
2222 sqlite3_bind_int(d->findClosestWithIdent, 2, FGPositioned::INVALID);
2223 sqlite3_bind_int(d->findClosestWithIdent, 3, FGPositioned::LAST_TYPE);
2224 }
2225
2226 SGVec3d cartPos(SGVec3d::fromGeod(aPos));
2227 sqlite3_bind_double(d->findClosestWithIdent, 4, cartPos.x());
2228 sqlite3_bind_double(d->findClosestWithIdent, 5, cartPos.y());
2229 sqlite3_bind_double(d->findClosestWithIdent, 6, cartPos.z());
2230
2231 FGPositionedRef result;
2232
2233 while (d->stepSelect(d->findClosestWithIdent)) {
2234 FGPositionedRef pos = loadById(sqlite3_column_int64(d->findClosestWithIdent, 0));
2235 if (aFilter && !aFilter->pass(pos)) {
2236 continue;
2237 }
2238
2239 result = pos;
2240 break;
2241 }
2242
2243 d->reset(d->findClosestWithIdent);
2244 return result;
2245 }
2246
2247
2248 int NavDataCache::getOctreeBranchChildren(int64_t octreeNodeId)
2249 {
2250 sqlite3_bind_int64(d->getOctreeChildren, 1, octreeNodeId);
2251 if (!d->execSelect(d->getOctreeChildren)) {
2252 // this can occur when in read-only mode: we don't add
2253 // new Octree nodes to the real DB (only in memory),
2254 // but will still call this code speculatively.
2255 // see the early-return just below in defineOctreeNode
2256 return 0;
2257 }
2258
2259 int children = sqlite3_column_int(d->getOctreeChildren, 0);
2260 d->reset(d->getOctreeChildren);
2261 return children;
2262 }
2263
2264 void NavDataCache::defineOctreeNode(Octree::Branch* pr, Octree::Node* nd)
2265 {
2266 if (isReadOnly()) {
2267 return;
2268 }
2269
2270 sqlite3_bind_int64(d->insertOctree, 1, nd->guid());
2271 d->execInsert(d->insertOctree);
2272
2273 #ifdef LAZY_OCTREE_UPDATES
2274 d->deferredOctreeUpdates.insert(pr);
2275 #else
2276 // lowest three bits of node ID are 0..7 index of the child in the parent
2277 int childIndex = nd->guid() & 0x07;
2278
2279 sqlite3_bind_int64(d->updateOctreeChildren, 1, pr->guid());
2280 // mask has bit N set where child N exists
2281 int childMask = 1 << childIndex;
2282 sqlite3_bind_int(d->updateOctreeChildren, 2, childMask);
2283 d->execUpdate(d->updateOctreeChildren);
2284 #endif
2285 }
2286
2287 TypedPositionedVec
2288 NavDataCache::getOctreeLeafChildren(int64_t octreeNodeId)
2289 {
2290 sqlite3_bind_int64(d->getOctreeLeafChildren, 1, octreeNodeId);
2291
2292 TypedPositionedVec r;
2293 while (d->stepSelect(d->getOctreeLeafChildren)) {
2294 FGPositioned::Type ty = static_cast<FGPositioned::Type>
2295 (sqlite3_column_int(d->getOctreeLeafChildren, 1));
2296 r.push_back(std::make_pair(ty,
2297 sqlite3_column_int64(d->getOctreeLeafChildren, 0)));
2298 }
2299
2300 d->reset(d->getOctreeLeafChildren);
2301 return r;
2302 }
2303
2304
2305 /**
2306 * A special purpose helper (used by FGAirport::searchNamesAndIdents) to
2307 * implement the AirportList dialog. It's unfortunate that it needs to reside
2308 * here, but for now it's least ugly solution.
2309 */
2310 char** NavDataCache::searchAirportNamesAndIdents(const std::string& searchInput)
2311 {
2312 sqlite3_stmt_ptr stmt;
2313 unsigned int numMatches = 0, numAllocated = 16;
2314 string heliport("HELIPORT");
2315 bool heli_p = searchInput.substr(0, heliport.length()) == heliport;
2316 auto pos = searchInput.find(":");
2317 string aFilter((pos != string::npos) ? searchInput.substr(pos+1) : searchInput);
2318 string searchTerm("%" + aFilter + "%");
2319
2320 if (aFilter.empty() && !heli_p) {
2321 stmt = d->getAllAirports;
2322 numAllocated = 4096; // start much larger for all airports
2323 } else {
2324 stmt = d->searchAirports;
2325 sqlite_bind_stdstring(stmt, 1, searchTerm);
2326 if (heli_p) {
2327 sqlite3_bind_int(stmt, 2, FGPositioned::HELIPORT);
2328 sqlite3_bind_int(stmt, 3, FGPositioned::HELIPORT);
2329 }
2330 else {
2331 sqlite3_bind_int(stmt, 2, FGPositioned::AIRPORT);
2332 sqlite3_bind_int(stmt, 3, FGPositioned::SEAPORT);
2333 }
2334 }
2335
2336 char** result = (char**) malloc(sizeof(char*) * numAllocated);
2337 while (d->stepSelect(stmt)) {
2338 if ((numMatches + 1) >= numAllocated) {
2339 numAllocated <<= 1; // double in size!
2340 // reallocate results array
2341 char** nresult = (char**) malloc(sizeof(char*) * numAllocated);
2342 memcpy(nresult, result, sizeof(char*) * numMatches);
2343 free(result);
2344 result = nresult;
2345 }
2346
2347 // nasty code to avoid excessive string copying and allocations.
2348 // We format results as follows (note whitespace!):
2349 // ' name-of-airport-chars (ident)'
2350 // so the total length is:
2351 // 1 + strlen(name) + 4 + strlen(icao) + 1 + 1 (for the null)
2352 // which gives a grand total of 7 + name-length + icao-length.
2353 // note the ident can be three letters (non-ICAO local strip), four
2354 // (default ICAO) or more (extended format ICAO)
2355 int nameLength = sqlite3_column_bytes(stmt, 1);
2356 int icaoLength = sqlite3_column_bytes(stmt, 0);
2357 char* entry = (char*) malloc(7 + nameLength + icaoLength);
2358 char* dst = entry;
2359 *dst++ = ' ';
2360 memcpy(dst, sqlite3_column_text(stmt, 1), nameLength);
2361 dst += nameLength;
2362 *dst++ = ' ';
2363 *dst++ = ' ';
2364 *dst++ = ' ';
2365 *dst++ = '(';
2366 memcpy(dst, sqlite3_column_text(stmt, 0), icaoLength);
2367 dst += icaoLength;
2368 *dst++ = ')';
2369 *dst++ = 0;
2370
2371 result[numMatches++] = entry;
2372 }
2373
2374 result[numMatches] = NULL; // end of list marker
2375 d->reset(stmt);
2376 return result;
2377 }
2378
2379 FGPositionedRef
2380 NavDataCache::findCommByFreq(int freqKhz, const SGGeod& aPos, FGPositioned::Filter* aFilter)
2381 {
2382 auto matches = findCommsByFreq(freqKhz, aPos, aFilter);
2383 if (matches.empty()) {
2384 return {};
2385 }
2386
2387 return loadById(matches.front());
2388 }
2389
2390 PositionedIDVec
2391 NavDataCache::findCommsByFreq(int freqKhz, const SGGeod& aPos, FGPositioned::Filter* aFilter)
2392 {
2393 PositionedIDVec matches;
2394
2395 sqlite3_bind_int(d->findCommByFreq, 1, freqKhz);
2396 if (aFilter) {
2397 sqlite3_bind_int(d->findCommByFreq, 2, aFilter->minType());
2398 sqlite3_bind_int(d->findCommByFreq, 3, aFilter->maxType());
2399 } else { // full type range
2400 sqlite3_bind_int(d->findCommByFreq, 2, FGPositioned::FREQ_GROUND);
2401 sqlite3_bind_int(d->findCommByFreq, 3, FGPositioned::FREQ_UNICOM);
2402 }
2403
2404 SGVec3d cartPos(SGVec3d::fromGeod(aPos));
2405 sqlite3_bind_double(d->findCommByFreq, 4, cartPos.x());
2406 sqlite3_bind_double(d->findCommByFreq, 5, cartPos.y());
2407 sqlite3_bind_double(d->findCommByFreq, 6, cartPos.z());
2408 FGPositionedRef result;
2409
2410 while (d->execSelect(d->findCommByFreq)) {
2411 const auto id = sqlite3_column_int64(d->findCommByFreq, 0);
2412 if (aFilter) {
2413 FGPositionedRef p = loadById(id);
2414 if (aFilter && !aFilter->pass(p)) {
2415 continue;
2416 }
2417 }
2418
2419
2420 matches.push_back(id);
2421 }
2422
2423 d->reset(d->findCommByFreq);
2424 return matches;
2425 }
2426
2427 PositionedIDVec
2428 NavDataCache::findNavaidsByFreq(int freqKhz, const SGGeod& aPos, FGPositioned::Filter* aFilter)
2429 {
2430 sqlite3_bind_int(d->findNavsByFreq, 1, freqKhz);
2431 if (aFilter) {
2432 sqlite3_bind_int(d->findNavsByFreq, 2, aFilter->minType());
2433 sqlite3_bind_int(d->findNavsByFreq, 3, aFilter->maxType());
2434 } else { // full type range
2435 sqlite3_bind_int(d->findNavsByFreq, 2, FGPositioned::NDB);
2436 sqlite3_bind_int(d->findNavsByFreq, 3, FGPositioned::GS);
2437 }
2438
2439 SGVec3d cartPos(SGVec3d::fromGeod(aPos));
2440 sqlite3_bind_double(d->findNavsByFreq, 4, cartPos.x());
2441 sqlite3_bind_double(d->findNavsByFreq, 5, cartPos.y());
2442 sqlite3_bind_double(d->findNavsByFreq, 6, cartPos.z());
2443
2444 return d->selectIds(d->findNavsByFreq);
2445 }
2446
2447 PositionedIDVec
2448 NavDataCache::findNavaidsByFreq(int freqKhz, FGPositioned::Filter* aFilter)
2449 {
2450 sqlite3_bind_int(d->findNavsByFreqNoPos, 1, freqKhz);
2451 if (aFilter) {
2452 sqlite3_bind_int(d->findNavsByFreqNoPos, 2, aFilter->minType());
2453 sqlite3_bind_int(d->findNavsByFreqNoPos, 3, aFilter->maxType());
2454 } else { // full type range
2455 sqlite3_bind_int(d->findNavsByFreqNoPos, 2, FGPositioned::NDB);
2456 sqlite3_bind_int(d->findNavsByFreqNoPos, 3, FGPositioned::GS);
2457 }
2458
2459 return d->selectIds(d->findNavsByFreqNoPos);
2460 }
2461
2462 PositionedIDVec
2463 NavDataCache::airportItemsOfType(PositionedID apt,FGPositioned::Type ty,
2464 FGPositioned::Type maxTy)
2465 {
2466 if (maxTy == FGPositioned::INVALID) {
2467 maxTy = ty; // single-type range
2468 }
2469
2470 sqlite3_bind_int64(d->getAirportItems, 1, apt);
2471 sqlite3_bind_int(d->getAirportItems, 2, ty);
2472 sqlite3_bind_int(d->getAirportItems, 3, maxTy);
2473
2474 return d->selectIds(d->getAirportItems);
2475 }
2476
2477 PositionedID
2478 NavDataCache::airportItemWithIdent(PositionedID apt, FGPositioned::Type ty,
2479 const std::string& ident)
2480 {
2481 sqlite3_bind_int64(d->getAirportItemByIdent, 1, apt);
2482 sqlite_bind_stdstring(d->getAirportItemByIdent, 2, ident);
2483 sqlite3_bind_int(d->getAirportItemByIdent, 3, ty);
2484 PositionedID result = 0;
2485
2486 if (d->execSelect(d->getAirportItemByIdent)) {
2487 result = sqlite3_column_int64(d->getAirportItemByIdent, 0);
2488 }
2489
2490 d->reset(d->getAirportItemByIdent);
2491 return result;
2492 }
2493
2494 AirportRunwayPair
2495 NavDataCache::findAirportRunway(const std::string& aName)
2496 {
2497 if (aName.empty()) {
2498 return AirportRunwayPair();
2499 }
2500
2501 string_list parts = simgear::strutils::split(aName);
2502 if (parts.size() < 2) {
2503 SG_LOG(SG_NAVCACHE, SG_WARN, "findAirportRunway: malformed name:" << aName);
2504 return AirportRunwayPair();
2505 }
2506
2507 AirportRunwayPair result;
2508 sqlite_bind_stdstring(d->findAirportRunway, 1, parts[0]);
2509 const auto cleanedRunway = cleanRunwayNo(parts[1]);
2510 sqlite_bind_stdstring(d->findAirportRunway, 2, cleanedRunway);
2511
2512 if (d->execSelect(d->findAirportRunway)) {
2513 result = AirportRunwayPair(sqlite3_column_int64(d->findAirportRunway, 0),
2514 sqlite3_column_int64(d->findAirportRunway, 1));
2515
2516 } else {
2517 SG_LOG(SG_NAVCACHE, SG_WARN, "findAirportRunway: unknown airport/runway:" << aName);
2518 }
2519
2520 d->reset(d->findAirportRunway);
2521 return result;
2522 }
2523
2524 PositionedID
2525 NavDataCache::findILS(PositionedID airport, const string& aRunway, const string& navIdent)
2526 {
2527 string runway(cleanRunwayNo(aRunway));
2528
2529 sqlite_bind_stdstring(d->findILS, 1, navIdent);
2530 sqlite3_bind_int64(d->findILS, 2, airport);
2531 sqlite_bind_stdstring(d->findILS, 3, runway);
2532 PositionedID result = 0;
2533 if (d->execSelect(d->findILS)) {
2534 result = sqlite3_column_int64(d->findILS, 0);
2535 }
2536
2537 d->reset(d->findILS);
2538 return result;
2539 }
2540
2541 int NavDataCache::findAirway(int network, const string& aName, bool create)
2542 {
2543 assert((network == 1) || (network == 2));
2544
2545 sqlite3_bind_int(d->findAirwayNet, 1, network);
2546 sqlite_bind_stdstring(d->findAirwayNet, 2, aName);
2547
2548 int airway = 0;
2549 if (d->execSelect(d->findAirwayNet)) {
2550 // already exists
2551 airway = sqlite3_column_int(d->findAirwayNet, 0);
2552 } else if (create) {
2553 d->reset(d->insertAirway);
2554 sqlite_bind_stdstring(d->insertAirway, 1, aName);
2555 sqlite3_bind_int(d->insertAirway, 2, network);
2556 airway = d->execInsert(d->insertAirway);
2557 } else {
2558 // doesn't exist but don't create
2559 }
2560
2561 d->reset(d->findAirwayNet);
2562 return airway;
2563 }
2564
2565 int NavDataCache::findAirway(const string& aName)
2566 {
2567 sqlite_bind_stdstring(d->findAirway, 1, aName);
2568
2569 int airway = 0;
2570 if (d->execSelect(d->findAirway)) {
2571 // already exists
2572 airway = sqlite3_column_int(d->findAirway, 0);
2573 }
2574
2575 d->reset(d->findAirway);
2576 return airway;
2577 }
2578
2579
2580 void NavDataCache::insertEdge(int network, int airwayID, PositionedID from, PositionedID to)
2581 {
2582 sqlite3_bind_int(d->insertAirwayEdge, 1, network);
2583 sqlite3_bind_int(d->insertAirwayEdge, 2, airwayID);
2584 sqlite3_bind_int64(d->insertAirwayEdge, 3, from);
2585 sqlite3_bind_int64(d->insertAirwayEdge, 4, to);
2586 d->execInsert(d->insertAirwayEdge);
2587 }
2588
2589 bool NavDataCache::isInAirwayNetwork(int network, PositionedID pos)
2590 {
2591 sqlite3_bind_int(d->isPosInAirway, 1, network);
2592 sqlite3_bind_int64(d->isPosInAirway, 2, pos);
2593 bool ok = d->execSelect(d->isPosInAirway);
2594 d->reset(d->isPosInAirway);
2595
2596 return ok;
2597 }
2598
2599 AirwayEdgeVec NavDataCache::airwayEdgesFrom(int network, PositionedID pos)
2600 {
2601 sqlite3_bind_int(d->airwayEdgesFrom, 1, network);
2602 sqlite3_bind_int64(d->airwayEdgesFrom, 2, pos);
2603
2604 AirwayEdgeVec result;
2605 while (d->stepSelect(d->airwayEdgesFrom)) {
2606 result.push_back(AirwayEdge(
2607 sqlite3_column_int(d->airwayEdgesFrom, 0),
2608 sqlite3_column_int64(d->airwayEdgesFrom, 1)
2609 ));
2610 }
2611
2612 d->reset(d->airwayEdgesFrom);
2613
2614 // find bidirectional / backwsards edges
2615 // at present all edges are bidirectional
2616 sqlite3_bind_int(d->airwayEdgesTo, 1, network);
2617 sqlite3_bind_int64(d->airwayEdgesTo, 2, pos);
2618
2619 while (d->stepSelect(d->airwayEdgesTo)) {
2620 result.push_back(AirwayEdge(
2621 sqlite3_column_int(d->airwayEdgesTo, 0),
2622 sqlite3_column_int64(d->airwayEdgesTo, 1)
2623 ));
2624 }
2625
2626 d->reset(d->airwayEdgesTo);
2627
2628 return result;
2629 }
2630
2631 AirwayRef NavDataCache::loadAirway(int airwayID)
2632 {
2633 sqlite3_bind_int(d->loadAirway, 1, airwayID);
2634 bool ok = d->execSelect(d->loadAirway);
2635 AirwayRef result;
2636 if (ok) {
2637 string ident = (char*) sqlite3_column_text(d->loadAirway, 0);
2638 Airway::Level network = static_cast<Airway::Level>(sqlite3_column_int(d->loadAirway, 1));
2639 result = new Airway(ident, network, airwayID, 0, 0);
2640 }
2641 d->reset(d->loadAirway);
2642 return result;
2643 }
2644
2645 PositionedIDVec NavDataCache::airwayWaypts(int id)
2646 {
2647 d->reset(d->airwayEdges);
2648 sqlite3_bind_int(d->airwayEdges, 1, id);
2649
2650 typedef std::pair<PositionedID, PositionedID> Edge;
2651 typedef std::deque<Edge> EdgeVec;
2652 typedef std::deque<PositionedID> PositionedIDDeque;
2653
2654 // build up the EdgeVec, order is arbitrary
2655 EdgeVec rawEdges;
2656 while (d->stepSelect(d->airwayEdges)) {
2657 rawEdges.push_back(Edge(sqlite3_column_int64(d->airwayEdges, 0),
2658 sqlite3_column_int64(d->airwayEdges, 1)
2659 ));
2660 }
2661
2662 d->reset(d->airwayEdges);
2663 if (rawEdges.empty()) {
2664 return {};
2665 }
2666
2667 // linearize
2668 PositionedIDVec result;
2669
2670 while (!rawEdges.empty()) {
2671 bool didAddEdge = false;
2672 std::set<PositionedID> seen;
2673 EdgeVec nextDeque;
2674 PositionedIDDeque linearAirway;
2675 PositionedID firstId = rawEdges.front().first,
2676 lastId = rawEdges.front().second;
2677
2678 // first edge is trivial
2679 linearAirway.push_back(firstId);
2680 linearAirway.push_back(lastId);
2681 seen.insert(firstId);
2682 seen.insert(lastId);
2683 rawEdges.pop_front();
2684
2685 while (!rawEdges.empty()) {
2686 Edge e = rawEdges.front();
2687 rawEdges.pop_front();
2688
2689 bool seenFirst = (seen.find(e.first) != seen.end());
2690 bool seenSecond = (seen.find(e.second) != seen.end());
2691
2692 // duplicated segment, should be impossible
2693 assert(!(seenFirst && seenSecond));
2694
2695 if (!seenFirst && !seenSecond) {
2696 // push back to try later on
2697 nextDeque.push_back(e);
2698 if (rawEdges.empty()) {
2699 rawEdges = nextDeque;
2700 nextDeque.clear();
2701
2702 if (!didAddEdge) {
2703 // we have a disjoint, need to start a new section
2704 // break out of the inner while loop so the outer
2705 // one can process and restart
2706 break;
2707 }
2708 didAddEdge = false;
2709 }
2710
2711 continue;
2712 }
2713
2714 // we have an exterior edge, grow our current linear piece
2715 if (seenFirst && (e.first == firstId)) {
2716 linearAirway.push_front(e.second);
2717 firstId = e.second;
2718 seen.insert(e.second);
2719 } else if (seenSecond && (e.second == firstId)) {
2720 linearAirway.push_front(e.first);
2721 firstId = e.first;
2722 seen.insert(e.first);
2723 } else if (seenFirst && (e.first == lastId)) {
2724 linearAirway.push_back(e.second);
2725 lastId = e.second;
2726 seen.insert(e.second);
2727 } else if (seenSecond && (e.second == lastId)) {
2728 linearAirway.push_back(e.first);
2729 lastId = e.first;
2730 seen.insert(e.first);
2731 }
2732 didAddEdge = true;
2733
2734 if (rawEdges.empty()) {
2735 rawEdges = nextDeque;
2736 nextDeque.clear();
2737 }
2738 }
2739
2740 if (!result.empty())
2741 result.push_back(0);
2742 result.insert(result.end(), linearAirway.begin(), linearAirway.end());
2743 } // outer loop
2744
2745 SG_LOG(SG_AUTOPILOT, SG_WARN, "Airway:" << id);
2746 for (unsigned int i=0; i<result.size(); ++i) {
2747 if (result.at(i) == 0) {
2748 SG_LOG(SG_AUTOPILOT, SG_WARN, i << " <break>");
2749 } else {
2750 SG_LOG(SG_AUTOPILOT, SG_WARN, i << " " << loadById(result.at(i))->ident());
2751
2752 }
2753 }
2754
2755 return result;
2756 }
2757
2758 PositionedID NavDataCache::findNavaidForRunway(PositionedID runway, FGPositioned::Type ty)
2759 {
2760 sqlite3_bind_int64(d->findNavaidForRunway, 1, runway);
2761 sqlite3_bind_int(d->findNavaidForRunway, 2, ty);
2762
2763 PositionedID result = 0;
2764 if (d->execSelect(d->findNavaidForRunway)) {
2765 result = sqlite3_column_int64(d->findNavaidForRunway, 0);
2766 }
2767
2768 d->reset(d->findNavaidForRunway);
2769 return result;
2770 }
2771
2772 bool NavDataCache::isReadOnly() const
2773 {
2774 return d->readOnly;
2775 }
2776
2777 SGPath NavDataCache::path() const
2778 {
2779 return d->path;
2780 }
2781
2782 PositionedID NavDataCache::createTransientID()
2783 {
2784 return d->nextTransientId--;
2785 }
2786
2787 /////////////////////////////////////////////////////////////////////////////////////////
2788 // Transaction RAII object
2789
2790 NavDataCache::Transaction::Transaction(NavDataCache* cache) :
2791 _instance(cache),
2792 _committed(false)
2793 {
2794 assert(cache);
2795 if (!cache->isReadOnly()) {
2796 _instance->beginTransaction();
2797 }
2798 }
2799
2800 NavDataCache::Transaction::~Transaction()
2801 {
2802 if (_instance->d->abandonCache || _instance->isReadOnly()) {
2803 return;
2804 }
2805
2806 if (!_committed) {
2807 SG_LOG(SG_NAVCACHE, SG_INFO, "aborting cache transaction!");
2808 _instance->abortTransaction();
2809 }
2810 }
2811
2812 void NavDataCache::Transaction::commit()
2813 {
2814 if (_instance->isReadOnly()) {
2815 return;
2816 }
2817
2818 assert(!_committed);
2819 _committed = true;
2820 _instance->commitTransaction();
2821 }
2822
2823 /////////////////////////////////////////////////////////////////////////////
2824
2825 class NavDataCache::ThreadedGUISearch::ThreadedGUISearchPrivate : public SGThread
2826 {
2827 public:
2828 ThreadedGUISearchPrivate() :
2829 db(NULL),
2830 isComplete(false),
2831 quit(false)
2832 {}
2833
2834 virtual void run()
2835 {
2836 while (!quit) {
2837 int err = sqlite3_step(query);
2838 if (err == SQLITE_DONE) {
2839 break;
2840 } else if (err == SQLITE_ROW) {
2841 PositionedID r = sqlite3_column_int64(query, 0);
2842 std::lock_guard<std::mutex> g(lock);
2843 results.push_back(r);
2844 } else if (err == SQLITE_BUSY) {
2845 // sleep a tiny amount
2846 SGTimeStamp::sleepForMSec(1);
2847 } else {
2848 std::string errMsg = sqlite3_errmsg(db);
2849 SG_LOG(SG_NAVCACHE, SG_ALERT, "Sqlite error:" << errMsg << " running threaded search query");
2850 }
2851 }
2852
2853 std::lock_guard<std::mutex> g(lock);
2854 isComplete = true;
2855 }
2856
2857 std::mutex lock;
2858 sqlite3* db;
2859 sqlite3_stmt_ptr query;
2860 PositionedIDVec results;
2861 bool isComplete;
2862 bool quit;
2863 };
2864
2865 NavDataCache::ThreadedGUISearch::ThreadedGUISearch(const std::string& term, bool onlyAirports) :
2866 d(new ThreadedGUISearchPrivate)
2867 {
2868 SGPath p = NavDataCache::instance()->path();
2869 int openFlags = SQLITE_OPEN_READONLY;
2870 std::string pathUtf8 = p.utf8Str();
2871 sqlite3_open_v2(pathUtf8.c_str(), &d->db, openFlags, NULL);
2872
2873 std::string sql;
2874 if (onlyAirports) {
2875 sql = "SELECT rowid FROM positioned WHERE name LIKE '%" + term
2876 + "%' AND (type >= 1 AND type <= 3)";
2877 } else {
2878 // types are hard-coded here becuase this is only used by NavaidSearchModel
2879 // in ther launcher. We would ideally use a TypeFilter but that would
2880 // mean loading each positioned to filter them, which is inefficient.
2881 sql = "SELECT rowid FROM positioned WHERE name LIKE '%" + term
2882 + "%' AND ((type >= 1 AND type <= 3) OR ((type >= 9 AND type <= 11)) OR (type=18 AND name LIKE '% TACAN') ) ";
2883 }
2884 sqlite3_prepare_v2(d->db, sql.c_str(), sql.length(), &d->query, NULL);
2885
2886 d->start();
2887 }
2888
2889 NavDataCache::ThreadedGUISearch::~ThreadedGUISearch()
2890 {
2891 {
2892 std::lock_guard<std::mutex> g(d->lock);
2893 d->quit = true;
2894 }
2895
2896 d->join();
2897 sqlite3_finalize(d->query);
2898 sqlite3_close_v2(d->db);
2899 }
2900
2901 PositionedIDVec NavDataCache::ThreadedGUISearch::results() const
2902 {
2903 PositionedIDVec r;
2904 {
2905 std::lock_guard<std::mutex> g(d->lock);
2906 r = std::move(d->results);
2907 }
2908 return r;
2909 }
2910
2911 bool NavDataCache::ThreadedGUISearch::isComplete() const
2912 {
2913 std::lock_guard<std::mutex> g(d->lock);
2914 return d->isComplete;
2915 }
2916
2917 } // of namespace flightgear