Remove uses of .str(), .c_str() and some other methods of SGPath.
Pass SGPath directly where possible, or explicitly convert to the
appropriate 8-bit encoding.
BOOST_FOREACH(SGPath p, globals->get_data_paths("AI")) {
p.append(model_path);
if (p.exists()) {
- f = p.str();
+ f = p.local8BitStr();
break;
}
} // of AI data paths iteration
/** Write flight recorder tape with given filename and meta properties to disk */
bool
-FGReplay::saveTape(const char* Filename, SGPropertyNode* MetaDataProps)
+FGReplay::saveTape(const SGPath& Filename, SGPropertyNode* MetaDataProps)
{
bool ok = true;
/* open output stream *******************************************/
- gzContainerWriter output(Filename, FlightRecorderFileMagic);
+ gzContainerWriter output(Filename.local8BitStr(), FlightRecorderFileMagic);
if (!output.good())
{
SG_LOG(SG_SYSTEMS, SG_ALERT, "Cannot open file" << Filename);
}
if (ok)
- ok &= saveTape(p.c_str(), myMetaData.get());
+ ok &= saveTape(p, myMetaData.get());
if (ok)
guiMessage("Flight recorder tape saved successfully!");
* Actual data and signal configuration is not read when in "Preview" mode.
*/
bool
-FGReplay::loadTape(const char* Filename, bool Preview, SGPropertyNode* UserData)
+FGReplay::loadTape(const SGPath& Filename, bool Preview, SGPropertyNode* UserData)
{
bool ok = true;
/* open input stream ********************************************/
- gzContainerReader input(Filename, FlightRecorderFileMagic);
+ gzContainerReader input(Filename.local8BitStr(), FlightRecorderFileMagic);
if (input.eof() || !input.good())
{
SG_LOG(SG_SYSTEMS, SG_ALERT, "Cannot open file " << Filename);
tapeDirectory.append(tape);
tapeDirectory.concat(".fgtape");
SG_LOG(SG_SYSTEMS, MY_SG_DEBUG, "Checking flight recorder file " << tapeDirectory << ", preview: " << Preview);
- return loadTape(tapeDirectory.c_str(), Preview, UserData);
+ return loadTape(tapeDirectory, Preview, UserData);
}
}
double get_end_time();
bool listTapes(bool SameAircraftFilter, const SGPath& tapeDirectory);
- bool saveTape(const char* Filename, SGPropertyNode* MetaData);
- bool loadTape(const char* Filename, bool Preview, SGPropertyNode* UserData);
+ bool saveTape(const SGPath& Filename, SGPropertyNode* MetaData);
+ bool loadTape(const SGPath& Filename, bool Preview, SGPropertyNode* UserData);
double sim_time;
double last_mt_time;
{
SGPath tpath = globals->resolve_resource_path(path);
if( !tpath.isNull() )
- return osgDB::readRefImageFile(tpath.c_str());
+ return osgDB::readRefImageFile(tpath.local8BitStr());
SG_LOG(SG_IO, SG_ALERT, "canvas::Image: No such image: '" << path << "'");
}
}
osg::ref_ptr<osgDB::ReaderWriter::Options> fontOptions = new osgDB::ReaderWriter::Options("monochrome");
- osg::ref_ptr<osgText::Font> font = osgText::readFontFile(tpath.c_str(), fontOptions.get());
+ osg::ref_ptr<osgText::Font> font = osgText::readFontFile(tpath.local8BitStr(), fontOptions.get());
if (font != 0) {
_font = font;
}
osg::ref_ptr<osgDB::ReaderWriter::Options> fontOptions = new osgDB::ReaderWriter::Options("monochrome");
- osg::ref_ptr<osgText::Font> font = osgText::readFontFile(tpath.c_str(), fontOptions.get());
+ osg::ref_ptr<osgText::Font> font = osgText::readFontFile(tpath.local8BitStr(), fontOptions.get());
if (font != 0) {
_font = font;
{
SGPath ephem_data_path(globals->get_fg_root());
ephem_data_path.append("Astro");
- _impl = new SGEphemeris(ephem_data_path.c_str());
+ _impl = new SGEphemeris(ephem_data_path.local8BitStr());
tieStar("/ephemeris/sun/xs", _impl->get_sun(), &Star::getxs);
tieStar("/ephemeris/sun/ys", _impl->get_sun(), &Star::getys);
if (result == NSFileHandlingPanelOKButton) {
completion_path = [[d->panel URL] path];
//NSLog(@"the URL is: %@", d->panel URL]);
- completion_sgpath = ([completion_path UTF8String]);
+ completion_sgpath = SGPath::fromUtf8([completion_path UTF8String]);
_callback->onFileDialogDone(this, completion_sgpath);
}
}];
NSCursor* cocoaCursorForKey(FGMouseCursor::Cursor aKey)
{
NSImage* img = nil;
-
- NSString* path = [NSString stringWithCString:globals->get_fg_root().c_str()
- encoding:NSUTF8StringEncoding];
+
+ std::string p = globals->get_fg_root().utf8Str();
+ NSString* path = [NSString stringWithCString:p.c_str() encoding:NSUTF8StringEncoding];
path = [path stringByAppendingPathComponent:@"gui"];
switch (aKey) {
{
static std::string fontext("txf");
init();
- ulDir* fontdir = ulOpenDir(_path.c_str());
+ std::string fontPath = _path.local8BitStr();
+ ulDir* fontdir = ulOpenDir(fontPath.c_str());
if (!fontdir)
return false;
const ulDirEnt *dirEntry;
path.append(dirEntry->d_name);
if (path.extension() == fontext) {
fntTexFont* f = new fntTexFont;
- if (f->load((char *)path.c_str()))
+ std::string ps = path.local8BitStr();
+ if (f->load(ps.c_str()))
_texFonts[std::string(dirEntry->d_name)] = f;
else
delete f;
{
ui->setupUi(this);
if (m_downloadDir.isEmpty()) {
- m_downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
+ m_downloadDir = QString::fromStdString(flightgear::defaultDownloadDir().utf8Str());
}
QString baseIntroString = ui->introText->text();
SGPropertyNode_ptr dlg = _dialogRoot->getChild("dialog", 0, true);
SGPath dlgXML = globals->resolve_resource_path("gui/dialogs/file-select.xml");
- readProperties(dlgXML.str(), dlg);
+ readProperties(dlgXML, dlg);
dlg->setStringValue("name", name);
gui->newDialog(dlg);
_dialogRoot->setStringValue("title", _title);
_dialogRoot->setStringValue("button", _buttonText);
- _dialogRoot->setStringValue("directory", _initialPath.str());
+ _dialogRoot->setStringValue("directory", _initialPath.utf8Str());
_dialogRoot->setStringValue("selection", _placeholder);
// convert patterns vector into pattern nodes
{
QString s = m_downloadDir;
if (s.isEmpty()) {
- s = QString::fromStdString(flightgear::defaultDownloadDir());
+ s = QString::fromStdString(flightgear::defaultDownloadDir().utf8Str());
s.append(tr(" (default)"));
m_ui->clearDownloadDir->setEnabled(false);
} else {
// append the TerraSync path
QString downloadDir = settings.value("download-dir").toString();
if (downloadDir.isEmpty()) {
- downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
+ downloadDir = QString::fromStdString(flightgear::defaultDownloadDir().utf8Str());
}
SGPath terraSyncDir(downloadDir.toStdString());
QSettings settings;
QString downloadDir = settings.value("download-dir").toString();
if (downloadDir.isEmpty()) {
- downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
+ downloadDir = QString::fromStdString(flightgear::defaultDownloadDir().utf8Str());
}
QFileInfo info(downloadDir);
SGPath path(address);
path = globals->resolve_maybe_aircraft_path(address);
if (!path.isNull())
- address = path.str();
+ address = path.local8BitStr();
else
{
mkDialog ("Sorry, file not found!");
// to be executed in graphics context (maybe separate thread)
void run(osg::GraphicsContext* gc)
{
- _result = sg_glDumpWindow(_path.c_str(),
+ std::string ps = _path.local8BitStr();
+ _result = sg_glDumpWindow(ps.c_str(),
_xsize,
_ysize);
}
{
globals->get_event_mgr()->removeTask("SnapShotTimer");
- fgSetString("/sim/paths/screenshot-last", _path.c_str());
+ fgSetString("/sim/paths/screenshot-last", _path.utf8Str());
fgSetBool("/sim/signals/screenshot", _result);
fgSetMouseCursor(_mouse);
SGPath path = _dialog_names[name];
SGPropertyNode_ptr props = new SGPropertyNode;
try {
- readProperties(path.str(), props);
+ readProperties(path, props);
} catch (const sg_exception &) {
SG_LOG(SG_INPUT, SG_ALERT, "Error parsing dialog " << path);
return NULL;
simgear::Dir dir(path);
if( !dir.exists() )
{
- SG_LOG(SG_INPUT, SG_INFO, "directory does not exist: " << path.str());
+ SG_LOG(SG_INPUT, SG_INFO, "directory does not exist: " << path);
return;
}
BOOST_FOREACH(SGPath xmlPath, xmls) {
if (!cache->isCachedFileModified(xmlPath)) {
// cached, easy
- string name = cache->readStringProperty(xmlPath.str());
+ string name = cache->readStringProperty(xmlPath.utf8Str());
_dialog_names[name] = xmlPath;
continue;
}
// we need to parse the actual XML
SGPropertyNode_ptr props = new SGPropertyNode;
try {
- readProperties(xmlPath.str(), props);
+ readProperties(xmlPath, props);
} catch (const sg_exception &) {
SG_LOG(SG_INPUT, SG_ALERT, "Error parsing dialog " << xmlPath);
continue;
// update cached values
if (!cache->isReadOnly()) {
cache->stampCacheFile(xmlPath);
- cache->writeStringProperty(xmlPath.str(), name);
+ cache->writeStringProperty(xmlPath.utf8Str(), name);
}
} // of directory children iteration
SGPropertyNode_ptr result(new SGPropertyNode);
try {
- readProperties(it->second.str(), result);
- result->setStringValue("source", it->second.c_str());
+ readProperties(it->second, result);
+ result->setStringValue("source", it->second.utf8Str());
} catch (sg_exception&) {
SG_LOG(SG_INPUT, SG_WARN, "parse failure reading:" << it->second);
return NULL;
{
flightgear::NavDataCache* cache = flightgear::NavDataCache::instance();
NamePathMap::iterator it;
- BOOST_FOREACH(string s, cache->readStringListProperty(path.str())) {
+ BOOST_FOREACH(string s, cache->readStringListProperty(path.utf8Str())) {
// important - only insert if not already present. This ensures
// user configs can override those in the base package, since they are
// searched first.
void FGDeviceConfigurationMap::refreshCacheForFile(const SGPath& path)
{
- SG_LOG(SG_INPUT, SG_DEBUG, "Reading device file " << path.str());
+ SG_LOG(SG_INPUT, SG_DEBUG, "Reading device file " << path);
SGPropertyNode_ptr n(new SGPropertyNode);
try {
- readProperties(path.str(), n);
+ readProperties(path, n);
} catch (sg_exception&) {
SG_LOG(SG_INPUT, SG_ALERT, "parse failure reading:" << path);
return;
flightgear::NavDataCache* cache = flightgear::NavDataCache::instance();
cache->stampCacheFile(path);
- cache->writeStringListProperty(path.str(), names);
+ cache->writeStringListProperty(path.utf8Str(), names);
}
// Scan the user config files for the specified option and return
// the value.
-static string fgScanForOption( const string& option, const string& path ) {
+static string fgScanForOption( const string& option, const SGPath& path ) {
sg_gzifstream in( path );
if ( !in.is_open() ) {
return "";
if ( homedir != NULL ) {
SGPath config( homedir );
config.append( ".fgfsrc" );
- arg = fgScanForOption( option, config.str() );
+ arg = fgScanForOption( option, config );
}
}
#include <simgear/constants.h>
#include <simgear/misc/sg_path.hxx>
+#include <simgear/misc/sgstream.hxx>
#include <simgear/props/props_io.hxx>
#include <osg/GLU>
_font_renderer->setPointSize(_font_size);
_text_list.setFont(_font_renderer);
_loaded = false;
-
+
currentColorChanged();
_currentPath->fireValueChanged();
}
end = _ladders.end();
for (it = _ladders.begin(); it != end; ++it)
delete *it;
-
+
_items.clear();
_ladders.clear();
-
+
delete _clip_box;
_clip_box = NULL;
-
+
_loaded = false;
}
}
int ret = 0;
- ifstream input(path.c_str());
+ sg_ifstream input(path);
if (!input.good()) {
- SG_LOG(SG_INPUT, SG_ALERT, "HUD: Cannot read configuration from '" << path.c_str() << "'");
+ SG_LOG(SG_INPUT, SG_ALERT, "HUD: Cannot read configuration from '" << path << "'");
return 0x4;
}
if (_listener_active)
return;
_listener_active = true;
-
+
bool loadNow = false;
_visible = _visibility->getBoolValue();
if (_visible && !_loaded) {
loadNow = true;
}
-
+
if (!strcmp(node->getName(), "current-path") && _visible) {
loadNow = true;
}
-
+
if (loadNow) {
int pathIndex = _currentPath->getIntValue();
SGPropertyNode* pathNode = fgGetNode("/sim/hud/path", pathIndex);
path = pathNode->getStringValue();
SG_LOG(SG_INSTR, SG_INFO, "will load Hud from " << path);
}
-
+
_loaded = true;
load(path.c_str());
}
-
+
if (!strcmp(node->getName(), "current-color")) {
currentColorChanged();
}
-
+
_scr_width = _scr_widthN->getIntValue();
_scr_height = _scr_heightN->getIntValue();
-
+
_3Denabled = _3DenabledN->getBoolValue();
_transparent = _transparency->getBoolValue();
_antialiased = _antialiasing->getBoolValue();
if (index < 0) {
index = 0;
}
-
+
n = n->getChild("color", index, false);
if (!n) {
return;
}
-
+
if (n->hasValue("red"))
_red->setFloatValue(n->getFloatValue("red", 1.0));
if (n->hasValue("green"))
#include <simgear/sg_inlines.h>
#include <simgear/misc/sg_path.hxx>
+#include <simgear/misc/sgstream.hxx>
#include <simgear/timing/sg_time.hxx>
#include <simgear/magvar/magvar.hxx>
#include <simgear/structure/exception.hxx>
case FGPositioned::SEAPORT:
case FGPositioned::HELIPORT:
return GPS_WP_APT;
-
+
case FGPositioned::VOR:
return GPS_WP_VOR;
-
+
case FGPositioned::NDB:
return GPS_WP_NDB;
-
+
case FGPositioned::WAYPOINT:
return GPS_WP_USR;
-
+
case FGPositioned::FIX:
return GPS_WP_INT;
-
+
default:
return GPS_WP_USR;
}
if (!aPos) {
return NULL; // happens if find returns no match
}
-
- return new GPSWaypoint(aPos->ident(),
+
+ return new GPSWaypoint(aPos->ident(),
aPos->latitude() * SG_DEGREES_TO_RADIANS,
aPos->longitude() * SG_DEGREES_TO_RADIANS,
GPSWpTypeFromFGPosType(aPos->type())
_grnd_speed_node = fgGetNode("/instrumentation/gps/indicated-ground-speed-kt", true);
_true_track_node = fgGetNode("/instrumentation/gps/indicated-track-true-deg", true);
_mag_track_node = fgGetNode("/instrumentation/gps/indicated-track-magnetic-deg", true);
-
+
// Use FG's position values at construction in case FG's gps has not run first update yet.
_lon = fgGetDouble("/position/longitude-deg") * SG_DEGREES_TO_RADIANS;
_lat = fgGetDouble("/position/latitude-deg") * SG_DEGREES_TO_RADIANS;
_groundSpeed_kts = 0.0;
_track = 0.0;
_magTrackDeg = 0.0;
-
+
// Sensible defaults. These can be overriden by derived classes if desired.
_cdiScales.clear();
_cdiScales.push_back(5.0);
_sourceCdiScaleIndex = 0;
_cdiScaleTransition = false;
_currentCdiScale = 5.0;
-
+
_cleanUpPage = -1;
-
+
_activeWaypoint.id.clear();
_dist2Act = 0.0;
_crosstrackDist = 0.0;
_powerOnTime.set_min(0);
_powerOnTimerSet = false;
_alarmSet = false;
-
+
// Configuration Initialisation
// Should this be in kln89.cxx ?
_turnAnticipationEnabled = false;
-
+
_messageStack.clear();
-
+
_dto = false;
-
+
_approachLoaded = false;
_approachArm = false;
_approachReallyArmed = false;
}
void DCLGPS::init() {
-
+
// Not sure if this should be here, but OK for now.
CreateDefaultFlightPlans();
void DCLGPS::update(double dt) {
//cout << "update called!\n";
-
+
_lon = _lon_node->getDoubleValue() * SG_DEGREES_TO_RADIANS;
_lat = _lat_node->getDoubleValue() * SG_DEGREES_TO_RADIANS;
_alt = _alt_node->getDoubleValue();
}
_checkLon = _gpsLon;
_checkLat = _gpsLat;
-
+
// TODO - check for unit power before running this.
if(!_powerOnTimerSet) {
SetPowerOnTimer();
- }
-
+ }
+
// Check if an alarm timer has expired
if(_alarmSet) {
if(_alarmTime.hr() == atoi(fgGetString("/instrumentation/clock/indicated-hour"))
_alarmSet = false;
}
}
-
+
if(!_departed) {
if(_groundSpeed_kts > 30.0) {
_departed = true;
//cout << "Error, in leg mode with flightplan of 2 or more waypoints, but either active or from wp is NULL!\n";
OrientateToActiveFlightPlan();
}
-
+
// Approach stuff
if(_approachLoaded) {
if(!_approachReallyArmed && !_approachActive) {
}
}
}
-
+
// CDI scale transition stuff
if(_cdiScaleTransition) {
if(fabs(_currentCdiScale - _cdiScales[_targetCdiScaleIndex]) < 0.001) {
_currentCdiScaleIndex = _targetCdiScaleIndex;
_cdiScaleTransition = false;
} else {
- double scaleDiff = (_targetCdiScaleIndex > _sourceCdiScaleIndex
+ double scaleDiff = (_targetCdiScaleIndex > _sourceCdiScaleIndex
? _cdiScales[_sourceCdiScaleIndex] - _cdiScales[_targetCdiScaleIndex]
: _cdiScales[_targetCdiScaleIndex] - _cdiScales[_sourceCdiScaleIndex]);
//cout << "ScaleDiff = " << scaleDiff << '\n';
} else {
_currentCdiScale = _cdiScales[_currentCdiScaleIndex];
}
-
-
+
+
// Urgh - I've been setting the heading bug based on DTK,
// bug I think it should be based on heading re. active waypoint
// based on what the sim does after the final waypoint is passed.
_dtkMag = GetMagHeadingFromTo(_fromWaypoint->lat, _fromWaypoint->lon, _activeWaypoint->lat, _activeWaypoint->lon);
// Don't change the heading bug if speed is too low otherwise it flickers to/from at rest
if(_groundSpeed_ms > 5) {
- //cout << "track = " << _track << ", dtk = " << _dtkTrue << '\n';
+ //cout << "track = " << _track << ", dtk = " << _dtkTrue << '\n';
double courseDev = _track - _dtkTrue;
//cout << "courseDev = " << courseDev << ", normalized = ";
SG_NORMALIZE_RANGE(courseDev, -180.0, 180.0);
if(!_activeWaypoint.id.empty()) {
double hdgTrue = GetGreatCircleCourse(_gpsLat, _gpsLon, _activeWaypoint.lat, _activeWaypoint.lon) * SG_RADIANS_TO_DEGREES;
if(_groundSpeed_ms > 5) {
- //cout << "track = " << _track << ", hdgTrue = " << hdgTrue << '\n';
+ //cout << "track = " << _track << ", hdgTrue = " << hdgTrue << '\n';
double courseDev = _track - hdgTrue;
//cout << "courseDev = " << courseDev << ", normalized = ";
SG_NORMALIZE_RANGE(courseDev, -180.0, 180.0);
_dtkMag = 0.0;
}
}
-
+
_dist2Act = GetGreatCircleDistance(_gpsLat, _gpsLon, _activeWaypoint.lat, _activeWaypoint.lon) * SG_NM_TO_METER;
if(_groundSpeed_ms > 10.0) {
_eta = _dist2Act / _groundSpeed_ms;
} else {
_eta = 0.0;
}
-
+
/*
// First attempt at a sensible cross-track correction calculation
// Uh? - I think this is implemented further down the file!
if(_fromWaypoint != NULL) {
-
+
} else {
_crosstrackDist = 0.0;
}
}
}
-/*
+/*
Expand a SIAP ident to the full procedure name (as shown on the approach chart).
NOTE: Some of this is inferred from data, some is from documentation.
-
+
Example expansions from ARINC 424-18 [and the airport they're taken from]:
"R10LY" <--> "RNAV (GPS) Y RWY 10 L" [KBOI]
"R10-Z" <--> "RNAV (GPS) Z RWY 10" [KHTO]
"VDM-A" <--> "VOR/DME or GPS-A" [KEAG]
"VDMB" <--> "VOR/DME or GPS-B" [KDKX]
"VORA" <--> "VOR or GPS-A" [KEMT]
-
+
It seems that there are 2 basic types of expansions; those that include
the runway and those that don't. Of those that don't, it seems that 2
different positions within the string to encode the identifying letter
string DCLGPS::ExpandSIAPIdent(const string& ident) {
string name;
bool has_rwy = false;
-
+
switch(ident[0]) {
case 'N': name = "NDB or GPS"; has_rwy = false; break;
case 'P': name = "GPS"; has_rwy = true; break;
default: // TODO output a log message
break;
}
-
+
if(has_rwy) {
// Add the identifying letter if present
if(ident.size() == 5) {
name += ' ';
name += ident[4];
}
-
+
// Add the runway
name += " RWY ";
name += ident.substr(1, 2);
-
+
// Add a left/right/centre indication if present.
if(ident.size() > 3) {
if((ident[3] != '-') && (ident[3] != ' ')) { // Early versions of the spec allowed a blank instead of a dash so check for both
// No suffix letter
}
}
-
+
return(name);
}
"PG" => Runway record.
"PP" => Path point record. ???
"PS" => MSA record (minimum safe altitude).
-
+
------ The following is for "PF", approach segment -------
-
+
Col 14-19: SIAP ident for this approach (left justified). This is a standardised abbreviated approach name.
e.g. "R10LZ" expands to "RNAV (GPS) Z RWY 10 L". See the comment block for ExpandSIAPIdent for full details.
Col 20: Route type. This is tricky - I don't have full documentation and am having to guess a bit.
'A' => Arrival route? This seems to be used to encode arrival routes from the IAF to the approach proper.
Note that the final fix of the arrival route is duplicated in the approach proper.
- 'D' => VOR/DME or GPS
+ 'D' => VOR/DME or GPS
'N' => NDB or GPS
'P' => GPS (ARINC 424-18), GPS and RNAV (GPS) (ARINC 424-15 and before).
'R' => RNAV (GPS) (ARINC 424-18).
GPSWaypoint* wp;
GPSFlightPlan* fp;
const GPSWaypoint* cwp;
-
- std::ifstream fin;
+
+ sg_ifstream fin;
SGPath path = globals->get_fg_root();
path.append("Navaids/rnav.dat");
- fin.open(path.c_str(), ios::in);
+ fin.open(path, ios::in);
if(!fin) {
//cout << "Unable to open input file " << path.c_str() << '\n';
return;
}
char tmp[256];
string s;
-
+
string apt_ident; // This gets set to the ICAO code of the current airport being processed.
string iap_ident; // The abbreviated name of the current approach being processed.
string wp_ident; // The ident of the waypoint of the current line
char last_route_type = 0;
char route_type;
char waypoint_fix_type; // This is the waypoint type from col 43, i.e. the type of fix. May be blank.
-
+
int j;
-
+
// Debugging info
unsigned int nLoaded = 0;
unsigned int nErrors = 0;
-
+
//for(i=0; i<64; ++i) {
while(!fin.eof()) {
fin.getline(tmp, 256);
iap_in_progress = true;
iap_error = false;
}
-
+
// Route type
route_type = s[19];
sequence_number = atoi(s.substr(26,3).c_str());
break;
}
}
-
+
// Ignore lines with no waypoint ID for now - these are normally part of the
// missed approach procedure, and we don't use them in the KLN89.
if(!wp_ident.empty()) {
case ' ': w.appType = GPS_APP_NONE; break;
//default: cout << "Unknown waypoint_fix_type: \'" << waypoint_fix_type << "\' [" << apt_ident << ", " << iap_ident << "]\n";
}
-
+
if(wp_error) {
//cout << "Unable to find waypoint " << w.id << " [" << apt_ident << ", " << iap_ident << "]\n";
iap_error = true;
}
-
+
if(!wp_error) {
if(route_in_progress) {
if(sequence_number > last_sequence_number) {
}
}
}
-
+
// If we get to the end of the file, load any approach that is still in progress
// TODO - sanity check that the approach has all the required elements
if(iap_in_progress) {
nLoaded++;
}
}
-
+
//cout << "Done loading approach database\n";
//cout << "Loaded: " << nLoaded << '\n';
//cout << "Failed: " << nErrors << '\n';
-
+
fin.close();
}
-GPSWaypoint* DCLGPS::GetActiveWaypoint() {
- return &_activeWaypoint;
+GPSWaypoint* DCLGPS::GetActiveWaypoint() {
+ return &_activeWaypoint;
}
-
+
// Returns meters
-float DCLGPS::GetDistToActiveWaypoint() {
+float DCLGPS::GetDistToActiveWaypoint() {
return _dist2Act;
}
//
// If the KLN89 is not connected to an external indicator, then:
// If there is an active waypoint, the OBS heading is set such that the
- // deviation indicator remains at the same deviation (i.e. set to DTK,
+ // deviation indicator remains at the same deviation (i.e. set to DTK,
// although there may be some small difference).
//
// If there is not an active waypoint, I am not sure what value should be
// TODO - what should we really do here?
_obsHeading = 0;
}
-
+
// Valid OBS heading values are 0 -> 359 degrees inclusive (from kln89 simulator).
if(_obsHeading > 359) _obsHeading -= 360;
if(_obsHeading < 0) _obsHeading += 360;
-
+
// TODO - the _fromWaypoint location will change as the OBS heading changes.
// Might need to store the OBS initiation position somewhere in case it is needed again.
SetOBSFromWaypoint();
void DCLGPS::SetOBSFromWaypoint() {
if(!_obsMode) return;
if(_activeWaypoint.id.empty()) return;
-
+
// TODO - base the 180 deg correction on the to/from flag.
_fromWaypoint = GetPositionOnMagRadial(_activeWaypoint, 10, _obsHeading + 180.0);
_fromWaypoint.type = GPS_WP_VIRT;
if(_groundSpeed_kts < 30.0) {
return(-1.0);
}
-
+
double eta = 0.0;
int n1 = GetActiveWaypointIndex();
int n2 = GetWaypointIndex(id);
void DCLGPS::OrientateToFlightPlan(GPSFlightPlan* fp) {
//cout << "Orientating...\n";
- //cout << "_lat = " << _lat << ", _lon = " << _lon << ", _gpsLat = " << _gpsLat << ", gpsLon = " << _gpsLon << '\n';
+ //cout << "_lat = " << _lat << ", _lon = " << _lon << ", _gpsLat = " << _gpsLat << ", gpsLon = " << _gpsLon << '\n';
if(fp->IsEmpty()) {
_activeWaypoint.id.clear();
_navFlagged = true;
double d0 = fabs(CalcCrossTrackDeviation(*fp->waypoints[i-1], *fp->waypoints[i]));
// That is the shortest distance away we could be though - check for
// longer distances if we are 'off the end' of the leg.
- double ht1 = GetGreatCircleCourse(fp->waypoints[i-1]->lat, fp->waypoints[i-1]->lon,
- fp->waypoints[i]->lat, fp->waypoints[i]->lon)
+ double ht1 = GetGreatCircleCourse(fp->waypoints[i-1]->lat, fp->waypoints[i-1]->lon,
+ fp->waypoints[i]->lat, fp->waypoints[i]->lon)
* SG_RADIANS_TO_DEGREES;
// not simply the reverse of the above due to great circle navigation.
- double ht2 = GetGreatCircleCourse(fp->waypoints[i]->lat, fp->waypoints[i]->lon,
- fp->waypoints[i-1]->lat, fp->waypoints[i-1]->lon)
+ double ht2 = GetGreatCircleCourse(fp->waypoints[i]->lat, fp->waypoints[i]->lon,
+ fp->waypoints[i-1]->lat, fp->waypoints[i-1]->lon)
* SG_RADIANS_TO_DEGREES;
double hw1 = GetGreatCircleCourse(_gpsLat, _gpsLon,
- fp->waypoints[i]->lat, fp->waypoints[i]->lon)
+ fp->waypoints[i]->lat, fp->waypoints[i]->lon)
* SG_RADIANS_TO_DEGREES;
- double hw2 = GetGreatCircleCourse(_gpsLat, _gpsLon,
- fp->waypoints[i-1]->lat, fp->waypoints[i-1]->lon)
+ double hw2 = GetGreatCircleCourse(_gpsLat, _gpsLon,
+ fp->waypoints[i-1]->lat, fp->waypoints[i-1]->lon)
* SG_RADIANS_TO_DEGREES;
double h1 = ht1 - hw1;
double h2 = ht2 - hw2;
void DCLGPS::OrientateToActiveFlightPlan() {
OrientateToFlightPlan(_activeFP);
-}
+}
/***************************************/
GPSWaypoint* DCLGPS::FindFirstById(const string& id) const
{
- DCLGPSFilter filter;
+ DCLGPSFilter filter;
FGPositionedList matches = FGPositioned::findAllWithIdent(id, &filter, false);
if (matches.empty()) {
return NULL;
}
-
+
FGPositioned::sortByRange(matches, SGGeod::fromRad(_lon, _lat));
return GPSWaypoint::createFromPositioned(matches.front());
}
{
multi = false;
FGPositioned::TypeFilter filter(ty);
-
+
FGPositionedList matches =
FGPositioned::findAllWithIdent(id, &filter, exact);
if (matches.empty()) {
return NULL;
}
-
+
FGPositioned::sortByRange(matches, SGGeod::fromRad(_lon, _lat));
return matches.front();
}
return dynamic_cast<FGAirport*>(FindTypedFirstById(id, FGPositioned::AIRPORT, multi, exact));
}
-FGNavRecord* DCLGPS::FindClosestVor(double lat_rad, double lon_rad) {
+FGNavRecord* DCLGPS::FindClosestVor(double lat_rad, double lon_rad) {
FGPositioned::TypeFilter filter(FGPositioned::VOR);
double cutoff = 1000; // nautical miles
FGPositionedRef v = FGPositioned::findClosest(SGGeod::fromRad(lon_rad, lat_rad), cutoff, &filter);
if (!v) {
return NULL;
}
-
+
return dynamic_cast<FGNavRecord*>(v.ptr());
}
A mathematically equivalent formula, which is less subject to rounding error for short distances is:
-d=2*asin(sqrt((sin((lat1-lat2)/2))^2 +
+d=2*asin(sqrt((sin((lat1-lat2)/2))^2 +
cos(lat1)*cos(lat2)*(sin((lon1-lon2)/2))^2))
-
+
*/
// Returns distance in nm, takes lat & lon in RADIANS
return(Rad2Nm(d));
}
-// fmod dosen't do what we want :-(
+// fmod dosen't do what we want :-(
static double mod(double d1, double d2) {
return(d1 - d2*floor(d1/d2));
}
}
cout << h * SG_RADIANS_TO_DEGREES << '\n';
*/
-
+
return( mod(atan2(sin(lon2-lon1)*cos(lat2),
cos(lat1)*sin(lat2)-sin(lat1)*cos(lat2)*cos(lon2-lon1)),
2.0*SG_PI) );
GPSWaypoint DCLGPS::GetPositionOnRadial(const GPSWaypoint& wp1, double d, double h) {
while(h < 0.0) h += 360.0;
while(h > 360.0) h -= 360.0;
-
+
h *= SG_DEGREES_TO_RADIANS;
d *= (SG_PI / (180.0 * 60.0));
-
+
double lat=asin(sin(wp1.lat)*cos(d)+cos(wp1.lat)*sin(d)*cos(h));
double lon;
if(cos(lat)==0) {
} else {
lon=mod(wp1.lon+asin(sin(h)*sin(d)/cos(lat))+SG_PI,2*SG_PI)-SG_PI;
}
-
+
GPSWaypoint wp;
wp.lat = lat;
wp.lon = lon;
double DCLGPS::CalcCrossTrackDeviation(const GPSWaypoint& wp1, const GPSWaypoint& wp2) const {
//if(wp1 == NULL || wp2 == NULL) return(0.0);
if(wp1.id.empty() || wp2.id.empty()) return(0.0);
- double xtd = asin(sin(Nm2Rad(GetGreatCircleDistance(wp1.lat, wp1.lon, _gpsLat, _gpsLon)))
+ double xtd = asin(sin(Nm2Rad(GetGreatCircleDistance(wp1.lat, wp1.lon, _gpsLat, _gpsLon)))
* sin(GetGreatCircleCourse(wp1.lat, wp1.lon, _gpsLat, _gpsLon) - GetGreatCircleCourse(wp1.lat, wp1.lon, wp2.lat, wp2.lon)));
return(Rad2Nm(xtd));
}
-AlignedProjection::AlignedProjection()
+AlignedProjection::AlignedProjection()
{
SGGeod g; // ctor initializes to zero
Init( g, 0.0 );
}
-AlignedProjection::AlignedProjection(const SGGeod& centre, double heading)
+AlignedProjection::AlignedProjection(const SGGeod& centre, double heading)
{
Init( centre, heading );
}
return SGGeod::fromRadM(_origin.getLongitudeRad()+delta_lon, _origin.getLatitudeRad()+delta_lat, pt.z());
}
-
}
SGPath config = globals->resolve_aircraft_path(path_n->getStringValue());
- SG_LOG( SG_COCKPIT, SG_INFO, "Reading instruments from " << config.str() );
+ SG_LOG( SG_COCKPIT, SG_INFO, "Reading instruments from " << config );
try {
- readProperties( config.str(), config_props );
+ readProperties( config, config_props );
if (!build(config_props)) {
throw sg_exception(
"Detected an internal inconsistency in the instrumentation\n"
}
} catch (const sg_exception& e) {
SG_LOG(SG_COCKPIT, SG_ALERT, "Failed to load instrumentation system model: "
- << config.str() << ":" << e.getFormattedMessage() );
+ << config << ":" << e.getFormattedMessage() );
}
SGPath high = path;
high.append( "Navaids/range.high" );
- static_terminalRangeInterp.reset(new SGInterpTable(term.str()));
- static_lowRangeInterp.reset(new SGInterpTable(low.str()));
- static_highRangeInterp.reset(new SGInterpTable(high.str()));
+ static_terminalRangeInterp.reset(new SGInterpTable(term));
+ static_lowRangeInterp.reset(new SGInterpTable(low));
+ static_highRangeInterp.reset(new SGInterpTable(high));
}
string branch("/instrumentation/" + _name);
/* ---------------------------------------------------------------- */
-static std::string VORTablePath( const char * name )
+static SGPath VORTablePath( const char * name )
{
SGPath path( globals->get_fg_root() );
path.append( "Navaids" );
path.append(name);
- return path.str();
+ return path;
}
class VOR : public NavRadioComponentWithIdent {
SGPath mpath( globals->get_fg_root() );
mpath.append( fgGetString("/sim/rendering/materials-file") );
bool loaded = new_matlib->load(globals->get_fg_root().local8BitStr(),
- mpath.str(),
+ mpath.local8BitStr(),
globals->get_props());
if ( ! loaded ) {
SG_LOG( SG_GENERAL, SG_ALERT,
- "Error loading materials file " << mpath.str() );
+ "Error loading materials file " << mpath );
return false;
}
do_load_xml_to_proptree(const SGPropertyNode * arg)
{
SGPath file(arg->getStringValue("filename"));
- if (file.str().empty())
+ if (file.isNull())
return false;
if (file.extension() != "xml")
std::string icao = arg->getStringValue("icao");
if (icao.empty()) {
if (file.isRelative()) {
- SGPath absPath = globals->resolve_maybe_aircraft_path(file.str());
+ SGPath absPath = globals->resolve_maybe_aircraft_path(file.utf8Str());
if (!absPath.isNull())
file = absPath;
else
{
SG_LOG(SG_IO, SG_ALERT, "loadxml: Cannot find XML property file '"
- << file.str() << "'.");
+ << file << "'.");
return false;
}
}
} else {
- if (!XMLLoader::findAirportData(icao, file.str(), file)) {
+ if (!XMLLoader::findAirportData(icao, file.utf8Str(), file)) {
SG_LOG(SG_IO, SG_INFO, "loadxml: failed to find airport data for "
- << file.str() << " at ICAO:" << icao);
+ << file << " at ICAO:" << icao);
return false;
}
}
std::string validated_path = fgValidatePath(file, false);
if (validated_path.empty()) {
- SG_LOG(SG_IO, SG_ALERT, "loadxml: reading '" << file.str() << "' denied "
+ SG_LOG(SG_IO, SG_ALERT, "loadxml: reading '" << file << "' denied "
"(unauthorized directory - authorization no longer follows symlinks; to authorize reading additional directories, add them to --fg-aircraft)");
return false;
}
do_save_xml_from_proptree(const SGPropertyNode * arg)
{
SGPath file(arg->getStringValue("filename"));
- if (file.str().empty())
+ if (file.isNull())
return false;
if (file.extension() != "xml")
std::string validated_path = fgValidatePath(file, true);
if (validated_path.empty()) {
- SG_LOG(SG_IO, SG_ALERT, "savexml: writing to '" << file.str() << "' denied "
+ SG_LOG(SG_IO, SG_ALERT, "savexml: writing to '" << file << "' denied "
"(unauthorized directory - authorization no longer follows symlinks)");
return false;
}
// no scenery paths set *at all*, use the data in FG_ROOT
SGPath root(globals->get_fg_root());
root.append("Scenery");
- globals->append_fg_scenery(root.str());
+ globals->append_fg_scenery(root);
}
return true;
SG_LOG(SG_GENERAL, SG_INFO, "found aircraft in dir: " << aircraftDir );
try {
- readProperties(setFile.str(), globals->get_props());
+ readProperties(setFile, globals->get_props());
} catch ( const sg_exception &e ) {
SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
flightgear::fatalMessageBox("Error reading aircraft",
if (!checkCache()) {
// prepare cache for re-scan
SGPropertyNode *n = _cache->getNode("fg-root", true);
- n->setStringValue(globals->get_fg_root().c_str());
+ n->setStringValue(globals->get_fg_root().utf8Str());
n->setAttribute(SGPropertyNode::USERARCHIVE, true);
n = _cache->getNode("fg-aircraft", true);
n->setStringValue(getAircraftPaths().c_str());
visitAircraftPaths();
}
- if (_foundPath.str().empty()) {
+ if (_foundPath.isNull()) {
SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
flightgear::fatalMessageBox("Aircraft not found",
"The requested aircraft '" + aircraft + "' could not be found in any of the search paths");
return false;
}
- SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
+ SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath);
fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
if (!_foundPath.exists()) {
- SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
+ SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath);
return false;
}
try {
- readProperties(_foundPath.str(), globals->get_props());
+ readProperties(_foundPath, globals->get_props());
} catch ( const sg_exception &e ) {
SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
flightgear::fatalMessageBox("Error reading aircraft",
char buf[16];
bool result = false;
+ std::string ps = pidPath.local8BitStr();
#if defined(SG_WINDOWS)
size_t len = snprintf(buf, 16, "%d", _getpid());
- HANDLE f = CreateFileA(pidPath.c_str(), GENERIC_READ | GENERIC_WRITE,
+ HANDLE f = CreateFileA(ps.c_str(), GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ, /* sharing */
NULL, /* security attributes */
CREATE_NEW, /* error if already exists */
// POSIX, do open+unlink trick to the file is deleted on exit, even if we
// crash or exit(-1)
ssize_t len = snprintf(buf, 16, "%d", getpid());
- int fd = ::open(pidPath.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0644);
+ int fd = ::open(ps.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0644);
if (fd >= 0) {
result = ::write(fd, buf, len) == len;
- if( ::unlink(pidPath.c_str()) != 0 ) // delete file when app quits
+ if( ::unlink(ps.c_str()) != 0 ) // delete file when app quits
result = false;
}
#endif
if (!result) {
flightgear::fatalMessageBox("File permissions problem",
"Can't write to user-data storage folder, check file permissions and FG_HOME.",
- "User-data at:" + dataPath.str());
+ "User-data at:" + dataPath.utf8Str());
}
return result;
}
SGPropertyNode *home = fgGetNode("/sim", true);
home->removeChild("fg-home", 0);
home = home->getChild("fg-home", 0, true);
- home->setStringValue(dataPath.c_str());
+ home->setStringValue(dataPath.utf8Str());
home->setAttribute(SGPropertyNode::WRITE, false);
fgSetDefaults();
// set aircraft-dir to short circuit the search process
InstallRef acftInstall = acftPackage->install();
- fgSetString("/sim/aircraft-dir", acftInstall->path().c_str());
+ fgSetString("/sim/aircraft-dir", acftInstall->path().utf8Str());
// overwrite the fully qualified ID with the aircraft one, so the
// code in FindAndCacheAircraft works as normal
SGPropertyNode *curr = fgGetNode("/sim", true);
curr->removeChild("fg-current", 0);
curr = curr->getChild("fg-current", 0, true);
- curr->setStringValue(cwd.path().str());
+ curr->setStringValue(cwd.path().utf8Str());
curr->setAttribute(SGPropertyNode::WRITE, false);
fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
SGPath mpath( globals->get_fg_root() );
mpath.append( fgGetString("/sim/rendering/materials-file") );
- if ( ! globals->get_matlib()->load(globals->get_fg_root().local8BitStr(), mpath.str(),
+ if ( ! globals->get_matlib()->load(globals->get_fg_root().local8BitStr(), mpath.local8BitStr(),
globals->get_props()) ) {
throw sg_io_exception("Error loading materials file", mpath);
}
packageAircraftDir.append("Aircraft");
- SG_LOG(SG_GENERAL, SG_INFO, "init package root at:" << packageAircraftDir.str());
+ SG_LOG(SG_GENERAL, SG_INFO, "init package root at:" << packageAircraftDir);
SGSharedPtr<Root> pkgRoot(new Root(packageAircraftDir, FLIGHTGEAR_VERSION));
bool
-fgLoadProps (const char * path, SGPropertyNode * props, bool in_fg_root, int default_mode)
+fgLoadProps (const std::string& path, SGPropertyNode * props, bool in_fg_root, int default_mode)
{
- string fullpath;
+ SGPath fullpath;
if (in_fg_root) {
SGPath loadpath(globals->get_fg_root());
loadpath.append(path);
- fullpath = loadpath.str();
+ fullpath = loadpath;
} else {
- fullpath = path;
+ fullpath = SGPath::fromUtf8(path);
}
try {
* @return true if the properties loaded successfully, false
* otherwise.
*/
-extern bool fgLoadProps (const char * path, SGPropertyNode * props,
+extern bool fgLoadProps (const std::string& path, SGPropertyNode * props,
bool in_fg_root = true, int default_mode = 0);
void setLoggingClasses (const char * c);
// tell the ResouceManager about the scenery path
// needed to load Models from this scenery path
- simgear::ResourceManager::instance()->addBasePath(abspath.str(),
+ simgear::ResourceManager::instance()->addBasePath(abspath.local8BitStr(),
simgear::ResourceManager::PRIORITY_DEFAULT);
simgear::Dir dir(abspath);
SGPropertyNode *n = props->getNode("/sim", true);
n->removeChild("fg-root", 0);
n = n->getChild("fg-root", 0, true);
- n->setStringValue(fg_root.c_str());
+ n->setStringValue(fg_root.utf8Str());
n->setAttribute(SGPropertyNode::WRITE, false);
}
SGPath autosaveFile = simgear::Dir(dataPath).file(autosaveName());
SGPropertyNode autosave;
if (autosaveFile.exists()) {
- SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << autosaveFile.str());
+ SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << autosaveFile);
try {
- readProperties(autosaveFile.str(), &autosave, SGPropertyNode::USERARCHIVE);
+ readProperties(autosaveFile, &autosave, SGPropertyNode::USERARCHIVE);
} catch (sg_exception& e) {
SG_LOG(SG_INPUT, SG_WARN, "failed to read user settings:" << e.getMessage()
<< "(from " << e.getOrigin() << ")");
SGPath autosaveFile(globals->get_fg_home());
autosaveFile.append(autosaveName());
autosaveFile.create_dir( 0700 );
- SG_LOG(SG_IO, SG_INFO, "Saving user settings to " << autosaveFile.str());
+ SG_LOG(SG_IO, SG_INFO, "Saving user settings to " << autosaveFile);
try {
- writeProperties(autosaveFile.str(), globals->get_props(), false, SGPropertyNode::USERARCHIVE);
+ writeProperties(autosaveFile, globals->get_props(), false, SGPropertyNode::USERARCHIVE);
} catch (const sg_exception &e) {
guiErrorMessage("Error writing autosave:", e);
}
path.append(path_str);
SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings for '" <<
localeNode->getStringValue("lang", "<none>")
- <<"' from " << path.str());
+ <<"' from " << path);
// load the actual file
try
{
- readProperties(path.str(), stringNode->getNode(resource, 0, true));
+ readProperties(path, stringNode->getNode(resource, 0, true));
} catch (const sg_exception &e)
{
- SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings from " << path.str() <<
+ SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings from " << path <<
". Error: " << e.getFormattedMessage());
return false;
}
}
}
- fgSetString("/sim/terrasync/cache-path", tsyncCache.c_str());
+ fgSetString("/sim/terrasync/cache-path", tsyncCache.utf8Str());
simgear::SGTerraSync* terra_sync = new simgear::SGTerraSync();
terra_sync->setRoot(globals->get_props());
}
path.append(renderer+".xml");
if (path.exists()) {
- SG_LOG(SG_INPUT, SG_INFO, "Reading video settings from " << path.str());
+ SG_LOG(SG_INPUT, SG_INFO, "Reading video settings from " << path);
try {
SGPropertyNode *r_prop = fgGetNode("/sim/rendering");
- readProperties(path.str(), r_prop);
+ readProperties(path, r_prop);
} catch (sg_exception& e) {
SG_LOG(SG_INPUT, SG_WARN, "failed to read video settings:" << e.getMessage()
<< "(from " << e.getOrigin() << ")");
fgSetString("/sim/multiplay/txhost", "");
fgSetInt("/sim/multiplay/rxport", 0);
fgSetInt("/sim/multiplay/txport", 0);
-
+
SGPropertyNode* v = globals->get_props()->getNode("/sim/version", true);
v->setValueReadOnly("flightgear", FLIGHTGEAR_VERSION);
v->setValueReadOnly("simgear", SG_STRINGIZE(SIMGEAR_VERSION));
#else
v->setValueReadOnly("nightly-build", false);
#endif
-
+
char* envp = ::getenv( "http_proxy" );
if( envp != NULL )
fgSetupProxy( envp );
{
_minStatus = getNumMaturity(fgGetString("/sim/aircraft-min-status", "all"));
}
-
-
+
+
void show(const vector<SGPath> & path_list)
{
for (vector<SGPath>::const_iterator p = path_list.begin();
p != path_list.end(); ++p)
visitDir(*p, 0);
-
+
simgear::requestConsole(); // ensure console is shown on Windows
-
+
std::sort(_aircraft.begin(), _aircraft.end(), ciLessLibC());
cout << "Available aircraft:" << endl;
for ( unsigned int i = 0; i < _aircraft.size(); i++ ) {
cout << _aircraft[i] << endl;
}
}
-
+
private:
virtual VisitResult visit(const SGPath& path)
{
SGPropertyNode root;
try {
- readProperties(path.str(), &root);
+ readProperties(path, &root);
} catch (sg_exception& ) {
return VISIT_CONTINUE;
}
-
+
int maturity = 0;
string descStr(" ");
descStr += path.file();
if (nPos == (int)(descStr.size() - 8)) {
descStr.resize(nPos);
}
-
+
SGPropertyNode *node = root.getNode("sim");
if (node) {
SGPropertyNode* desc = node->getNode("description");
if (node->hasValue("status")) {
maturity = getNumMaturity(node->getStringValue("status"));
}
-
+
if (desc) {
if (descStr.size() <= 27+3) {
descStr.append(29+3-descStr.size(), ' ');
descStr += desc->getStringValue();
}
} // of have 'sim' node
-
+
if (maturity >= _minStatus) {
_aircraft.push_back(descStr);
}
-
+
return VISIT_CONTINUE;
}
-
-
+
+
int getNumMaturity(const char * str)
{
// changes should also be reflected in $FG_ROOT/data/options.xml &
// $FG_ROOT/data/Translations/string-default.xml
const char* levels[] = {"alpha","beta","early-production","production"};
-
+
if (!strcmp(str, "all")) {
return 0;
}
-
+
for (size_t i=0; i<(sizeof(levels)/sizeof(levels[0]));i++)
if (strcmp(str,levels[i])==0)
return i;
-
+
return 0;
}
-
+
// recommended in Meyers, Effective STL when internationalization and embedded
// NULLs aren't an issue. Much faster than the STL or Boost lex versions.
struct ciLessLibC : public std::binary_function<string, string, bool>
return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ? 1 : 0;
}
};
-
+
int _minStatus;
string_list _aircraft;
};
{
ShowAircraft s;
s.show(path_list);
-
+
#ifdef _MSC_VER
cout << "Hit a key to continue..." << endl;
std::cin.get();
string::size_type pos = arg.find('=');
if (pos == arg.npos || pos == 0 || pos + 1 == arg.size())
return FG_OPTIONS_ERROR;
-
+
string name = arg.substr(0, pos);
string value = arg.substr(pos + 1);
string type;
pos = name.find(':');
-
+
if (pos != name.npos && pos != 0 && pos + 1 != name.size()) {
type = name.substr(0, pos);
name = name.substr(pos + 1);
}
SGPropertyNode *n = fgGetNode(name.c_str(), true);
-
+
bool writable = n->getAttribute(SGPropertyNode::WRITE);
if (!writable)
n->setAttribute(SGPropertyNode::WRITE, true);
-
+
bool ret = false;
if (type.empty())
ret = n->setUnspecifiedValue(value.c_str());
ret = n->setIntValue(atoi(value.c_str()));
else if (type == "b" || type == "bool")
ret = n->setBoolValue(value == "true" || atoi(value.c_str()) != 0);
-
+
if (!writable)
n->setAttribute(SGPropertyNode::WRITE, false);
return ret ? FG_OPTIONS_OK : FG_OPTIONS_ERROR;
class DelayedTapeLoader : SGPropertyChangeListener {
public:
DelayedTapeLoader( const char * tape ) :
- _tape(tape)
+ _tape(SGPath::fromLocal8Bit(tape))
{
SGPropertyNode_ptr n = fgGetNode("/sim/signals/fdm-initialized", true);
n->addChangeListener( this );
// tell the replay subsystem to load the tape
FGReplay* replay = (FGReplay*) globals->get_subsystem("replay");
SGPropertyNode_ptr arg = new SGPropertyNode();
- arg->setStringValue("tape", _tape );
+ arg->setStringValue("tape", _tape.utf8Str() );
arg->setBoolValue( "same-aircraft", 0 );
replay->loadTape(arg);
delete this; // commence suicide
}
private:
- std::string _tape;
+ SGPath _tape;
};
/**
* internal storage of a value->option binding
*/
-class OptionValue
+class OptionValue
{
public:
OptionValue(OptionDesc* d, const string& v) :
desc(d), value(v)
{;}
-
+
OptionDesc* desc;
string value;
};
typedef std::vector<OptionValue> OptionValueVec;
typedef std::map<string, OptionDesc*> OptionDescDict;
-
+
class Options::OptionsPrivate
{
public:
-
+
OptionValueVec::const_iterator findValue(const string& key) const
{
OptionValueVec::const_iterator it = values.begin();
if (!it->desc) {
continue; // ignore markers
}
-
+
if (it->desc->option == key) {
return it;
}
} // of set values iteration
-
+
return it; // not found
}
return it;
}
} // of set values iteration
-
+
return it; // not found
}
-
+
OptionDesc* findOption(const string& key) const
{
OptionDescDict::const_iterator it = options.find(key);
if (it == options.end()) {
return NULL;
}
-
+
return it->second;
}
-
+
int processOption(OptionDesc* desc, const string& arg_value)
{
if (!desc) {
return FG_OPTIONS_OK; // tolerate marker options
}
-
+
switch ( desc->type & 0xffff ) {
case OPTION_BOOL:
fgSetBool( desc->property, desc->b_param );
return FG_OPTIONS_ERROR;
}
break;
-
+
case OPTION_IGNORE:
break;
}
-
+
return FG_OPTIONS_OK;
}
-
+
/**
* insert a marker value into the values vector. This is necessary
* when processing options, to ensure the correct ordering, where we scan
{
values.push_back(OptionValue(NULL, "-"));
}
-
+
/**
* given a current iterator into the values, find the preceding group marker,
* or return the beginning of the value vector.
return pos; // found a marker, we're done
}
}
-
+
return pos;
}
-
+
bool showHelp,
verbose,
showAircraft,
shouldLoadDefaultConfig;
-
+
OptionDescDict options;
OptionValueVec values;
simgear::PathList propertyFiles;
};
-
+
Options* Options::sharedInstance()
{
if (shared_instance == NULL) {
shared_instance = new Options;
}
-
+
return shared_instance;
}
-
+
Options::Options() :
p(new OptionsPrivate())
{
p->verbose = false;
p->showAircraft = false;
p->shouldLoadDefaultConfig = true;
-
+
// build option map
OptionDesc *desc = &fgOptionArray[ 0 ];
while ( desc->option != 0 ) {
++desc;
}
}
-
+
Options::~Options()
{
}
-
+
void Options::init(int argc, char **argv, const SGPath& appDataPath)
{
// first, process the command line
inOptions = true;
continue;
}
-
+
int result = parseOption(argv[i]);
processArgResult(result);
} else {
// XML properties file
- SGPath f(argv[i]);
+ SGPath f = SGPath::fromLocal8Bit(argv[i]);
if (!f.exists()) {
- SG_LOG(SG_GENERAL, SG_ALERT, "config file not found:" << f.str());
+ SG_LOG(SG_GENERAL, SG_ALERT, "config file not found:" << f);
} else {
p->propertyFiles.push_back(f);
}
}
} // of arguments iteration
p->insertGroupMarker(); // command line is one group
-
+
// establish log-level before anything else - otherwise it is not possible
// to show extra (debug/info/warning) messages for the start-up phase.
fgOptLogLevel(valueForOption("log-level", "alert").c_str());
setupRoot(argc, argv);
return;
}
-
+
// then config files
SGPath config;
- std::string homedir;
- if (getenv("HOME")) {
- homedir = getenv("HOME");
- }
-
- if( !homedir.empty() && !hostname.empty() ) {
+
+
+ if( !hostname.empty() ) {
// Check for ~/.fgfsrc.hostname
- config.set(homedir);
+ config = SGPath::home();
config.append(".fgfsrc");
config.concat( "." );
config.concat( hostname );
readConfig(config);
}
-
+
// Check for ~/.fgfsrc
- if( !homedir.empty() ) {
- config.set(homedir);
+ config = SGPath::home();
config.append(".fgfsrc");
readConfig(config);
- }
-
+
// check for a config file in app data
SGPath appDataConfig(appDataPath);
appDataConfig.append("fgfsrc");
if (appDataConfig.exists()) {
readConfig(appDataConfig);
}
-
+
// setup FG_ROOT
setupRoot(argc, argv);
-
+
// system.fgfsrc is disabled, as we no longer allow anything in fgdata to set
// fg-root/fg-home/fg-aircraft and hence control what files Nasal can access
- std::string name_for_error = homedir.empty() ? appDataConfig.str() : config.str();
+ std::string name_for_error = config.utf8Str();
if( ! hostname.empty() ) {
config = globals->get_fg_root();
config.append( "system.fgfsrc" );
config.concat( hostname );
if (config.exists()) {
flightgear::fatalMessageBox("Unsupported configuration",
- "You have a " + config.str() + " file, which is no longer processed for security reasons",
+ "You have a " + config.utf8Str() + " file, which is no longer processed for security reasons",
"If you created this file intentionally, please move it to " + name_for_error);
}
}
config.append( "system.fgfsrc" );
if (config.exists()) {
flightgear::fatalMessageBox("Unsupported configuration",
- "You have a " + config.str() + " file, which is no longer processed for security reasons",
+ "You have a " + config.utf8Str() + " file, which is no longer processed for security reasons",
"If you created this file intentionally, please move it to " + name_for_error);
}
}
} else if (isOptionSet("vehicle")) {
aircraft = valueForOption("vehicle");
}
-
+
if (!aircraft.empty()) {
SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
fgSetString("/sim/aircraft", aircraft.c_str() );
} else {
SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
}
-
+
if (p->showAircraft) {
PathList path_list;
fgShowAircraft(path_list);
exit(0);
}
-
+
if (isOptionSet("aircraft-dir")) {
SGPath aircraftDirPath(valueForOption("aircraft-dir"));
fgSetString("/sim/aircraft-state", stateName);
}
}
-
+
void Options::processArgResult(int result)
{
if ((result == FG_OPTIONS_HELP) || (result == FG_OPTIONS_ERROR))
p->shouldLoadDefaultConfig = false;
} else if (result == FG_OPTIONS_SHOW_SOUND_DEVICES) {
SGSoundMgr smgr;
-
+
smgr.init();
string vendor = smgr.get_vendor();
string renderer = smgr.get_renderer();
cout << renderer << " provided by " << vendor << endl;
cout << endl << "No. Device" << endl;
-
+
vector <const char*>devices = smgr.get_available_devices();
for (vector <const char*>::size_type i=0; i<devices.size(); i++) {
cout << i << ". \"" << devices[i] << "\"" << endl;
exit(0);
}
}
-
+
void Options::readConfig(const SGPath& path)
{
- sg_gzifstream in( path.str() );
+ sg_gzifstream in( path );
if ( !in.is_open() ) {
return;
}
-
- SG_LOG( SG_GENERAL, SG_INFO, "Processing config file: " << path.str() );
-
+
+ SG_LOG( SG_GENERAL, SG_INFO, "Processing config file: " << path );
+
in >> skipcomment;
while ( ! in.eof() ) {
string line;
getline( in, line, '\n' );
-
+
// catch extraneous (DOS) line ending character
int i;
for (i = line.length(); i > 0; i--)
if (line[i - 1] > 32)
break;
line = line.substr( 0, i );
-
+
if ( parseOption( line ) == FG_OPTIONS_ERROR ) {
- cerr << endl << "Config file parse error: " << path.str() << " '"
+ cerr << endl << "Config file parse error: " << path << " '"
<< line << "'" << endl;
p->showHelp = true;
}
p->insertGroupMarker(); // each config file is a group
}
-
+
int Options::parseOption(const string& s)
{
if ((s == "--help") || (s=="-h")) {
SG_LOG(SG_GENERAL, SG_ALERT, "malformed property option:" << s);
return FG_OPTIONS_ERROR;
}
-
+
p->values.push_back(OptionValue(desc, s.substr(7)));
return FG_OPTIONS_OK;
} else if ( s.find( "--" ) == 0 ) {
key = s.substr( 2, eqPos - 2 );
value = s.substr( eqPos + 1);
}
-
+
return addOption(key, value);
} else {
flightgear::modalMessageBox("Unknown option", "Unknown command-line option: " + s);
return FG_OPTIONS_ERROR;
}
}
-
+
int Options::addOption(const string &key, const string &value)
{
OptionDesc* desc = p->findOption(key);
flightgear::modalMessageBox("Unknown option", "Unknown command-line option: " + key);
return FG_OPTIONS_ERROR;
}
-
+
if (!(desc->type & OPTION_MULTI)) {
OptionValueVec::const_iterator it = p->findValue(key);
if (it != p->values.end()) {
return FG_OPTIONS_OK;
}
}
-
+
p->values.push_back(OptionValue(desc, value));
return FG_OPTIONS_OK;
}
p->values.erase(it);
}
}
-
+
p->values.push_back(OptionValue(desc, value));
return FG_OPTIONS_OK;
}
OptionValueVec::const_iterator it = p->findValue(key);
return (it != p->values.end());
}
-
+
string Options::valueForOption(const string& key, const string& defValue) const
{
OptionValueVec::const_iterator it = p->findValue(key);
if (it == p->values.end()) {
return defValue;
}
-
+
return it->value;
}
if (!it->desc) {
continue; // ignore marker values
}
-
+
if (it->desc->option == key) {
result.push_back(it->value);
}
}
-
+
return result;
}
-string defaultDownloadDir()
+SGPath defaultDownloadDir()
{
#if defined(SG_WINDOWS)
SGPath p(SGPath::documents());
#else
SGPath p(globals->get_fg_home());
#endif
- return p.str();
+ return p;
}
OptionResult Options::processOptions()
showUsage();
return FG_OPTIONS_EXIT;
}
-
+
// processing order is complicated. We must process groups LIFO, but the
// values *within* each group in FIFO order, to retain consistency with
// older versions of FG, and existing user configs.
OptionValueVec::const_iterator groupBegin = p->rfindGroup(groupEnd);
// run over the group in FIFO order
OptionValueVec::const_iterator it;
- for (it = groupBegin; it != groupEnd; ++it) {
+ for (it = groupBegin; it != groupEnd; ++it) {
int result = p->processOption(it->desc, it->value);
switch(result)
{
case FG_OPTIONS_ERROR:
showUsage();
return FG_OPTIONS_ERROR;
-
+
case FG_OPTIONS_EXIT:
return FG_OPTIONS_EXIT;
-
+
default:
break;
}
SG_LOG(SG_GENERAL, SG_INFO, "\toption:" << it->desc->option << " = " << it->value);
}
}
-
+
groupEnd = groupBegin;
}
BOOST_FOREACH(const SGPath& file, p->propertyFiles) {
SG_LOG(SG_GENERAL, SG_INFO,
- "Reading command-line property file " << file.str());
- readProperties(file.str(), globals->get_props());
+ "Reading command-line property file " << file);
+ readProperties(file, globals->get_props());
}
// now options are process, do supplemental fixup
}
// download dir fix-up
- string downloadDir = simgear::strutils::strip(fgGetString("/sim/paths/download-dir"));
- if (downloadDir.empty()) {
+ SGPath downloadDir = SGPath::fromUtf8(fgGetString("/sim/paths/download-dir"));
+ if (downloadDir.isNull()) {
downloadDir = defaultDownloadDir();
SG_LOG(SG_GENERAL, SG_INFO, "Using default download dir: " << downloadDir);
} else {
}
// terrasync directory fixup
- string terrasyncDir = simgear::strutils::strip(fgGetString("/sim/terrasync/scenery-dir"));
- if (terrasyncDir.empty()) {
+ SGPath terrasyncDir = SGPath::fromUtf8(fgGetString("/sim/terrasync/scenery-dir"));
+ if (terrasyncDir.isNull()) {
SGPath p(downloadDir);
p.append("TerraSync");
- terrasyncDir = p.str();
+ terrasyncDir = p;
simgear::Dir d(terrasyncDir);
if (!d.exists()) {
}
SG_LOG(SG_GENERAL, SG_INFO, "Using default TerraSync: " << terrasyncDir);
- fgSetString("/sim/terrasync/scenery-dir", p.str());
+ fgSetString("/sim/terrasync/scenery-dir", p.utf8Str());
} else {
SG_LOG(SG_GENERAL, SG_INFO, "Using explicit TerraSync dir: " << terrasyncDir);
}
// is enabled or not. This allows us to toggle terrasync on/off at
// runtime and have things work as expected
const PathList& scenery_paths(globals->get_fg_scenery());
- if (std::find(scenery_paths.begin(), scenery_paths.end(), SGPath(terrasyncDir)) == scenery_paths.end()) {
+ if (std::find(scenery_paths.begin(), scenery_paths.end(), terrasyncDir) == scenery_paths.end()) {
// terrasync dir is not in the scenery paths, add it
- globals->append_fg_scenery(SGPath(terrasyncDir));
+ globals->append_fg_scenery(terrasyncDir);
}
if (addFGDataScenery) {
return FG_OPTIONS_OK;
}
-
+
void Options::showUsage() const
{
fgOptLogLevel( "alert" );
-
+
FGLocale *locale = globals->get_locale();
SGPropertyNode options_root;
-
+
simgear::requestConsole(); // ensure console is shown on Windows
cout << endl;
cout << "Make sure the file options.xml is located in the FlightGear base directory," << endl;
cout << "and the location of the base directory is specified by setting $FG_ROOT or" << endl;
cout << "by adding --fg-root=path as a program argument." << endl;
-
+
exit(-1);
}
if (usage) {
cout << usage << endl;
}
-
+
vector<SGPropertyNode_ptr>section = options->getChildren("section");
for (unsigned int j = 0; j < section.size(); j++) {
string msg = "";
-
+
vector<SGPropertyNode_ptr>option = section[j]->getChildren("option");
for (unsigned int k = 0; k < option.size(); k++) {
-
+
SGPropertyNode *name = option[k]->getNode("name");
SGPropertyNode *short_name = option[k]->getNode("short");
SGPropertyNode *key = option[k]->getNode("key");
SGPropertyNode *arg = option[k]->getNode("arg");
bool brief = option[k]->getNode("brief") != 0;
-
+
if ((brief || p->verbose) && name) {
string tmp = name->getStringValue();
-
+
if (key){
tmp.append(":");
tmp.append(key->getStringValue());
tmp.append(", -");
tmp.append(short_name->getStringValue());
}
-
+
if (tmp.size() <= 25) {
msg+= " --";
msg += tmp;
}
// There may be more than one <description> tag associated
// with one option
-
+
vector<SGPropertyNode_ptr> desc;
desc = option[k]->getChildren("description");
if (! desc.empty()) {
vector<SGPropertyNode_ptr>trans_desc = locale->getLocalizedStrings(t.c_str(),"options");
for ( unsigned int m = 0; m < trans_desc.size(); m++ ) {
string t_str = trans_desc[m]->getStringValue();
-
+
if ((m > 0) || ((l > 0) && m == 0)) {
msg.append( 32, ' ');
}
-
+
// If the string is too large to fit on the screen,
// then split it up in several pieces.
-
+
while ( t_str.size() > 47 ) {
-
+
string::size_type m = t_str.rfind(' ', 47);
msg += t_str.substr(0, m) + '\n';
msg.append( 32, ' ');
-
+
t_str.erase(t_str.begin(), t_str.begin() + m + 1);
}
msg += t_str + '\n';
}
}
}
-
+
const char* name = locale->getLocalizedString(section[j]->getStringValue("name"),"options");
if (!msg.empty() && name) {
cout << endl << name << ":" << endl;
msg.erase();
}
}
-
+
if ( !p->verbose ) {
const char* verbose_help = locale->getLocalizedString(options->getStringValue("verbose-help"),"options");
if (verbose_help)
std::cin.get();
#endif
}
-
+
#if defined(__CYGWIN__)
SGPath Options::platformDefaultRoot() const
{
- return "../data";
+ return SGPath::fromUtf8("../data");
}
#elif defined(SG_WINDOWS)
SGPath Options::platformDefaultRoot() const
{
- return "..\\data";
+ return SGPath::fromUtf8("..\\data");
}
#elif defined(SG_MAC)
// platformDefaultRoot defined in CocoaHelpers.mm
#else
SGPath Options::platformDefaultRoot() const
{
- return SGPath(PKGLIBDIR);
+ return SGPath::fromUtf8(PKGLIBDIR);
}
#endif
-
+
void Options::setupRoot(int argc, char **argv)
{
SGPath root;
SG_LOG(SG_GENERAL, SG_INFO, "Qt launcher set fg_root = " << root );
}
}
- }
-
+ }
+
globals->set_fg_root(root);
static char required_version[] = FLIGHTGEAR_VERSION;
string base_version = fgBasePackageVersion(root);
exit(-1);
}
-
+
if (base_version != required_version) {
flightgear::fatalMessageBox("Base package version mismatch",
"Version check failed: please check your installation.",
}
#endif
}
-
+
bool Options::shouldLoadDefaultConfig() const
{
return p->shouldLoadDefaultConfig;
return true;
}
}
-
+
return false;
}
-
-} // of namespace flightgear
+} // of namespace flightgear
* Documents (FlightGear), on Unixes we default to FG_HOME, which is
* typically invisible.
*/
- std::string defaultDownloadDir();
+ SGPath defaultDownloadDir();
/// option processing can have various result values
/// depending on what the user requested. Note processOptions only
string acfile = fgGetString("/sim/aircraft") + string(".xml");
acData.append(acfile);
SGPropertyNode root;
- readProperties(acData.str(), &root);
+ readProperties(acData, &root);
SGPropertyNode * node = root.getNode("sim");
fltType = node->getStringValue("aircraft-class", "NONE" );
acOperator = node->getStringValue("aircraft-operator", "NONE" );
} catch (const sg_exception &) {
SG_LOG(SG_GENERAL, SG_INFO,
- "Could not load aircraft aircrat type and operator information from: " << acData.str() << ". Using defaults");
+ "Could not load aircraft aircrat type and operator information from: " << acData << ". Using defaults");
// cout << path.str() << endl;
}
if (fltType.empty() || fltType == "NONE") {
SG_LOG(SG_GENERAL, SG_INFO,
- "Aircraft type information not found in: " << acData.str() << ". Using default value");
+ "Aircraft type information not found in: " << acData << ". Using default value");
fltType = fgGetString("/sim/aircraft-class" );
}
if (acOperator.empty() || fltType == "NONE") {
SG_LOG(SG_GENERAL, SG_INFO,
- "Aircraft operator information not found in: " << acData.str() << ". Using default value");
+ "Aircraft operator information not found in: " << acData << ". Using default value");
acOperator = fgGetString("/sim/aircraft-operator" );
}
// no match found
return "";
}
-std::string fgValidatePath(const SGPath& path, bool write) { return fgValidatePath(path.str(),write); }
+std::string fgValidatePath(const SGPath& path, bool write) { return fgValidatePath(path.utf8Str(),write); }
// end of util.cxx
static osg::Node *
-fgLoad3DModelPanel(const std::string &path, SGPropertyNode *prop_root)
+fgLoad3DModelPanel(const SGPath &path, SGPropertyNode *prop_root)
{
bool loadPanels = true;
- osg::Node* node = simgear::SGModelLib::loadModel(path, prop_root, NULL, loadPanels);
+ osg::Node* node = simgear::SGModelLib::loadModel(path.local8BitStr(), prop_root, NULL, loadPanels);
if (node)
node->setNodeMask(~SG_NODEMASK_TERRAIN_BIT);
return node;
osg::Node* node = NULL;
try {
- node = fgLoad3DModelPanel( resolvedPath.str(), globals->get_props());
+ node = fgLoad3DModelPanel( resolvedPath, globals->get_props());
} catch (const sg_exception &ex) {
SG_LOG(SG_AIRCRAFT, SG_ALERT, "Failed to load aircraft from " << path << ':');
SG_LOG(SG_AIRCRAFT, SG_ALERT, " " << ex.getFormattedMessage());
// no models loaded, load the glider instead
if (!_aircraft.get()) {
SG_LOG(SG_AIRCRAFT, SG_ALERT, "(Falling back to glider.ac.)");
- osg::Node* model = fgLoad3DModelPanel( "Models/Geometry/glider.ac",
+ osg::Node* model = fgLoad3DModelPanel( SGPath::fromLocal8Bit("Models/Geometry/glider.ac"),
globals->get_props());
_aircraft.reset(new SGModelPlacement);
_aircraft->init(model);
bool FlightPlan::save(const SGPath& path)
{
- SG_LOG(SG_NAVAID, SG_INFO, "Saving route to " << path.str());
+ SG_LOG(SG_NAVAID, SG_INFO, "Saving route to " << path);
try {
SGPropertyNode_ptr d(new SGPropertyNode);
d->setIntValue("version", 2);
Waypt* wpt = _legs[i]->waypoint();
wpt->saveAsNode(routeNode->getChild("wp", i, true));
} // of waypoint iteration
- writeProperties(path.str(), d, true /* write-all */);
+ writeProperties(path, d, true /* write-all */);
return true;
} catch (sg_exception& e) {
- SG_LOG(SG_NAVAID, SG_ALERT, "Failed to save flight-plan '" << path.str() << "'. " << e.getMessage());
+ SG_LOG(SG_NAVAID, SG_ALERT, "Failed to save flight-plan '" << path << "'. " << e.getMessage());
return false;
}
}
{
if (!path.exists())
{
- SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load flight-plan '" << path.str()
+ SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load flight-plan '" << path
<< "'. The file does not exist.");
return false;
}
- SG_LOG(SG_NAVAID, SG_INFO, "going to read flight-plan from:" << path.str());
+ SG_LOG(SG_NAVAID, SG_INFO, "going to read flight-plan from:" << path);
bool Status = false;
lockDelegate();
GpxXmlVisitor gpxVistor(this);
try
{
- readXML(path.str(), gpxVistor);
+ readXML(path.local8BitStr(), gpxVistor);
} catch (sg_exception& e)
{
// XML parsing fails => not a GPX XML file
{
SGPropertyNode_ptr routeData(new SGPropertyNode);
try {
- readProperties(path.str(), routeData);
+ readProperties(path, routeData);
} catch (sg_exception& e) {
SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load flight-plan '" << e.getOrigin()
<< "'. " << e.getMessage());
_legs.push_back(new Leg(this, w));
} // of line iteration
} catch (sg_exception& e) {
- SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load route from: '" << path.str() << "'. " << e.getMessage());
+ SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load route from: '" << path << "'. " << e.getMessage());
_legs.clear();
return false;
}
if (tag == "Airport") {
string icao(atts.getValue("ICAOcode"));
if (_airport->ident() != icao) {
- throw sg_format_exception("Airport and ICAO mismatch", icao, _path.str());
+ throw sg_format_exception("Airport and ICAO mismatch", icao, _path.utf8Str());
}
} else if (tag == "Sid") {
string ident(atts.getValue("Name"));
void SHPParser::parsePolyLines(const SGPath& aPath, PolyLine::Type aTy,
PolyLineList& aResult, bool aClosed)
{
- gzFile file = gzopen(aPath.c_str(), "rb");
+ std::string s = aPath.local8BitStr();
+ gzFile file = gzopen(s.c_str(), "rb");
if (!file) {
- throw sg_io_exception("couldn't open file:" + aPath.str());
+ throw sg_io_exception("couldn't open file:", aPath);
}
try {
//int airwayIndex = 0;
//FGNode *n;
- sg_gzifstream in( path.str() );
+ sg_gzifstream in( path );
if ( !in.is_open() ) {
- SG_LOG( SG_NAVAID, SG_ALERT, "Cannot open file: " << path.str() );
- throw sg_io_exception("Could not open airways data", sg_location(path.str()));
+ SG_LOG( SG_NAVAID, SG_ALERT, "Cannot open file: " << path );
+ throw sg_io_exception("Could not open airways data", path);
}
// toss the first two lines of the file
in >> skipeol;
void loadFixes(const SGPath& path)
{
- sg_gzifstream in( path.str() );
+ sg_gzifstream in( path );
if ( !in.is_open() ) {
throw sg_io_exception("Cannot open file:", path);
}
// load and initialize the navigational databases
bool navDBInit(const SGPath& path)
{
- sg_gzifstream in( path.str() );
+ sg_gzifstream in( path );
if ( !in.is_open() ) {
- SG_LOG( SG_NAVAID, SG_ALERT, "Cannot open file: " << path.str() );
+ SG_LOG( SG_NAVAID, SG_ALERT, "Cannot open file: " << path );
return false;
}
bool loadCarrierNav(const SGPath& path)
{
- SG_LOG( SG_NAVAID, SG_DEBUG, "opening file: " << path.str() );
- sg_gzifstream incarrier( path.str() );
+ SG_LOG( SG_NAVAID, SG_DEBUG, "opening file: " << path );
+ sg_gzifstream incarrier( path );
if ( !incarrier.is_open() ) {
- SG_LOG( SG_NAVAID, SG_ALERT, "Cannot open file: " << path.str() );
+ SG_LOG( SG_NAVAID, SG_ALERT, "Cannot open file: " << path );
return false;
}
bool loadTacan(const SGPath& path, FGTACANList *channellist)
{
- SG_LOG( SG_NAVAID, SG_DEBUG, "opening file: " << path.str() );
- sg_gzifstream inchannel( path.str() );
+ SG_LOG( SG_NAVAID, SG_DEBUG, "opening file: " << path );
+ sg_gzifstream inchannel( path );
if ( !inchannel.is_open() ) {
- SG_LOG( SG_NAVAID, SG_ALERT, "Cannot open file: " << path.str() );
+ SG_LOG( SG_NAVAID, SG_ALERT, "Cannot open file: " << path );
return false;
}
// load and initialize the POI database
bool poiDBInit(const SGPath& path)
{
- sg_gzifstream in( path.str() );
+ sg_gzifstream in( path );
if ( !in.is_open() ) {
- SG_LOG( SG_NAVAID, SG_ALERT, "Cannot open file: " << path.str() );
+ SG_LOG( SG_NAVAID, SG_ALERT, "Cannot open file: " << path );
return false;
}
{
return (rr == SPEED_RESTRICT_MACH) || (rr == SPEED_COMPUTED_MACH);
}
-
+
Waypt::Waypt(RouteBase* aOwner) :
_altitudeFt(0.0),
_speed(0.0),
Waypt::~Waypt()
{
}
-
+
std::string Waypt::ident() const
{
return "";
}
-
+
bool Waypt::flag(WayptFlag aFlag) const
{
return ((_flags & aFlag) != 0);
}
-
+
void Waypt::setFlag(WayptFlag aFlag, bool aV)
{
if (aFlag == 0) {
throw sg_range_exception("invalid waypoint flag set");
}
-
+
_flags = (_flags & ~aFlag);
if (aV) _flags |= aFlag;
}
if (ident() != aOther->ident()) { // cheap check first
return false;
}
-
+
return matches(aOther->position());
}
assert(_speedRestrict != SPEED_RESTRICT_MACH);
return speed();
}
-
+
double Waypt::speedMach() const
{
assert(_speedRestrict == SPEED_RESTRICT_MACH);
if (_magVarDeg == NO_MAG_VAR) {
// derived classes with a default pos must override this method
assert(!(position() == SGGeod()));
-
+
double jd = globals->get_time_params()->getJD();
_magVarDeg = sgGetMagVar(position(), jd) * SG_RADIANS_TO_DEGREES;
}
-
+
return _magVarDeg;
}
-
+
double Waypt::headingRadialDeg() const
{
return 0.0;
}
-
+
///////////////////////////////////////////////////////////////////////////
// persistence
if (l == "below") return RESTRICT_BELOW;
if (l == "none") return RESTRICT_NONE;
if (l == "mach") return SPEED_RESTRICT_MACH;
-
+
if (l.empty()) return RESTRICT_NONE;
- throw sg_io_exception("unknown restriction specification:" + l,
+ throw sg_io_exception("unknown restriction specification:" + l,
"Route restrictFromString");
}
case RESTRICT_ABOVE: return "above";
case RESTRICT_NONE: return "none";
case SPEED_RESTRICT_MACH: return "mach";
-
+
default:
throw sg_exception("invalid route restriction",
"Route restrictToString");
throw sg_exception("broken factory method for type:" + aTypeName,
"Waypt::createInstance");
}
-
+
return r;
}
WayptRef Waypt::createFromProperties(RouteBase* aOwner, SGPropertyNode_ptr aProp)
{
if (!aProp->hasChild("type")) {
- throw sg_io_exception("bad props node, no type provided",
+ throw sg_io_exception("bad props node, no type provided",
"Waypt::createFromProperties");
}
-
+
try {
WayptRef nd(createInstance(aOwner, aProp->getStringValue("type")));
nd->initFromProperties(aProp);
} catch (sg_exception& e) {
SG_LOG(SG_GENERAL, SG_WARN, "failed to create waypoint, trying basic:" << e.getMessage());
}
-
+
// if we failed to make the waypoint, try again making a basic waypoint.
// this handles the case where a navaid waypoint is missing, for example
WayptRef nd(new BasicWaypt(aOwner));
nd->initFromProperties(aProp);
return nd;
}
-
+
void Waypt::saveAsNode(SGPropertyNode* n) const
{
n->setStringValue("type", type());
void Waypt::initFromProperties(SGPropertyNode_ptr aProp)
{
if (aProp->hasChild("generated")) {
- setFlag(WPT_GENERATED, aProp->getBoolValue("generated"));
+ setFlag(WPT_GENERATED, aProp->getBoolValue("generated"));
}
-
+
if (aProp->hasChild("overflight")) {
- setFlag(WPT_OVERFLIGHT, aProp->getBoolValue("overflight"));
+ setFlag(WPT_OVERFLIGHT, aProp->getBoolValue("overflight"));
}
-
+
if (aProp->hasChild("arrival")) {
- setFlag(WPT_ARRIVAL, aProp->getBoolValue("arrival"));
+ setFlag(WPT_ARRIVAL, aProp->getBoolValue("arrival"));
}
-
+
if (aProp->hasChild("approach")) {
setFlag(WPT_APPROACH, aProp->getBoolValue("approach"));
}
-
+
if (aProp->hasChild("departure")) {
- setFlag(WPT_DEPARTURE, aProp->getBoolValue("departure"));
+ setFlag(WPT_DEPARTURE, aProp->getBoolValue("departure"));
}
-
+
if (aProp->hasChild("miss")) {
- setFlag(WPT_MISS, aProp->getBoolValue("miss"));
+ setFlag(WPT_MISS, aProp->getBoolValue("miss"));
}
-
+
if (aProp->hasChild("alt-restrict")) {
_altRestrict = restrictionFromString(aProp->getStringValue("alt-restrict"));
_altitudeFt = aProp->getDoubleValue("altitude-ft");
}
-
+
if (aProp->hasChild("speed-restrict")) {
_speedRestrict = restrictionFromString(aProp->getStringValue("speed-restrict"));
_speed = aProp->getDoubleValue("speed");
}
-
-
+
+
}
void Waypt::writeToProperties(SGPropertyNode_ptr aProp) const
if (flag(WPT_DEPARTURE)) {
aProp->setBoolValue("departure", true);
}
-
+
if (flag(WPT_ARRIVAL)) {
aProp->setBoolValue("arrival", true);
}
-
+
if (flag(WPT_APPROACH)) {
aProp->setBoolValue("approach", true);
}
-
+
if (flag(WPT_MISS)) {
aProp->setBoolValue("miss", true);
}
-
+
if (flag(WPT_GENERATED)) {
aProp->setBoolValue("generated", true);
}
-
+
if (_altRestrict != RESTRICT_NONE) {
aProp->setStringValue("alt-restrict", restrictionToString(_altRestrict));
aProp->setDoubleValue("altitude-ft", _altitudeFt);
}
-
+
if (_speedRestrict != RESTRICT_NONE) {
aProp->setStringValue("speed-restrict", restrictionToString(_speedRestrict));
aProp->setDoubleValue("speed", _speed);
void RouteBase::dumpRouteToKML(const WayptVec& aRoute, const std::string& aName)
{
SGPath p = "/Users/jmt/Desktop/" + aName + ".kml";
- std::fstream f;
- f.open(p.str().c_str(), fstream::out | fstream::app);
+ sg_ofstream f(p);
if (!f.is_open()) {
- SG_LOG(SG_NAVAID, SG_WARN, "unable to open:" << p.str());
+ SG_LOG(SG_NAVAID, SG_WARN, "unable to open:" << p);
return;
}
-
+
// pre-amble
f << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n"
"<Document>\n";
dumpRouteToKMLLineString(aName, aRoute, f);
-
+
// post-amble
- f << "</Document>\n"
+ f << "</Document>\n"
"</kml>" << endl;
f.close();
}
aStream << "<LineString>\n";
aStream << "<tessellate>1</tessellate>\n";
aStream << "<coordinates>\n";
-
+
// waypoints
for (unsigned int i=0; i<aRoute.size(); ++i) {
SGGeod pos = aRoute[i]->position();
aStream << pos.getLongitudeDeg() << "," << pos.getLatitudeDeg() << " " << endl;
}
-
+
// postable
aStream << "</coordinates>\n"
"</LineString>\n"
assert(aApt);
try {
NavdataVisitor visitor(aApt, aPath);
- readXML(aPath.str(), visitor);
+ readXML(aPath.local8BitStr(), visitor);
} catch (sg_io_exception& ex) {
- SG_LOG(SG_NAVAID, SG_WARN, "failure parsing procedures: " << aPath.str() <<
+ SG_LOG(SG_NAVAID, SG_WARN, "failure parsing procedures: " << aPath <<
"\n\t" << ex.getMessage() << "\n\tat:" << ex.getLocation().asString());
} catch (sg_exception& ex) {
- SG_LOG(SG_NAVAID, SG_WARN, "failure parsing procedures: " << aPath.str() <<
+ SG_LOG(SG_NAVAID, SG_WARN, "failure parsing procedures: " << aPath <<
"\n\t" << ex.getMessage());
}
}
-
+
} // of namespace flightgear
exit( -1 );
}
- if ( input0_path.str().length() ) {
+ if ( !input0_path.isNull() ) {
input0 = new FGATCInput( 0, input0_path );
input0->open();
}
- if ( input1_path.str().length() ) {
+ if ( !input1_path.isNull() ) {
input1 = new FGATCInput( 1, input1_path );
input1->open();
}
- if ( output0_path.str().length() ) {
+ if ( !output0_path.isNull() ) {
output0 = new FGATCOutput( 0, output0_path );
output0->open( lock0_fd );
}
- if ( output1_path.str().length() ) {
+ if ( !output1_path.isNull() ) {
output1 = new FGATCOutput( 1, output1_path );
output1->open( lock1_fd );
}
path.append(file_name.c_str());
SG_LOG(SG_NETWORK, SG_INFO, "Reading communication protocol from "
- << path.str());
+ << path);
SGPropertyNode root;
try {
- readProperties(path.str(), &root);
+ readProperties(path, &root);
} catch (const sg_exception & ex) {
SG_LOG(SG_NETWORK, SG_ALERT,
"Unable to load the protocol configuration file: " << ex.getFormattedMessage() );
cJSON * json = cJSON_CreateObject();
if( c ) {
cJSON_AddItemToObject(json, "id", cJSON_CreateString( c->id().c_str() ));
- cJSON_AddItemToObject(json, "installRoot", cJSON_CreateString( c->installRoot().str().c_str() ));
+ std::string s = c->installRoot().utf8Str();
+ cJSON_AddItemToObject(json, "installRoot", cJSON_CreateString( s.c_str() ));
cJSON_AddItemToObject(json, "url", cJSON_CreateString( c->url().c_str() ));
cJSON_AddItemToObject(json, "description", cJSON_CreateString( c->description().c_str() ));
cJSON_AddItemToObject(json, "packages", PackageListToJson(c->packages()) );
cJSON * json = cJSON_CreateObject();
if( command == "path" ) {
-
- cJSON_AddItemToObject(json, "path", cJSON_CreateString( packageRoot->path().str().c_str() ));
+ std::string p = packageRoot->path().utf8Str();
+ cJSON_AddItemToObject(json, "path", cJSON_CreateString( p.c_str() ));
} else if( command == "version" ) {
// antenna.cxx -- implementation of FGRadioAntenna
-// Class to represent a virtual radio antenna properties
+// Class to represent a virtual radio antenna properties
// Written by Adrian Musceac YO8RZZ, started December 2011.
//
// This program is free software; you can redistribute it and/or
#include <stdlib.h>
#include <fstream>
#include <Scenery/scenery.hxx>
+#include <simgear/misc/sgstream.hxx>
+
#include "antenna.hxx"
using namespace std;
FGRadioAntenna::FGRadioAntenna(string type) {
-
+
_mirror_y = 1; // normally we want to mirror these axis because the pattern is simetric
_mirror_z = 1;
_invert_ground = 0; // TODO: use for inverting the antenna ground, for instance aircraft body reflection
// WIP
double FGRadioAntenna::calculate_gain(double bearing, double angle) {
-
+
// TODO: what if the pattern is assimetric?
bearing = fabs(bearing);
if (bearing > 180)
//cerr << "Bearing: " << bearing << " angle: " << angle << " azimuth: " << azimuth << " elevation: " << elevation << endl;
for (unsigned i =0; i < _pattern.size(); i++) {
AntennaGain *point_gain = _pattern[i];
-
+
if ( (azimuth == point_gain->azimuth) && (elevation == point_gain->elevation)) {
return point_gain->gain;
}
}
-
+
return 0;
}
void FGRadioAntenna::load_NEC_antenna_pattern(string type) {
-
+
//SGPath pattern_file(globals->get_fg_home());
SGPath pattern_file(globals->get_fg_root());
pattern_file.append("Navaids/Antennas");
if (!pattern_file.exists()) {
return;
}
- ifstream file_in(pattern_file.c_str());
+ sg_ifstream file_in(pattern_file);
int heading, elevation;
double gain;
while(!file_in.eof()) {
flightgear::FlightPlan* fp = new flightgear::FlightPlan;
SGPath path(naStr_data(args[0]));
if (!path.exists()) {
- naRuntimeError(c, "flightplan, no file at path %s", path.c_str());
+ std::string pdata = path.utf8Str();
+ naRuntimeError(c, "flightplan, no file at path %s", pdata.c_str());
}
if (!fp->load(path)) {
// SGPath caches permissions, which breaks for relative paths
// if the current directory changes
SG_LOG(SG_NASAL, SG_ALERT, "os.path: file operation on '" <<
- path.str() << "' access denied (relative paths not accepted; use "
+ path<< "' access denied (relative paths not accepted; use "
"realpath() to make a path absolute)");
}
- perm.read = path.isAbsolute() && !fgValidatePath(path.str(), false).empty();
- perm.write = path.isAbsolute() && !fgValidatePath(path.str(), true ).empty();
+ perm.read = path.isAbsolute() && !fgValidatePath(path, false).empty();
+ perm.write = path.isAbsolute() && !fgValidatePath(path, true ).empty();
return perm;
}
static naRef validatedPathToNasal( const nasal::CallContext& ctx,
const SGPath& p )
{
- return ctx.to_nasal( SGPathRef(new SGPath(p.str(), &checkIORules)) );
+ return ctx.to_nasal( SGPathRef(new SGPath(p.utf8Str(), &checkIORules)) );
}
/**
return p.create_dir(ctx.getArg<mode_t>(0, 0755) & 0775);
}
+static void f_path_set(SGPath& p, const nasal::CallContext& ctx)
+{
+ p = SGPath::fromUtf8(ctx.getArg<std::string>(0), p.getPermissionChecker());
+}
+
/**
* os.path.desktop()
*/
// See: http://docs.freeflightsim.org/simgear/classSGPath.html
NasalSGPath::init("os.path")
- .method("set", &SGPath::set)
+ .method("set", &f_path_set)
.method("append", &SGPath::append)
- .method("add", &SGPath::add)
.method("concat", &SGPath::concat)
.member("realpath", &SGPath::realpath)
.member("extension", &SGPath::extension)
.member("lower_extension", &SGPath::lower_extension)
.member("complete_lower_extension", &SGPath::complete_lower_extension)
- .member("str", &SGPath::str)
- .member("str_native", &SGPath::str_native)
+ .member("str", &SGPath::utf8Str)
.member("mtime", &SGPath::modTime)
.method("exists", &SGPath::exists)
naRuntimeError(c, "bad arguments to resolveDataPath()");
SGPath p = globals->resolve_maybe_aircraft_path(naStr_data(args[0]));
- const char* pdata = p.c_str();
- return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
+ std::string pdata = p.utf8Str();
+ return naStr_fromdata(naNewString(c), const_cast<char*>(pdata.c_str()), pdata.length());
}
static naRef f_findDataDir(naContext c, naRef me, int argc, naRef* args)
naRuntimeError(c, "bad arguments to findDataDir()");
SGPath p = globals->find_data_dir(naStr_data(args[0]));
- const char* pdata = p.c_str();
- return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
+ std::string pdata = p.utf8Str();
+ return naStr_fromdata(naNewString(c), const_cast<char*>(pdata.c_str()), pdata.length());
}
class NasalCommand : public SGCommandMgr::Command
SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
for (unsigned int i=0; i<scripts.size(); ++i) {
SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
- pFileNode->setStringValue(scripts[i].c_str());
+ pFileNode->setStringValue(scripts[i].utf8Str());
}
if (!module_node->hasChild("enabled",0))
{
bool FGNasalSys::loadModule(SGPath file, const char* module)
{
int len = 0;
- char* buf = readfile(file.c_str(), &len);
+ std::string pdata = file.local8BitStr();
+ char* buf = readfile(pdata.c_str(), &len);
if(!buf) {
SG_LOG(SG_NASAL, SG_ALERT,
- "Nasal error: could not read script file " << file.c_str()
+ "Nasal error: could not read script file " << file
<< " into module " << module);
return false;
}
- bool ok = createModule(module, file.c_str(), buf, len);
+ bool ok = createModule(module, pdata.c_str(), buf, len);
delete[] buf;
return ok;
}
return;
}
SG_LOG(SG_SOUND, SG_INFO, "Reading sound " << node->getName()
- << " from " << path.str());
+ << " from " << path);
SGPropertyNode root;
try {
- readProperties(path.str(), &root);
+ readProperties(path, &root);
} catch (const sg_exception &) {
SG_LOG(SG_SOUND, SG_ALERT,
- "Error reading file '" << path.str() << '\'');
+ "Error reading file '" << path << '\'');
return;
}
<< config.str() );
#endif
try {
- readProperties( config.str(), config_props );
+ readProperties( config, config_props );
if ( build(config_props) ) {
enabled = true;
} catch (const sg_exception&) {
SG_LOG( SG_SYSTEMS, SG_ALERT,
"Failed to load electrical system model: "
- << config.str() );
+ << config );
}
} else {
SG_LOG( SG_SYSTEMS, SG_INFO,
SGPath config = globals->resolve_aircraft_path(path_n->getStringValue());
SG_LOG( SG_SYSTEMS, SG_INFO, "Reading systems from "
- << config.str() );
+ << config );
try
{
- readProperties( config.str(), config_props );
+ readProperties( config, config_props );
build(config_props);
}
catch( const sg_exception& )
{
SG_LOG( SG_SYSTEMS, SG_ALERT, "Failed to load systems system model: "
- << config.str() );
+ << config );
}
} else {
{
SGPath zone(globals->get_fg_root());
zone.append("Timezone");
- _impl->updateLocal(globals->get_aircraft_position(), zone.str());
+ _impl->updateLocal(globals->get_aircraft_position(), zone.local8BitStr());
}
void TimeManager::initTimeOffset()
// initialize ambient, diffuse and specular tables
SGPath ambient_path = path;
ambient_path.append( "Lighting/ambient" );
- _ambient_tbl = new SGInterpTable( ambient_path.str() );
+ _ambient_tbl = new SGInterpTable( ambient_path );
SGPath diffuse_path = path;
diffuse_path.append( "Lighting/diffuse" );
- _diffuse_tbl = new SGInterpTable( diffuse_path.str() );
+ _diffuse_tbl = new SGInterpTable( diffuse_path );
SGPath specular_path = path;
specular_path.append( "Lighting/specular" );
- _specular_tbl = new SGInterpTable( specular_path.str() );
+ _specular_tbl = new SGInterpTable( specular_path );
// initialize sky table
SGPath sky_path = path;
sky_path.append( "Lighting/sky" );
- _sky_tbl = new SGInterpTable( sky_path.str() );
+ _sky_tbl = new SGInterpTable( sky_path );
globals->get_event_mgr()->addTask("updateSunPos", this,
&FGLight::updateSunPos, 0.5 );
*
**************************************************************************/
-/*
- * Traffic manager parses airlines timetable-like data and uses this to
+/*
+ * Traffic manager parses airlines timetable-like data and uses this to
* determine the approximate position of each AI aircraft in its database.
- * When an AI aircraft is close to the user's position, a more detailed
- * AIModels based simulation is set up.
- *
+ * When an AI aircraft is close to the user's position, a more detailed
+ * AIModels based simulation is set up.
+ *
* I'm currently assuming the following simplifications:
* 1) The earth is a perfect sphere
* 2) Each aircraft flies a perfect great circle route.
* 3) Each aircraft flies at a constant speed (with infinite accelerations and
- * decelerations)
- * 4) Each aircraft leaves at exactly the departure time.
- * 5) Each aircraft arrives at exactly the specified arrival time.
+ * decelerations)
+ * 4) Each aircraft leaves at exactly the departure time.
+ * 5) Each aircraft arrives at exactly the specified arrival time.
*
*
*****************************************************************************/
#include <simgear/compiler.h>
#include <simgear/misc/sg_path.hxx>
+#include <simgear/misc/sgstream.hxx>
#include <simgear/misc/sg_dir.hxx>
#include <simgear/props/props.hxx>
#include <simgear/structure/subsystem_mgr.hxx>
using std::vector;
/**
- * Thread encapsulating parsing the traffic schedules.
+ * Thread encapsulating parsing the traffic schedules.
*/
class ScheduleParseThread : public SGThread, public XMLVisitor
{
offset(0),
heavy(false)
{
-
+
}
-
+
// if we're destroyed while running, ensure the thread exits cleanly
~ScheduleParseThread()
{
_lock.unlock();
}
}
-
+
void setTrafficDirs(const PathList& dirs)
{
_trafficDirPaths = dirs;
}
-
+
bool isFinished() const
{
SGGuard<SGMutex> g(_lock);
return _isFinished;
}
-
+
virtual void run()
{
BOOST_FOREACH(SGPath p, _trafficDirPaths) {
return;
}
}
-
+
SGGuard<SGMutex> g(_lock);
_isFinished = true;
}
-
+
void startXML()
{
//cout << "Start XML" << endl;
requiredAircraft = "";
homePort = "";
}
-
+
void endXML()
{
//cout << "End XML" << endl;
}
-
+
void startElement(const char *name,
const XMLAttributes & atts)
{
SGPath path = globals->get_fg_root();
path.append("/Traffic/");
path.append(attval);
- readXML(path.str(), *this);
+ readXML(path.local8BitStr(), *this);
}
elementValueStack.push_back("");
// cout << " " << atts.getName(i) << '=' << atts.getValue(i) << endl;
}
-
+
void endElement(const char *name)
{
//cout << "End element " << name << endl;
const string & value = elementValueStack.back();
-
+
if (!strcmp(name, "model"))
mdl = value;
else if (!strcmp(name, "livery"))
//cerr << "Pusing back flight " << callsign << endl;
//cerr << callsign << " " << fltrules << " "<< departurePort << " " << arrivalPort << " "
// << cruiseAlt << " " << departureTime<< " "<< arrivalTime << " " << repeat << endl;
-
+
//Prioritize aircraft
string apt = fgGetString("/sim/presets/airport-id");
//cerr << "Airport information: " << apt << " " << departurePort << " " << arrivalPort << endl;
<< departureTime << ","
<< arrivalTime << "," << repeat << "," << requiredAircraft);
}
-
+
_trafficManager->flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
fltrules,
departurePort,
} else if (!strcmp(name, "aircraft")) {
endAircraft();
}
-
+
elementValueStack.pop_back();
}
-
+
void data(const char *s, int len)
{
string token = string(s, len);
//cout << "Character data " << string(s,len) << endl;
elementValueStack.back() += token;
}
-
+
void pi(const char *target, const char *data)
{
//cout << "Processing instruction " << target << ' ' << data << endl;
}
-
+
void warning(const char *message, int line, int column)
{
SG_LOG(SG_IO, SG_WARN,
"Warning: " << message << " (" << line << ',' << column << ')');
}
-
+
void error(const char *message, int line, int column)
{
SG_LOG(SG_IO, SG_ALERT,
"Error: " << message << " (" << line << ',' << column << ')');
}
-
+
private:
void endAircraft()
{
string isHeavy = heavy ? "true" : "false";
-
+
if (missingModels.find(mdl) != missingModels.end()) {
// don't stat() or warn again
requiredAircraft = homePort = "";
return;
}
-
+
if (!FGAISchedule::validModelPath(mdl)) {
missingModels.insert(mdl);
#if defined(ENABLE_DEV_WARNINGS)
requiredAircraft = homePort = "";
return;
}
-
+
int proportion =
(int) (fgGetDouble("/sim/traffic-manager/proportion") * 100);
int randval = rand() & 100;
requiredAircraft = homePort = "";
return;
}
-
+
if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
SG_LOG(SG_AI, SG_ALERT, "Traffic Dump AC," << homePort << "," << registration << "," << requiredAircraft
<< "," << acType << "," << livery << ","
<< airline << "," << m_class << "," << offset << "," << radius << "," << flighttype << "," << isHeavy << "," << mdl);
}
-
+
if (requiredAircraft == "") {
char buffer[16];
snprintf(buffer, 16, "%d", acCounter);
if (homePort == "") {
homePort = departurePort;
}
-
+
// caution, modifying the scheduled aircraft strucutre from the
// 'wrong' thread. This is safe becuase FGTrafficManager won't touch
// the structure while we exist.
m_class,
flighttype,
radius, offset));
-
+
acCounter++;
requiredAircraft = "";
homePort = "";
score = 0;
}
-
+
void parseTrafficDir(const SGPath& path)
{
SGTimeStamp st;
st.stamp();
-
+
simgear::Dir trafficDir(path);
simgear::PathList d = trafficDir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT);
-
+
BOOST_FOREACH(SGPath p, d) {
simgear::Dir d2(p);
SG_LOG(SG_AI, SG_INFO, "parsing traffic in:" << p);
simgear::PathList trafficFiles = d2.children(simgear::Dir::TYPE_FILE, ".xml");
- BOOST_FOREACH(SGPath xml, trafficFiles) {
- readXML(xml.str(), *this);
+ BOOST_FOREACH(SGPath xml, trafficFiles) {
+ readXML(xml.local8BitStr(), *this);
if (_cancelThread) {
return;
}
}
} // of sub-directories iteration
-
+
SG_LOG(SG_AI, SG_INFO, "parsing traffic schedules took:" << st.elapsedMSec() << "msec");
}
-
+
FGTrafficManager* _trafficManager;
mutable SGMutex _lock;
bool _isFinished;
bool _cancelThread;
simgear::PathList _trafficDirPaths;
-
+
// parser state
-
+
string_list elementValueStack;
// record model paths which are missing, to avoid duplicate
// warnings when parsing traffic schedules.
std::set<std::string> missingModels;
-
+
std::string mdl, livery, registration, callsign, fltrules,
port, timeString, departurePort, departureTime, arrivalPort, arrivalTime,
repeat, acType, airline, m_class, flighttype, requiredAircraft, homePort;
scheduleParser.reset();
doingInit = false;
}
-
+
return;
}
-
+
// Save the heuristics data
bool saveData = false;
- std::ofstream cachefile;
+ sg_ofstream cachefile;
if (fgGetBool("/sim/traffic-manager/heuristics")) {
SGPath cacheData(globals->get_fg_home());
cacheData.append("ai");
airport[0], airport[1], airport[2]);
cacheData.append(buffer);
cacheData.append(airport + "-cache.txt");
-
+
// Note: Intuitively, this doesn't make sense, but I do need to create the full file path first
// before creating the directories. The SimGear fgpath code has changed so that it first chops off
// the trailing dir separator and then determines the directory part of the file path by searching
// for the last dir separator. Effecively, this causes a full element of the directory tree to be
- // skipped.
- SG_LOG(SG_GENERAL, SG_DEBUG, "Trying to create dir for : " << cacheData.c_str());
+ // skipped.
+ SG_LOG(SG_GENERAL, SG_DEBUG, "Trying to create dir for : " << cacheData);
if (!cacheData.exists()) {
cacheData.create_dir(0755);
}
saveData = true;
- cachefile.open(cacheData.str().c_str());
+ cachefile.open(cacheData);
cachefile << "[TrafficManagerCachedata:ref:2011:09:04]" << endl;
-
+
}
}
-
+
BOOST_FOREACH(FGAISchedule* acft, scheduledAircraft) {
if (saveData) {
cachefile << acft->getRegistration() << " "
}
// TorstenD: don't start the traffic manager before the FDM is initialized
- // The FDM needs the scenery loaded and will wait for our spawned AIModels PagedLOD Nodes
+ // The FDM needs the scenery loaded and will wait for our spawned AIModels PagedLOD Nodes
// to appear if they are close (less than 1000m) to our position
if( !fgGetBool("/sim/signals/fdm-initialized") )
return;
terraSync->scheduleDataDir("AI/Traffic");
trafficSyncRequested = true;
}
-
+
if (terraSync->isDataDirPending("AI/Traffic")) {
return; // remain in the init state
}
-
+
SG_LOG(SG_AI, SG_INFO, "Traffic files sync complete");
}
-
+
doingInit = true;
if (string(fgGetString("/sim/traffic-manager/datafile")).empty()) {
simgear::PathList dirs = globals->get_data_paths("AI/Traffic");
-
+
// temporary flag to restrict loading while traffic data is found
// through terrasync /and/ fgdata. Ultimately we *do* want to be able to
// overlay sources.
-
+
if (dirs.size() > 1) {
SGPath p = dirs.back();
if (simgear::strutils::starts_with(p.utf8Str(),
dirs.pop_back();
}
}
-
+
if (dirs.empty()) {
doingInit = false;
return;
}
-
+
scheduleParser.reset(new ScheduleParseThread(this));
scheduleParser->setTrafficDirs(dirs);
scheduleParser->start();
// use a SchedulerParser to parse, but run it in this thread,
// i.e don't start it
ScheduleParseThread parser(this);
- readXML(path.str(), parser);
+ readXML(path.local8BitStr(), parser);
}
} else if (path.extension() == "conf") {
if (path.exists()) {
}
} else {
SG_LOG(SG_AI, SG_ALERT,
- "Unknown data format " << path.str()
+ "Unknown data format " << path
<< " for traffic");
}
//exit(1);
}
#endif
}
-
+
sort(scheduledAircraft.begin(), scheduledAircraft.end(),
compareSchedules);
currAircraft = scheduledAircraft.begin();
currAircraftClosest = scheduledAircraft.begin();
-
+
doingInit = false;
inited = true;
}
if (!fgGetBool("/sim/traffic-manager/heuristics")) {
return;
}
-
+
HeuristicMap heurMap;
//cerr << "Processing Heuristics" << endl;
// Load the heuristics data
cacheData.append(airport + "-cache.txt");
string revisionStr;
if (cacheData.exists()) {
- std::ifstream data(cacheData.c_str());
+ sg_ifstream data(cacheData);
data >> revisionStr;
if (revisionStr != "[TrafficManagerCachedata:ref:2011:09:04]") {
SG_LOG(SG_AI, SG_ALERT,"Traffic Manager Warning: discarding outdated cachefile " <<
- cacheData.c_str() << " for Airport " << airport);
+ cacheData << " for Airport " << airport);
} else {
while (1) {
Heuristic h; // = new Heuristic;
}
}
}
- }
-
+ }
+
for(currAircraft = scheduledAircraft.begin(); currAircraft != scheduledAircraft.end(); ++currAircraft) {
const string& registration = (*currAircraft)->getRegistration();
HeuristicMapIterator itr = heurMap.find(registration);
if (!doingInit) {
init();
}
-
+
if (!doingInit || !scheduleParser->isFinished()) {
return;
}
-
+
finishInit();
}
-
+
if (scheduledAircraft.empty()) {
return;
}
SGVec3d userCart = globals->get_aircraft_position_cart();
-
+
if (currAircraft == scheduledAircraft.end()) {
currAircraft = scheduledAircraft.begin();
}
string buffString;
vector <string> tokens, depTime,arrTime;
vector <string>::iterator it;
- std::ifstream infile(infileName.str().c_str());
+
+ sg_ifstream infile(infileName);
while (1) {
infile.getline(buffer, 256);
if (infile.eof()) {
if (!tokens.empty()) {
if (tokens[0] == string("AC")) {
if (tokens.size() != 13) {
- throw sg_io_exception("Error parsing traffic file @ " + buffString, sg_location(infileName.str()));
+ throw sg_io_exception("Error parsing traffic file @ " + buffString, infileName);
}
-
-
+
+
model = tokens[12];
livery = tokens[6];
homePort = tokens[1];
FlightType = tokens[9];
radius = atof(tokens[8].c_str());
offset = atof(tokens[7].c_str());;
-
+
if (!FGAISchedule::validModelPath(model)) {
SG_LOG(SG_AI, SG_WARN, "TrafficMgr: Missing model path:" <<
- model << " from " << infileName.str());
+ model << " from " << infileName);
} else {
-
+
SG_LOG(SG_AI, SG_INFO, "Adding Aircraft" << model << " " << livery << " " << homePort << " "
- << registration << " " << flightReq << " " << isHeavy
- << " " << acType << " " << airline << " " << m_class
+ << registration << " " << flightReq << " " << isHeavy
+ << " " << acType << " " << airline << " " << m_class
<< " " << FlightType << " " << radius << " " << offset);
- scheduledAircraft.push_back(new FGAISchedule(model,
- livery,
+ scheduledAircraft.push_back(new FGAISchedule(model,
+ livery,
homePort,
- registration,
+ registration,
flightReq,
isHeavy,
- acType,
- airline,
- m_class,
+ acType,
+ airline,
+ m_class,
FlightType,
radius,
offset));
if (tokens[0] == string("FLIGHT")) {
//cerr << "Found flight " << buffString << " size is : " << tokens.size() << endl;
if (tokens.size() != 10) {
- SG_LOG(SG_AI, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
+ SG_LOG(SG_AI, SG_ALERT, "Error parsing traffic file " << infileName << " at " << buffString);
exit(1);
}
string callsign = tokens[1];
<< cruiseAlt << " "
<< departureTime << " "
<< arrivalTime << " "
- << repeat << " "
+ << repeat << " "
<< requiredAircraft);
flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
pos = str.find_first_of(delimiters, lastPos);
}
}
-
-
SGPath mpath( globals->get_fg_root() );
mpath.append( fgGetString("/sim/rendering/materials-file") );
- if ( ! globals->get_matlib()->load(globals->get_fg_root().local8BitStr(), mpath.str(),
+ if ( ! globals->get_matlib()->load(globals->get_fg_root().local8BitStr(),
+ mpath.local8BitStr(),
globals->get_props()) ) {
throw sg_io_exception("Error loading materials file", mpath);
}
texture_path.append("Textures");
texture_path.append("Sky");
for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
- SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
+ SGCloudLayer * layer = new SGCloudLayer(texture_path.local8BitStr());
_sky->add_cloud_layer(layer);
}
- _sky->texture_path( texture_path.str() );
+ _sky->texture_path( texture_path.local8BitStr() );
if (!_classicalRenderer) {
eventHandler->setChangeStatsCameraRenderOrder( true );
SGSharedPtr<SGPropertyNode> style = fgGetNode("/sim/gui/style[0]", true);
osg::Texture2D* splashTexture = new osg::Texture2D;
- splashTexture->setImage(osgDB::readImageFile(tpath.c_str()));
+ splashTexture->setImage(osgDB::readImageFile(tpath.local8BitStr()));
osg::Camera* camera = new osg::Camera;
camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
FGFontCache* fontCache = FGFontCache::instance();
osgText::Text* text = new osgText::Text;
std::string fn = style->getStringValue("fonts/splash", "");
- text->setFont(fontCache->getfntpath(fn).str());
+ text->setFont(fontCache->getfntpath(fn).local8BitStr());
text->setCharacterSize(0.06);
text->setColor(osg::Vec4(1, 1, 1, 1));
text->setPosition(osg::Vec3(0, -0.92, 0));
geode->addDrawable(text);
osgText::Text* spinnertext = new osgText::Text;
- spinnertext->setFont(fontCache->getfntpath(fn).str());
+ spinnertext->setFont(fontCache->getfntpath(fn).local8BitStr());
spinnertext->setCharacterSize(0.06);
spinnertext->setColor(osg::Vec4(1, 1, 1, 1));
spinnertext->setPosition(osg::Vec3(0, -0.97, 0));
geode->addDrawable(spinnertext);
text = new osgText::Text;
- text->setFont(fontCache->getfntpath(fn).str());
+ text->setFont(fontCache->getfntpath(fn).local8BitStr());
text->setCharacterSize(0.08);
text->setColor(osg::Vec4(1, 1, 1, 1));
text->setPosition(osg::Vec3(0, 0.92, 0));
text = new osgText::Text;
- text->setFont(fontCache->getfntpath(fn).str());
+ text->setFont(fontCache->getfntpath(fn).local8BitStr());
text->setCharacterSize(0.06);
text->setColor(osg::Vec4(1, 1, 1, 1));
text->setPosition(osg::Vec3(0, 0.82, 0));
// open the gps file
file = path; file.append( "gps.dat.gz" );
- if ( (fgps = gzopen( file.c_str(), "r" )) == NULL ) {
- printf("Cannot open %s\n", file.c_str());
+ std::string fdata = file.local8BitStr();
+
+ if ( (fgps = gzopen( fdata.c_str(), "r" )) == NULL ) {
+ printf("Cannot open %s\n", fdata.c_str());
return false;
}
// open the imu file
file = path; file.append( "imu.dat.gz" );
- if ( (fimu = gzopen( file.c_str(), "r" )) == NULL ) {
- printf("Cannot open %s\n", file.c_str());
+ fdata = file.local8BitStr();
+ if ( (fimu = gzopen( fdata.c_str(), "r" )) == NULL ) {
+ printf("Cannot open %s\n", fdata.c_str());
return false;
}
// open the nav file
file = path; file.append( "nav.dat.gz" );
- if ( (fnav = gzopen( file.c_str(), "r" )) == NULL ) {
- printf("Cannot open %s\n", file.c_str());
+ fdata = file.local8BitStr();
+
+ if ( (fnav = gzopen( fdata.c_str(), "r" )) == NULL ) {
+ printf("Cannot open %s\n", fdata.c_str());
return false;
}
// open the servo file
file = path; file.append( "servo.dat.gz" );
- if ( (fservo = gzopen( file.c_str(), "r" )) == NULL ) {
- printf("Cannot open %s\n", file.c_str());
+ fdata = file.local8BitStr();
+
+ if ( (fservo = gzopen( fdata.c_str(), "r" )) == NULL ) {
+ printf("Cannot open %s\n", fdata.c_str());
return false;
}
// open the health file
file = path; file.append( "health.dat.gz" );
- if ( (fhealth = gzopen( file.c_str(), "r" )) == NULL ) {
- printf("Cannot open %s\n", file.c_str());
+ fdata = file.local8BitStr();
+
+ if ( (fhealth = gzopen( fdata.c_str(), "r" )) == NULL ) {
+ printf("Cannot open %s\n", fdata.c_str());
return false;
}
fg_root = PKGLIBDIR;
}
- std::string fg_scenery;
- if (arguments.read("--fg-scenery", fg_scenery)) {
- } else if (const char *fg_scenery_env = std::getenv("FG_SCENERY")) {
- fg_scenery = fg_scenery_env;
+ SGPath fg_scenery;
+ std::string s;
+ if (arguments.read("--fg-scenery", s)) {
+ fg_scenery = SGPath::fromLocal8Bit(s.c_str());
+ } else if (std::getenv("FG_SCENERY")) {
+ fg_scenery = SGPath::fromEnv("FG_SCENERY");
} else {
SGPath path(fg_root);
path.append("Scenery");
- fg_scenery = path.str();
+ fg_scenery = path;
}
SGSharedPtr<SGPropertyNode> props = new SGPropertyNode;
try {
SGPath preferencesFile = fg_root;
preferencesFile.append("preferences.xml");
- readProperties(preferencesFile.str(), props);
+ readProperties(preferencesFile, props);
} catch (...) {
// In case of an error, at least make summer :)
props->getNode("sim/startup/season", true)->setStringValue("summer");
SGPath mpath(fg_root);
mpath.append("Materials/default/materials.xml");
try {
- ml->load(fg_root, mpath.str(), props);
+ ml->load(fg_root, mpath.local8BitStr(), props);
} catch (...) {
SG_LOG(SG_GENERAL, SG_ALERT, "Problems loading FlightGear materials.\n"
<< "Probably FG_ROOT is not properly set.");
options = new simgear::SGReaderWriterOptions(*ropt);
else
options = new simgear::SGReaderWriterOptions;
- osgDB::convertStringPathIntoFilePathList(fg_scenery,
+ osgDB::convertStringPathIntoFilePathList(fg_scenery.local8BitStr(),
options->getDatabasePathList());
options->setMaterialLib(ml);
options->setPropertyNode(props);
if (!_initialized) {
char *envp = ::getenv("FG_FONTS");
if (envp != NULL) {
- _path.set(envp);
+ _path = SGPath::fromEnv("FG_FONTS");
} else {
- _path.set(ApplicationProperties::GetRootPath("Fonts").str());
+ _path = ApplicationProperties::GetRootPath("Fonts");
}
_initialized = true;
}
{
static std::string fontext("txf");
init();
- ulDir* fontdir = ulOpenDir(_path.c_str());
+ std::string pdata = _path.local8BitStr();
+ ulDir* fontdir = ulOpenDir(pdata.c_str());
if (!fontdir)
return false;
const ulDirEnt *dirEntry;
SGPath path(_path);
path.append(dirEntry->d_name);
if (path.extension() == fontext) {
+ std::string fdata = path.local8BitStr();
fntTexFont* f = new fntTexFont;
- if (f->load((char *)path.c_str()))
+ if (f->load((char *)fdata.c_str()))
_texFonts[std::string(dirEntry->d_name)] = f;
else
delete f;
try {
SGPath tpath = ApplicationProperties::GetRootPath( panelFilename.c_str() );
- readProperties( tpath.str(), ApplicationProperties::Properties );
+ readProperties( tpath, ApplicationProperties::Properties );
}
catch( sg_io_exception & e ) {
cerr << e.getFormattedMessage() << endl;
buf[511] = '\0';
if (cwd)
{
- path = cwd;
+ path = SGPath::fromLocal8Bit(cwd);
}
return path;
}
loader = textureLoader[extension];
}
- _texture = loader->loadTexture( tpath.c_str() );
- SG_LOG( SG_COCKPIT, SG_DEBUG, "Texture " << tpath.c_str() << " loaded from file as #" << _texture );
+ _texture = loader->loadTexture( tpath.local8BitStr() );
+ SG_LOG( SG_COCKPIT, SG_DEBUG, "Texture " << tpath << " loaded from file as #" << _texture );
cache[_path] = _texture;
}
sglog().set_log_classes(SG_ALL);
sglog().set_log_priority(SG_ALERT);
- std::string fg_root;
- if (arguments.read("--fg-root", fg_root)) {
- } else if (const char *fg_root_env = std::getenv("FG_ROOT")) {
- fg_root = fg_root_env;
+ SGPath fg_root;
+ std::string r;
+ if (arguments.read("--fg-root", r)) {
+ fg_root = SGPath::fromLocal8Bit(r.c_str());
+ } else if (std::getenv("FG_ROOT")) {
+ fg_root = SGPath::fromEnv("FG_ROOT");
} else {
- fg_root = PKGLIBDIR;
+ fg_root = SGPath(PKGLIBDIR);
}
- std::string fg_scenery;
- if (arguments.read("--fg-scenery", fg_scenery)) {
- } else if (const char *fg_scenery_env = std::getenv("FG_SCENERY")) {
- fg_scenery = fg_scenery_env;
+ SGPath fg_scenery;
+ std::string s;
+ if (arguments.read("--fg-scenery", s)) {
+ fg_scenery = SGPath::fromLocal8Bit(s.c_str());
+ } else if (std::getenv("FG_SCENERY")) {
+ fg_scenery = SGPath::fromEnv("FG_SCENERY");
} else {
SGPath path(fg_root);
path.append("Scenery");
- fg_scenery = path.str();
+ fg_scenery = path;
}
SGSharedPtr<SGPropertyNode> props = new SGPropertyNode;
try {
SGPath preferencesFile = fg_root;
preferencesFile.append("preferences.xml");
- readProperties(preferencesFile.str(), props);
+ readProperties(preferencesFile, props);
} catch (...) {
// In case of an error, at least make summer :)
props->getNode("sim/startup/season", true)->setStringValue("summer");
SGPath mpath(fg_root);
mpath.append("Materials/default/materials.xml");
try {
- ml->load(fg_root, mpath.str(), props);
+ ml->load(fg_root.local8BitStr(), mpath.local8BitStr(), props);
} catch (...) {
SG_LOG(SG_GENERAL, SG_ALERT, "Problems loading FlightGear materials.\n"
<< "Probably FG_ROOT is not properly set.");
}
- simgear::SGModelLib::init(fg_root, props);
+ simgear::SGModelLib::init(fg_root.local8BitStr(), props);
// Set up the reader/writer options
osg::ref_ptr<simgear::SGReaderWriterOptions> options;
options = new simgear::SGReaderWriterOptions(*ropt);
else
options = new simgear::SGReaderWriterOptions;
- osgDB::convertStringPathIntoFilePathList(fg_scenery,
+ osgDB::convertStringPathIntoFilePathList(fg_scenery.local8BitStr(),
options->getDatabasePathList());
options->setMaterialLib(ml);
options->setPropertyNode(props);
- options->setPluginStringData("SimGear::FG_ROOT", fg_root);
+ options->setPluginStringData("SimGear::FG_ROOT", fg_root.local8BitStr());
// Omit building bounding volume trees, as the viewer will not run a simulation
options->setPluginStringData("SimGear::BOUNDINGVOLUMES", "OFF");
viewer.setReaderWriterOptions(options.get());