| 1 | /* |
| 2 | * SPDX-FileName: main.cxx |
| 3 | * SPDX-FileComment: top level sim routines |
| 4 | * SPDX-FileCopyrightText: Copyright (C) 1997 - 2002 Curtis L. Olson - http://www.flightgear.org/~curt |
| 5 | * SPDX-License-Identifier: GPL-2.0-or-later |
| 6 | */ |
| 7 | |
| 8 | #include <config.h> |
| 9 | |
| 10 | #include <simgear/compiler.h> |
| 11 | #include <simgear/props/props_io.hxx> |
| 12 | |
| 13 | #include <iostream> |
| 14 | |
| 15 | #include <osg/Camera> |
| 16 | #include <osg/GraphicsContext> |
| 17 | #include <osgDB/Registry> |
| 18 | |
| 19 | |
| 20 | // Class references |
| 21 | #include <simgear/canvas/VGInitOperation.hxx> |
| 22 | #include <simgear/debug/logdelta.hxx> |
| 23 | #include <simgear/emesary/Emesary.hxx> |
| 24 | #include <simgear/emesary/notifications.hxx> |
| 25 | #include <simgear/io/raw_socket.hxx> |
| 26 | #include <simgear/math/SGMath.hxx> |
| 27 | #include <simgear/math/sg_random.hxx> |
| 28 | #include <simgear/misc/strutils.hxx> |
| 29 | #include <simgear/nasal/NasalEmesaryInterface.hxx> |
| 30 | #include <simgear/props/AtomicChangeListener.hxx> |
| 31 | #include <simgear/props/props.hxx> |
| 32 | #include <simgear/scene/material/Effect.hxx> |
| 33 | #include <simgear/scene/material/matlib.hxx> |
| 34 | #include <simgear/scene/model/modellib.hxx> |
| 35 | #include <simgear/scene/tsync/terrasync.hxx> |
| 36 | #include <simgear/structure/commands.hxx> |
| 37 | #include <simgear/timing/sg_time.hxx> |
| 38 | |
| 39 | #include <Add-ons/AddonManager.hxx> |
| 40 | #include <GUI/MessageBox.hxx> |
| 41 | #include <GUI/gui.h> |
| 42 | #include <Main/locale.hxx> |
| 43 | #include <Model/panelnode.hxx> |
| 44 | #include <Navaids/NavDataCache.hxx> |
| 45 | #include <Scenery/scenery.hxx> |
| 46 | #include <Sound/soundmanager.hxx> |
| 47 | #include <Time/TimeManager.hxx> |
| 48 | #include <Viewer/CameraGroup.hxx> |
| 49 | #include <Viewer/GraphicsPresets.hxx> |
| 50 | #include <Viewer/WindowSystemAdapter.hxx> |
| 51 | #include <Viewer/renderer.hxx> |
| 52 | #include <Viewer/splash.hxx> |
| 53 | #include <flightgearBuildId.h> |
| 54 | |
| 55 | #include "Main/MultipleInstanceLock.hxx" |
| 56 | #include "fg_commands.hxx" |
| 57 | #include "fg_init.hxx" |
| 58 | #include "fg_io.hxx" |
| 59 | #include "fg_os.hxx" |
| 60 | #include "fg_props.hxx" |
| 61 | #include "main.hxx" |
| 62 | #include "options.hxx" |
| 63 | #include "positioninit.hxx" |
| 64 | #include "screensaver_control.hxx" |
| 65 | #include "subsystemFactory.hxx" |
| 66 | #include "util.hxx" |
| 67 | #include <Main/ErrorReporter.hxx> |
| 68 | #include <Main/sentryIntegration.hxx> |
| 69 | |
| 70 | #include <simgear/embedded_resources/EmbeddedResourceManager.hxx> |
| 71 | #include <EmbeddedResources/FlightGear-resources.hxx> |
| 72 | |
| 73 | #if defined(HAVE_QT) |
| 74 | #include <GUI/QtLauncher.hxx> |
| 75 | #endif |
| 76 | |
| 77 | #ifdef __OpenBSD__ |
| 78 | #include <sys/resource.h> |
| 79 | #endif |
| 80 | |
| 81 | using namespace flightgear; |
| 82 | |
| 83 | using std::cerr; |
| 84 | using std::vector; |
| 85 | |
| 86 | // The atexit() function handler should know when the graphical subsystem |
| 87 | // is initialized. |
| 88 | extern int _bootstrap_OSInit; |
| 89 | |
| 90 | static SGPropertyNode_ptr frame_signal; |
| 91 | |
| 92 | #ifdef NASAL_BACKGROUND_GC_THREAD |
| 93 | static SGPropertyNode_ptr nasal_gc_threaded; |
| 94 | static SGPropertyNode_ptr nasal_gc_threaded_wait; |
| 95 | static SGSharedPtr<simgear::Notifications::MainLoopNotification> mln_begin(new simgear::Notifications::MainLoopNotification(simgear::Notifications::MainLoopNotification::Type::Begin)); |
| 96 | static SGSharedPtr<simgear::Notifications::MainLoopNotification> mln_end(new simgear::Notifications::MainLoopNotification(simgear::Notifications::MainLoopNotification::Type::End)); |
| 97 | static SGSharedPtr<simgear::Notifications::MainLoopNotification> mln_started(new simgear::Notifications::MainLoopNotification(simgear::Notifications::MainLoopNotification::Type::Started)); |
| 98 | static SGSharedPtr<simgear::Notifications::MainLoopNotification> mln_stopped(new simgear::Notifications::MainLoopNotification(simgear::Notifications::MainLoopNotification::Type::Stopped)); |
| 99 | static SGSharedPtr<simgear::Notifications::NasalGarbageCollectionConfigurationNotification> ngccn; |
| 100 | #endif |
| 101 | // This method is usually called after OSG has finished rendering a frame in what OSG calls an idle handler and |
| 102 | // is reposonsible for invoking all of the relevant per frame processing; most of which is handled by subsystems. |
| 103 | static void fgMainLoop( void ) |
| 104 | { |
| 105 | #ifdef NASAL_BACKGROUND_GC_THREAD |
| 106 | // |
| 107 | // the Nasal GC will automatically run when (during allocation) it discovers that more space is needed. |
| 108 | // This has a cost of between 5ms and 50ms (depending on the amount of currently active Nasal). |
| 109 | // The result is unscheduled and unpredictable pauses during normal operation when the garbage collector |
| 110 | // runs; which typically occurs at intervals between 1sec and 20sec. |
| 111 | // |
| 112 | // The solution to this, which overall increases CPU load, is to use a thread to do this; as Nasal is thread safe |
| 113 | // so what we do is to launch the garbage collection at the end of the main loop and then wait for completion at the start of the |
| 114 | // next main loop. |
| 115 | // So although the overall CPU is increased it has little effect on the frame rate; if anything it is an overall benefit |
| 116 | // as there are no unscheduled long duration frames. |
| 117 | // |
| 118 | // The implementation appears to work fine without waiting for completion at the start of the frame - so |
| 119 | // this wait at the start can be disabled by setting the property /sim/nasal-gc-threaded-wait to false. |
| 120 | |
| 121 | // first we see if the config has changed. The notification will return true from SetActive/SetWait when the |
| 122 | // value has been changed - and thus we notify the Nasal system that it should configure itself accordingly. |
| 123 | auto use_threaded_gc = nasal_gc_threaded->getBoolValue(); |
| 124 | auto threaded_wait = nasal_gc_threaded_wait->getBoolValue(); |
| 125 | bool notify_gc_config = false; |
| 126 | notify_gc_config = ngccn->SetActive(use_threaded_gc); |
| 127 | notify_gc_config |= ngccn->SetWait(threaded_wait); |
| 128 | if (notify_gc_config) |
| 129 | simgear::Emesary::GlobalTransmitter::instance()->NotifyAll(ngccn); |
| 130 | |
| 131 | simgear::Emesary::GlobalTransmitter::instance()->NotifyAll(mln_begin); |
| 132 | #endif |
| 133 | |
| 134 | if (sglog().has_popup()) { |
| 135 | std::string s = sglog().get_popup(); |
| 136 | flightgear::modalMessageBox("Alert", s, ""); |
| 137 | } |
| 138 | |
| 139 | frame_signal->fireValueChanged(); |
| 140 | |
| 141 | // Fetch the subsystem manager. |
| 142 | auto mgr = globals->get_subsystem_mgr(); |
| 143 | |
| 144 | // compute simulated time (allowing for pause, warp, etc) and |
| 145 | // real elapsed time |
| 146 | double sim_dt, real_dt; |
| 147 | mgr->get_subsystem<TimeManager>()->computeTimeDeltas(sim_dt, real_dt); |
| 148 | |
| 149 | // update all subsystems |
| 150 | mgr->update(sim_dt); |
| 151 | |
| 152 | // flush commands waiting in the queue |
| 153 | SGCommandMgr::instance()->executedQueuedCommands(); |
| 154 | simgear::AtomicChangeListener::fireChangeListeners(); |
| 155 | |
| 156 | #ifdef NASAL_BACKGROUND_GC_THREAD |
| 157 | simgear::Emesary::GlobalTransmitter::instance()->NotifyAll(mln_end); |
| 158 | #endif |
| 159 | } |
| 160 | |
| 161 | static void initTerrasync() |
| 162 | { |
| 163 | // add the terrasync root as a data path so data can be retrieved from it |
| 164 | // (even if we are in read-only mode) |
| 165 | SGPath terraSyncDir(globals->get_terrasync_dir()); |
| 166 | globals->append_data_path(terraSyncDir, false /* = ahead of FG_ROOT */); |
| 167 | |
| 168 | if (fgGetBool("/sim/fghome-readonly", false)) { |
| 169 | SG_LOG(SG_GENERAL, SG_ALERT, "initTerrasync() failing because /sim/fghome-readonly is true"); |
| 170 | return; |
| 171 | } |
| 172 | |
| 173 | // make fg-root dir available so existing Scenery data can be copied, and |
| 174 | // hence not downloaded again. |
| 175 | fgSetString("/sim/terrasync/installation-dir", (globals->get_fg_root() / "Scenery").utf8Str()); |
| 176 | |
| 177 | auto terra_sync = globals->get_subsystem_mgr()->add<simgear::SGTerraSync>(); |
| 178 | terra_sync->setRoot(globals->get_props()); |
| 179 | |
| 180 | terra_sync->bind(); |
| 181 | terra_sync->init(); |
| 182 | |
| 183 | if (fgGetBool("/sim/terrasync/enabled")) { |
| 184 | flightgear::addSentryTag("terrasync", "enabled"); |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | static void fgSetVideoOptions() |
| 189 | { |
| 190 | SGPath userDataPath = globals->get_fg_home(); |
| 191 | SGPath autosaveFile = globals->autosaveFilePath(userDataPath); |
| 192 | if (autosaveFile.exists()) return; |
| 193 | |
| 194 | std::string vendor = fgGetString("/sim/rendering/gl-vendor"); |
| 195 | SGPath path(globals->get_fg_root()); |
| 196 | path.append("Video"); |
| 197 | path.append(vendor); |
| 198 | if (path.exists()) |
| 199 | { |
| 200 | std::string renderer = fgGetString("/sim/rendering/gl-renderer"); |
| 201 | size_t pos = renderer.find("x86/"); |
| 202 | if (pos == std::string::npos) { |
| 203 | pos = renderer.find('/'); |
| 204 | } |
| 205 | if (pos == std::string::npos) { |
| 206 | pos = renderer.find(" ("); |
| 207 | } |
| 208 | if (pos != std::string::npos) { |
| 209 | renderer = renderer.substr(0, pos); |
| 210 | } |
| 211 | path.append(renderer+".xml"); |
| 212 | if (path.exists()) { |
| 213 | SG_LOG(SG_INPUT, SG_INFO, "Reading video settings from " << path); |
| 214 | try { |
| 215 | SGPropertyNode *r_prop = fgGetNode("/sim/rendering"); |
| 216 | readProperties(path, r_prop); |
| 217 | } catch (sg_exception& e) { |
| 218 | SG_LOG(SG_INPUT, SG_WARN, "failed to read video settings:" << e.getMessage() |
| 219 | << "(from " << e.getOrigin() << ")"); |
| 220 | } |
| 221 | } |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | static void checkOpenGLVersion() |
| 226 | { |
| 227 | flightgear::addSentryTag("gl-version", fgGetString("/sim/rendering/gl-version")); |
| 228 | flightgear::addSentryTag("gl-renderer", fgGetString("/sim/rendering/gl-vendor")); |
| 229 | flightgear::addSentryTag("gl-vendor", fgGetString("/sim/rendering/gl-renderer")); |
| 230 | |
| 231 | #if defined(SG_MAC) |
| 232 | // Mac users can't upgrade their drivers, so complaining about |
| 233 | // versions doesn't help them much |
| 234 | return; |
| 235 | #endif |
| 236 | |
| 237 | // format of these strings is not standardised, so be careful about |
| 238 | // parsing them. |
| 239 | std::string versionString(fgGetString("/sim/rendering/gl-version")); |
| 240 | string_list parts = simgear::strutils::split(versionString); |
| 241 | if (parts.size() == 3) { |
| 242 | if (parts[1].find("NVIDIA") != std::string::npos) { |
| 243 | // driver version number, dot-seperared |
| 244 | string_list driverVersion = simgear::strutils::split(parts[2], "."); |
| 245 | if (!driverVersion.empty()) { |
| 246 | int majorDriverVersion = simgear::strutils::to_int(driverVersion[0]); |
| 247 | if (majorDriverVersion < 300) { |
| 248 | std::ostringstream ss; |
| 249 | ss << "Please upgrade to at least version 300 of the nVidia drivers (installed version is " << parts[2] << ")"; |
| 250 | |
| 251 | flightgear::modalMessageBox("Outdated graphics drivers", |
| 252 | "FlightGear has detected outdated drivers for your graphics card.", |
| 253 | ss.str()); |
| 254 | } |
| 255 | } |
| 256 | } // of NVIDIA-style version string |
| 257 | } // of three parts |
| 258 | } |
| 259 | |
| 260 | namespace flightgear { |
| 261 | |
| 262 | void registerMainLoop() |
| 263 | { |
| 264 | // stash current frame signal property |
| 265 | frame_signal = fgGetNode("/sim/signals/frame", true); |
| 266 | |
| 267 | #ifdef NASAL_BACKGROUND_GC_THREAD |
| 268 | nasal_gc_threaded = fgGetNode("/sim/nasal-gc-threaded", true); |
| 269 | nasal_gc_threaded_wait = fgGetNode("/sim/nasal-gc-threaded-wait", true); |
| 270 | #endif |
| 271 | // init the Emesary receiver for Nasal |
| 272 | nasal::initMainLoopRecipient(); |
| 273 | |
| 274 | fgRegisterIdleHandler( fgMainLoop ); |
| 275 | } |
| 276 | |
| 277 | void unregisterMainLoopProperties() |
| 278 | { |
| 279 | nasal::shutdownMainLoopRecipient(); |
| 280 | frame_signal.reset(); |
| 281 | #ifdef NASAL_BACKGROUND_GC_THREAD |
| 282 | nasal_gc_threaded.reset(); |
| 283 | nasal_gc_threaded_wait.reset(); |
| 284 | #endif |
| 285 | } |
| 286 | |
| 287 | } // namespace flightgear |
| 288 | |
| 289 | // This is the top level master main function that is registered as |
| 290 | // our idle function |
| 291 | |
| 292 | // The first few passes take care of initialization things (a couple |
| 293 | // per pass) and once everything has been initialized fgMainLoop from |
| 294 | // then on. |
| 295 | |
| 296 | static int idle_state = 0; |
| 297 | |
| 298 | static void fgIdleFunction ( void ) { |
| 299 | // Specify our current idle function state. This is used to run all |
| 300 | // our initializations out of the idle callback so that we can get a |
| 301 | // splash screen up and running right away. |
| 302 | |
| 303 | // Fetch the subsystem manager. |
| 304 | auto mgr = globals->get_subsystem_mgr(); |
| 305 | |
| 306 | if ( idle_state == 0 ) { |
| 307 | auto camera = flightgear::getGUICamera(flightgear::CameraGroup::getDefault()); |
| 308 | if (guiInit(camera->getGraphicsContext())) { |
| 309 | checkOpenGLVersion(); |
| 310 | fgSetVideoOptions(); |
| 311 | idle_state++; |
| 312 | fgSplashProgress("loading-aircraft-list"); |
| 313 | fgSetBool("/sim/rendering/initialized", true); |
| 314 | } |
| 315 | } else if (idle_state == 1) { |
| 316 | if (flightgear::ExclusiveInstanceLock::isLocked()) { |
| 317 | fgSplashProgress("wait-on-shared-lock"); |
| 318 | return; |
| 319 | } else { |
| 320 | idle_state++; |
| 321 | } |
| 322 | |
| 323 | } else if (idle_state == 2) { |
| 324 | initTerrasync(); |
| 325 | idle_state++; |
| 326 | fgSplashProgress("loading-nav-dat"); |
| 327 | |
| 328 | } else if (idle_state == 3) { |
| 329 | bool done = fgInitNav(); |
| 330 | if (done) { |
| 331 | ++idle_state; |
| 332 | fgSplashProgress("init-scenery"); |
| 333 | // now the nav-cache is built, we can let other copies of FG run in parallel |
| 334 | // note if we used the launcher, the lock was already dropped. |
| 335 | flightgear::ExclusiveInstanceLock::destroyInstance(); |
| 336 | } |
| 337 | } else if (idle_state == 4) { |
| 338 | idle_state++; |
| 339 | |
| 340 | mgr->add<TimeManager>(); |
| 341 | |
| 342 | // Do some quick general initializations |
| 343 | if( !fgInitGeneral()) { |
| 344 | throw sg_exception("General initialization failed"); |
| 345 | } |
| 346 | |
| 347 | // now we have commands up |
| 348 | flightgear::delayedSentryInit(); |
| 349 | |
| 350 | //////////////////////////////////////////////////////////////////// |
| 351 | // Initialize the property-based built-in commands |
| 352 | //////////////////////////////////////////////////////////////////// |
| 353 | fgInitCommands(); |
| 354 | fgInitSceneCommands(); |
| 355 | |
| 356 | flightgear::registerSubsystemCommands(globals->get_commands()); |
| 357 | |
| 358 | //////////////////////////////////////////////////////////////////// |
| 359 | // Initialize the material manager |
| 360 | //////////////////////////////////////////////////////////////////// |
| 361 | globals->set_matlib( new SGMaterialLib ); |
| 362 | simgear::SGModelLib::setPanelFunc(FGPanelNode::load); |
| 363 | |
| 364 | } else if ((idle_state == 5) || (idle_state == 2005)) { |
| 365 | idle_state+=2; |
| 366 | flightgear::initPosition(); |
| 367 | |
| 368 | simgear::SGModelLib::init(globals->get_fg_root().utf8Str(), globals->get_props()); |
| 369 | |
| 370 | auto timeManager = mgr->get_subsystem<TimeManager>(); |
| 371 | timeManager->init(); |
| 372 | |
| 373 | //////////////////////////////////////////////////////////////////// |
| 374 | // Initialize the TG scenery subsystem. |
| 375 | //////////////////////////////////////////////////////////////////// |
| 376 | |
| 377 | auto scenery = mgr->add<FGScenery>(); |
| 378 | scenery->init(); |
| 379 | scenery->bind(); |
| 380 | |
| 381 | fgSplashProgress("creating-subsystems"); |
| 382 | } else if ((idle_state == 7) || (idle_state == 2007)) { |
| 383 | bool isReset = (idle_state == 2007); |
| 384 | idle_state = 8; // from the next state on, reset & startup are identical |
| 385 | SGTimeStamp st; |
| 386 | st.stamp(); |
| 387 | |
| 388 | try { |
| 389 | fgCreateSubsystems(isReset); |
| 390 | } catch (std::exception& e) { |
| 391 | // attempt to trace location of illegal argument / invalid string |
| 392 | // position errors on startup |
| 393 | flightgear::sentryReportException(std::string{"Creating subsystems: caught:"} + e.what()); |
| 394 | throw; |
| 395 | } |
| 396 | |
| 397 | SG_LOG(SG_GENERAL, SG_INFO, "Creating subsystems took:" << st.elapsedMSec()); |
| 398 | fgSplashProgress("binding-subsystems"); |
| 399 | |
| 400 | } else if (idle_state == 8) { |
| 401 | idle_state++; |
| 402 | SGTimeStamp st; |
| 403 | st.stamp(); |
| 404 | mgr->bind(); |
| 405 | SG_LOG(SG_GENERAL, SG_INFO, "Binding subsystems took:" << st.elapsedMSec()); |
| 406 | |
| 407 | fgSplashProgress("init-subsystems"); |
| 408 | } else if (idle_state == 9) { |
| 409 | SGSubsystem::InitStatus status = mgr->incrementalInit(); |
| 410 | if ( status == SGSubsystem::INIT_DONE) { |
| 411 | ++idle_state; |
| 412 | fgSplashProgress("finishing-subsystems"); |
| 413 | } else { |
| 414 | fgSplashProgress("init-subsystems"); |
| 415 | } |
| 416 | |
| 417 | } else if (idle_state == 10) { |
| 418 | idle_state = 900; |
| 419 | fgPostInitSubsystems(); |
| 420 | fgSplashProgress("finalize-position"); |
| 421 | } else if (idle_state == 900) { |
| 422 | idle_state = 1000; |
| 423 | |
| 424 | // setup OpenGL view parameters |
| 425 | globals->get_renderer()->setupView(); |
| 426 | |
| 427 | globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"), |
| 428 | fgGetInt("/sim/startup/ysize") ); |
| 429 | WindowSystemAdapter::getWSA()->windows[0]->gc->add( |
| 430 | new simgear::canvas::VGInitOperation() |
| 431 | ); |
| 432 | |
| 433 | int session = fgGetInt("/sim/session",0); |
| 434 | session++; |
| 435 | fgSetInt("/sim/session",session); |
| 436 | } |
| 437 | |
| 438 | if ( idle_state == 1000 ) { |
| 439 | sglog().setStartupLoggingEnabled(false); |
| 440 | |
| 441 | // We've finished all our initialization steps, from now on we |
| 442 | // run the main loop. |
| 443 | fgSetBool("sim/sceneryloaded", false); |
| 444 | flightgear::registerMainLoop(); |
| 445 | |
| 446 | #ifdef NASAL_BACKGROUND_GC_THREAD |
| 447 | ngccn = new simgear::Notifications::NasalGarbageCollectionConfigurationNotification(nasal_gc_threaded->getBoolValue(), nasal_gc_threaded_wait->getBoolValue()); |
| 448 | simgear::Emesary::GlobalTransmitter::instance()->NotifyAll(ngccn); |
| 449 | simgear::Emesary::GlobalTransmitter::instance()->NotifyAll(mln_started); |
| 450 | #endif |
| 451 | flightgear::addSentryBreadcrumb("entering main loop", "info"); |
| 452 | } |
| 453 | |
| 454 | if ( idle_state == 2000 ) { |
| 455 | flightgear::addSentryBreadcrumb("starting reset", "info"); |
| 456 | fgStartNewReset(); |
| 457 | idle_state = 2005; |
| 458 | } |
| 459 | } |
| 460 | |
| 461 | void fgResetIdleState() |
| 462 | { |
| 463 | idle_state = 2000; |
| 464 | fgRegisterIdleHandler( &fgIdleFunction ); |
| 465 | } |
| 466 | |
| 467 | void fgInitSecureMode() |
| 468 | { |
| 469 | bool secureMode = true; |
| 470 | if (Options::sharedInstance()->isOptionSet("allow-nasal-from-sockets")) { |
| 471 | SG_LOG(SG_GENERAL, SG_MANDATORY_INFO, "\n!! Network connections allowed to use Nasal !!\n" |
| 472 | "Network connections will be allowed full access to the simulator \n" |
| 473 | "including running arbitrary scripts. Ensure you have adequate security\n" |
| 474 | "(such as a firewall which blocks external connections).\n"); |
| 475 | secureMode = false; |
| 476 | } |
| 477 | |
| 478 | // it's by design that we overwrite any existing property tree value |
| 479 | // here - this prevents an aircraft or add-on setting the property |
| 480 | // value underneath us, eg in their -set.xml |
| 481 | SGPropertyNode_ptr secureFlag = fgGetNode("/sim/secure-flag", true); |
| 482 | secureFlag->setBoolValue(secureMode); |
| 483 | secureFlag->setAttributes(SGPropertyNode::READ | |
| 484 | SGPropertyNode::PRESERVE | |
| 485 | SGPropertyNode::PROTECTED); |
| 486 | } |
| 487 | |
| 488 | // this hack is needed to avoid weird viewport sizing within OSG on Windows. |
| 489 | // still required as of March 2017, sad times. |
| 490 | // see for example https://sourceforge.net/p/flightgear/codetickets/1958/ |
| 491 | static void ATIScreenSizeHack() |
| 492 | { |
| 493 | osg::ref_ptr<osg::Camera> hackCam = new osg::Camera; |
| 494 | hackCam->setRenderOrder(osg::Camera::PRE_RENDER); |
| 495 | int prettyMuchAnyInt = 1; |
| 496 | hackCam->setViewport(0, 0, prettyMuchAnyInt, prettyMuchAnyInt); |
| 497 | globals->get_renderer()->addCamera(hackCam, false); |
| 498 | } |
| 499 | |
| 500 | // Propose NVIDIA Optimus / AMD Xpress to use high-end GPU |
| 501 | #if defined(SG_WINDOWS) |
| 502 | extern "C" { |
| 503 | _declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001; |
| 504 | _declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1; |
| 505 | } |
| 506 | #endif |
| 507 | |
| 508 | struct SGLogDeltasListener : SGPropertyChangeListener |
| 509 | { |
| 510 | void valueChanged(SGPropertyNode* node) override |
| 511 | { |
| 512 | std::string value = node->getStringValue(); |
| 513 | std::cerr << __FILE__ << ":" << __LINE__ << ": sglogdeltas value=" << value << "\n"; |
| 514 | logDeltaSet(value.c_str()); |
| 515 | } |
| 516 | }; |
| 517 | static SGLogDeltasListener s_sglogdeltas_listener; |
| 518 | |
| 519 | // Main top level initialization |
| 520 | int fgMainInit( int argc, char **argv ) |
| 521 | { |
| 522 | sglog().setLogLevels( SG_ALL, SG_WARN ); |
| 523 | sglog().setStartupLoggingEnabled(true); |
| 524 | |
| 525 | globals = new FGGlobals; |
| 526 | auto initHomeResult = fgInitHome(argc, argv); |
| 527 | if (initHomeResult == InitHomeAbort) { |
| 528 | flightgear::fatalMessageBoxThenExit("Unable to create lock file", |
| 529 | "Flightgear was unable to create the lock file in FG_HOME"); |
| 530 | } |
| 531 | |
| 532 | #if defined(HAVE_QT) |
| 533 | flightgear::initApp(argc, argv); |
| 534 | #endif |
| 535 | |
| 536 | // check if the launcher is requested, since it affects config file parsing |
| 537 | bool showLauncher = flightgear::Options::checkForArgEnable(argc, argv, "launcher"); |
| 538 | // an Info.plist bundle can't define command line arguments, but it can set |
| 539 | // environment variables. This avoids needed a wrapper shell-script on OS-X. |
| 540 | showLauncher |= (::getenv("FG_LAUNCHER") != nullptr); |
| 541 | |
| 542 | bool needToShowReadOnlyWarning = (initHomeResult == InitHomeReadOnly); |
| 543 | #if defined(HAVE_QT) |
| 544 | // honour headless mode, even if Qt is enabled |
| 545 | // if we're in headless mode, we fall through to the case |
| 546 | // below and call modalMessageBox which logs |
| 547 | if (needToShowReadOnlyWarning && !flightgear::isHeadlessMode()) { |
| 548 | needToShowReadOnlyWarning = false; |
| 549 | auto r = flightgear::showLockFileDialog(); |
| 550 | if (r == flightgear::LockFileReset) { |
| 551 | SG_LOG( SG_GENERAL, SG_MANDATORY_INFO, "Deleting lock file at user request"); |
| 552 | flightgear::addSentryBreadcrumb("deleting lock-file at user request", "info"); |
| 553 | fgDeleteLockFile(); |
| 554 | fgSetBool("/sim/fghome-readonly", false); |
| 555 | } else if (r == flightgear::LockFileQuit) { |
| 556 | return EXIT_SUCCESS; |
| 557 | } |
| 558 | } |
| 559 | #endif |
| 560 | |
| 561 | if (needToShowReadOnlyWarning) { |
| 562 | // will handle headless mode by logging |
| 563 | flightgear::modalMessageBox("Multiple copies of FlightGear", |
| 564 | "Another copy of FlightGear is running, so this copy will run read-only.", |
| 565 | "This means aircraft and scenery cannot be downloaded, and settings will not be saved."); |
| 566 | } |
| 567 | |
| 568 | { |
| 569 | SGPropertyNode* sglogdeltas = globals->get_props()->getNode("/sim/sg-log-deltas", true /*create*/); |
| 570 | assert(sglogdeltas); |
| 571 | sglogdeltas->addChangeListener(&s_sglogdeltas_listener, false /*initial*/); |
| 572 | const char* sglogdeltas_value = getenv("SG_LOG_DELTAS"); |
| 573 | if (sglogdeltas_value) { |
| 574 | sglogdeltas->setStringValue(sglogdeltas_value); |
| 575 | } |
| 576 | } |
| 577 | |
| 578 | globals->get_props()->getNode("/sim", true /*create*/)->setAttribute(SGPropertyNode::VALUE_CHANGED_DOWN, true); |
| 579 | |
| 580 | { |
| 581 | SGPropertyNode* active = globals->get_props()->getNode("/sim/property-locking/active", true /*create*/); |
| 582 | SGPropertyNode* verbose = globals->get_props()->getNode("/sim/property-locking/verbose", true /*create*/); |
| 583 | SGPropertyNode* timing = globals->get_props()->getNode("/sim/property-locking/timing", true /*create*/); |
| 584 | SGPropertyNode* parent_listeners = globals->get_props()->getNode("/sim/property-locking/parent_listeners", true /*create*/); |
| 585 | SGPropertyLockControl(active, verbose, timing, parent_listeners); |
| 586 | } |
| 587 | |
| 588 | const bool readOnlyFGHome = fgGetBool("/sim/fghome-readonly"); |
| 589 | const auto level = flightgear::Options::getArgValue(argc, argv, "--log-level"); |
| 590 | fgInitLogging(level); |
| 591 | |
| 592 | if (readOnlyFGHome) { |
| 593 | flightgear::addSentryTag("fghome-readonly", "true"); |
| 594 | } |
| 595 | |
| 596 | std::string version(FLIGHTGEAR_VERSION); |
| 597 | SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version " << version ); |
| 598 | SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Build Type " << FG_BUILD_TYPE ); |
| 599 | SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR); |
| 600 | SG_LOG( SG_GENERAL, SG_INFO, "Jenkins number/ID " << JENKINS_BUILD_NUMBER << ":" |
| 601 | << JENKINS_BUILD_ID); |
| 602 | |
| 603 | flightgear::addSentryTag("osg-version", osgGetVersion()); |
| 604 | |
| 605 | #ifdef __OpenBSD__ |
| 606 | { |
| 607 | /* OpenBSD defaults to a small maximum data segment, which can cause |
| 608 | flightgear to crash with SIGBUS, so output a warning if this is likely. |
| 609 | */ |
| 610 | struct rlimit rlimit; |
| 611 | int e = getrlimit(RLIMIT_DATA, &rlimit); |
| 612 | if (e) { |
| 613 | SG_LOG( SG_GENERAL, SG_INFO, "This is OpenBSD; getrlimit() failed: " << strerror(errno)); |
| 614 | } |
| 615 | else { |
| 616 | unsigned long long required = 4ULL * (1ULL<<30); |
| 617 | if (rlimit.rlim_cur < required) { |
| 618 | SG_LOG( SG_GENERAL, SG_POPUP, "" |
| 619 | << "Max data segment (" << rlimit.rlim_cur << "bytes) too small.\n" |
| 620 | << "This can cause Flightgear to crash due to SIGBUS.\n" |
| 621 | << "E.g. increase with 'ulimit -d " << required/1024 << "'." |
| 622 | ); |
| 623 | } |
| 624 | } |
| 625 | } |
| 626 | #endif |
| 627 | |
| 628 | // seed the random number generator |
| 629 | sg_srandom_time(); |
| 630 | |
| 631 | string_list *col = new string_list; |
| 632 | globals->set_channel_options_list( col ); |
| 633 | |
| 634 | if (showLauncher) { |
| 635 | // to minimise strange interactions when launcher and config files |
| 636 | // set overlaping options, we disable the default files. Users can |
| 637 | // still explicitly request config files via --config options if they choose. |
| 638 | flightgear::Options::sharedInstance()->setShouldLoadDefaultConfig(false); |
| 639 | } |
| 640 | |
| 641 | // Load the configuration parameters. (Command line options |
| 642 | // override config file options. Config file options override |
| 643 | // defaults.) |
| 644 | int configResult = fgInitConfig(argc, argv, false); |
| 645 | if (configResult == flightgear::FG_OPTIONS_ERROR) { |
| 646 | return EXIT_FAILURE; |
| 647 | } else if (configResult == flightgear::FG_OPTIONS_EXIT) { |
| 648 | return EXIT_SUCCESS; |
| 649 | } |
| 650 | |
| 651 | bool didUseLauncher = false; |
| 652 | #if defined(HAVE_QT) |
| 653 | if (showLauncher) { |
| 654 | flightgear::addSentryBreadcrumb("starting launcher", "info"); |
| 655 | if (!flightgear::runLauncherDialog()) { |
| 656 | return EXIT_SUCCESS; |
| 657 | } |
| 658 | |
| 659 | didUseLauncher = true; |
| 660 | flightgear::addSentryBreadcrumb("completed launcher", "info"); |
| 661 | } |
| 662 | #else |
| 663 | if (showLauncher) { |
| 664 | SG_LOG(SG_GENERAL, SG_ALERT, "\n!Launcher requested, but FlightGear was compiled without Qt support!\n"); |
| 665 | } |
| 666 | #endif |
| 667 | |
| 668 | fgInitSecureMode(); |
| 669 | fgInitAircraftPaths(false); |
| 670 | |
| 671 | auto errorManager = globals->get_subsystem_mgr()->add<flightgear::ErrorReporter>(); |
| 672 | errorManager->preinit(); |
| 673 | |
| 674 | configResult = fgInitAircraft(false, didUseLauncher); |
| 675 | if (configResult == flightgear::FG_OPTIONS_ERROR) { |
| 676 | return EXIT_FAILURE; |
| 677 | } else if ((configResult == flightgear::FG_OPTIONS_EXIT) || |
| 678 | (configResult == flightgear::FG_OPTIONS_SHOW_AIRCRAFT)) |
| 679 | { |
| 680 | return EXIT_SUCCESS; |
| 681 | } |
| 682 | |
| 683 | addons::AddonManager::createInstance(); |
| 684 | |
| 685 | configResult = flightgear::Options::sharedInstance()->processOptions(); |
| 686 | if (configResult == flightgear::FG_OPTIONS_ERROR) { |
| 687 | return EXIT_FAILURE; |
| 688 | } else if (configResult == flightgear::FG_OPTIONS_EXIT) { |
| 689 | return EXIT_SUCCESS; |
| 690 | } |
| 691 | |
| 692 | // Set the lists of allowed paths for cases where a path comes from an |
| 693 | // untrusted source, such as the global property tree (this uses $FG_HOME |
| 694 | // and other paths set by Options::processOptions()). |
| 695 | fgInitAllowedPaths(); |
| 696 | |
| 697 | const auto& resMgr = simgear::EmbeddedResourceManager::createInstance(); |
| 698 | initFlightGearEmbeddedResources(); |
| 699 | // The language was set in processOptions() |
| 700 | const std::string locale = globals->get_locale()->getPreferredLanguage(); |
| 701 | // Must always be done after all resources have been added to 'resMgr' |
| 702 | resMgr->selectLocale(locale); |
| 703 | SG_LOG(SG_GENERAL, SG_INFO, |
| 704 | "EmbeddedResourceManager: selected locale '" << locale << "'"); |
| 705 | |
| 706 | if (fgGetBool("/sim/autosave-migration/did-migrate", false)) { |
| 707 | // inform the user we did migration. This is the earliest point |
| 708 | // we can do it, since now the locale is set |
| 709 | auto locale = globals->get_locale(); |
| 710 | const auto title = locale->getLocalizedString("settings-migration-title", "sys", "Settings migrated"); |
| 711 | const auto msg = locale->getLocalizedString("settings-migration-text", "sys", |
| 712 | "Saved settings were migrated from a previous version of FlightGear. " |
| 713 | "If you encounter any problems when using the system, try restoring " |
| 714 | "the default settings, before reporting a problem. " |
| 715 | "Saved settings can affect the appearance, performance and features of the simulator."); |
| 716 | flightgear::modalMessageBox(title, msg); |
| 717 | } |
| 718 | |
| 719 | // Copy the property nodes for the menus added by registered add-ons |
| 720 | addons::AddonManager::instance()->addAddonMenusToFGMenubar(); |
| 721 | |
| 722 | // The GraphicsPreset subsystem is special - it's not added together with |
| 723 | // the rest of the subsystems because it should be present before all the |
| 724 | // graphics-related stuff is initialized. |
| 725 | auto presets = globals->get_subsystem_mgr()->add<flightgear::GraphicsPresets>(); |
| 726 | presets->applyInitialPreset(); |
| 727 | |
| 728 | // Initialize the Window/Graphics environment. |
| 729 | |
| 730 | fgOSInit(&argc, argv); |
| 731 | _bootstrap_OSInit++; |
| 732 | |
| 733 | fgRegisterIdleHandler( &fgIdleFunction ); |
| 734 | |
| 735 | // Initialize sockets (WinSock needs this) |
| 736 | simgear::Socket::initSockets(); |
| 737 | |
| 738 | // Clouds3D requires an alpha channel |
| 739 | fgOSOpenWindow(true /* request stencil buffer */); |
| 740 | fgOSResetProperties(); |
| 741 | |
| 742 | fntInit(); |
| 743 | globals->get_renderer()->preinit(); |
| 744 | |
| 745 | if (fgGetBool("/sim/ati-viewport-hack", true)) { |
| 746 | SG_LOG(SG_GENERAL, SG_WARN, "Enabling ATI/AMD viewport hack"); |
| 747 | flightgear::addSentryTag("ati-viewport-hack", "enabled"); |
| 748 | ATIScreenSizeHack(); |
| 749 | } |
| 750 | |
| 751 | fgOutputSettings(); |
| 752 | |
| 753 | //try to disable the screensaver |
| 754 | fgOSDisableScreensaver(); |
| 755 | |
| 756 | // pass control off to the master event handler |
| 757 | int result = fgOSMainLoop(); |
| 758 | flightgear::unregisterMainLoopProperties(); |
| 759 | |
| 760 | fgOSCloseWindow(); |
| 761 | fgShutdownHome(); |
| 762 | |
| 763 | const bool requestLauncherRestart = fgGetBool("/sim/restart-launcher-on-exit"); |
| 764 | |
| 765 | #ifdef NASAL_BACKGROUND_GC_THREAD |
| 766 | simgear::Emesary::GlobalTransmitter::instance()->NotifyAll(mln_stopped); |
| 767 | #endif |
| 768 | |
| 769 | simgear::clearEffectCache(); |
| 770 | |
| 771 | // clean up here; ensure we null globals to avoid |
| 772 | // confusing the atexit() handler |
| 773 | delete globals; |
| 774 | globals = nullptr; |
| 775 | |
| 776 | // delete the NavCache here. This will cause the destruction of many cached |
| 777 | // objects (eg, airports, navaids, runways). |
| 778 | delete flightgear::NavDataCache::instance(); |
| 779 | |
| 780 | #if defined(HAVE_QT) |
| 781 | if (requestLauncherRestart) { |
| 782 | string_list originalArgs; |
| 783 | for (int arg = 1; arg < argc; ++arg) { |
| 784 | originalArgs.push_back(argv[arg]); |
| 785 | } |
| 786 | |
| 787 | if (!showLauncher) { |
| 788 | // The user specified the --restart-launcher option but without the |
| 789 | // --launcher option. So let's add the --launcher option so that the |
| 790 | // launcher actually starts instead of the simulator again. |
| 791 | originalArgs.push_back("--launcher"); |
| 792 | } |
| 793 | |
| 794 | flightgear::addSentryBreadcrumb("Requested to restart launcher", "info"); |
| 795 | flightgear::startLaunchOnExit(originalArgs); |
| 796 | } |
| 797 | #endif |
| 798 | return result; |
| 799 | } |