Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/libraries/core/Core.cc @ 12099

Last change on this file since 12099 was 11692, checked in by landauf, 6 years ago

with the latest CMake there are a lot of warnings about the usage of CMP0026. therefore the naming and content of the module/plugin-files had to be changed:
old: <library-filename>.module with content <target-name>
new: <target-name>.module with content <library-filename>
this seems to comply better with cmake and works equally well in c++ (with some small adjustments).
reference: https://cmake.org/cmake/help/v3.0/policy/CMP0026.html

  • Property svn:eol-style set to native
File size: 18.5 KB
RevLine 
[1505]1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      Fabian 'x3n' Landau
[2896]24 *      Reto Grieder
[1505]25 *   Co-authors:
[2896]26 *      ...
[1505]27 *
28 */
29
30/**
[3196]31@file
32@brief
33    Implementation of the Core singleton with its global variables (avoids boost include)
[1505]34*/
35
[1524]36#include "Core.h"
[2710]37
[1756]38#include <cassert>
[7427]39#include <cstdlib>
40#include <ctime>
[7401]41#include <fstream>
[5929]42#include <vector>
[2710]43
44#ifdef ORXONOX_PLATFORM_WINDOWS
[2896]45#  ifndef WIN32_LEAN_AND_MEAN
46#    define WIN32_LEAN_AND_MEAN
47#  endif
[2710]48#  include <windows.h>
[3214]49#  undef min
50#  undef max
[2710]51#endif
52
[5929]53#include "util/Clock.h"
[8858]54#include "util/Output.h"
[2710]55#include "util/Exception.h"
[10624]56#include "util/SignalHandler.h"
[8858]57#include "util/output/LogWriter.h"
[9550]58#include "util/output/OutputManager.h"
[10624]59#include "core/singleton/Scope.h"
60#include "ApplicationPaths.h"
61#include "ConfigurablePaths.h"
62#include "commandline/CommandLineIncludes.h"
[9667]63#include "config/ConfigFileManager.h"
[5781]64#include "GameMode.h"
65#include "GraphicsManager.h"
66#include "GUIManager.h"
[1505]67#include "Language.h"
[10624]68#include "Loader.h"
[5695]69#include "LuaState.h"
[7284]70#include "command/IOConsole.h"
71#include "command/TclBind.h"
72#include "command/TclThreadManager.h"
[5781]73#include "input/InputManager.h"
[9667]74#include "object/ObjectList.h"
[10624]75#include "module/DynLibManager.h"
76#include "module/ModuleInstance.h"
77#include "module/StaticInitializationManager.h"
78#include "module/PluginManager.h"
79#include "CoreStaticInitializationHandler.h"
80#include "UpdateListener.h"
[1505]81
82namespace orxonox
83{
[3196]84    //! Static pointer to the singleton
[11071]85    Core* Core::singletonPtr_s  = nullptr;
[2662]86
[3280]87    SetCommandLineArgument(settingsFile, "orxonox.ini").information("THE configuration file");
[8351]88#if !defined(ORXONOX_PLATFORM_APPLE) && !defined(ORXONOX_USE_WINMAIN)
[6746]89    SetCommandLineSwitch(noIOConsole).information("Use this if you don't want to use the IOConsole (for instance for Lua debugging)");
[8351]90#endif
[7163]91
[3280]92#ifdef ORXONOX_PLATFORM_WINDOWS
[8505]93    SetCommandLineArgument(limitToCPU, 0).information("Limits the program to one CPU/core (1, 2, 3, etc.). Default is off = 0.");
[3280]94#endif
[2710]95
[11011]96    SetCommandLineArgument(generateDoc, "")
97        .information("Generates a Doxygen file from things like SetConsoleCommand");
98
[3323]99    Core::Core(const std::string& cmdLine)
[11071]100        : applicationPaths_(nullptr)
101        , configurablePaths_(nullptr)
102        , dynLibManager_(nullptr)
103        , signalHandler_(nullptr)
104        , configFileManager_(nullptr)
105        , languageInstance_(nullptr)
106        , loaderInstance_(nullptr)
107        , ioConsole_(nullptr)
108        , tclBind_(nullptr)
109        , tclThreadManager_(nullptr)
110        , rootScope_(nullptr)
111        , graphicsManager_(nullptr)
112        , inputManager_(nullptr)
113        , guiManager_(nullptr)
114        , graphicsScope_(nullptr)
[5781]115        , bGraphicsLoaded_(false)
[11071]116        , staticInitHandler_(nullptr)
117        , pluginManager_(nullptr)
118        , rootModule_(nullptr)
119        , config_(nullptr)
[8423]120        , destructionHelper_(this)
[3280]121    {
[8858]122        orxout(internal_status) << "initializing Core object..." << endl;
123
[5693]124        // Set the hard coded fixed paths
[10624]125        this->applicationPaths_ = new ApplicationPaths();
[3280]126
[5693]127        // Create a new dynamic library manager
[8423]128        this->dynLibManager_ = new DynLibManager();
[2896]129
[10624]130        // create handler for static initialization
131        new StaticInitializationManager(); // create singleton
132        this->staticInitHandler_ = new CoreStaticInitializationHandler();
133        StaticInitializationManager::getInstance().addHandler(this->staticInitHandler_);
[5693]134
[10624]135        // load root module (all libraries which are linked to the executable, including core, network, and orxonox)
136        this->rootModule_ = ModuleInstance::getCurrentModuleInstance();
137        StaticInitializationManager::getInstance().loadModule(this->rootModule_);
138
[5693]139        // Parse command line arguments AFTER the modules have been loaded (static code!)
[8729]140        CommandLineParser::parse(cmdLine);
[5693]141
142        // Set configurable paths like log, config and media
[10624]143        this->configurablePaths_ = new ConfigurablePaths();
144        this->configurablePaths_->setConfigurablePaths(ApplicationPaths::getInstance());
[5693]145
[10624]146        orxout(internal_info) << "Root path:       " << ApplicationPaths::getRootPathString() << endl;
147        orxout(internal_info) << "Executable path: " << ApplicationPaths::getExecutablePathString() << endl;
148        orxout(internal_info) << "Modules path:    " << ApplicationPaths::getModulePathString() << endl;
149        orxout(internal_info) << "Plugins path:    " << ApplicationPaths::getPluginPathString() << endl;
[8858]150
[10624]151        orxout(internal_info) << "Data path:       " << ConfigurablePaths::getDataPathString() << endl;
152        orxout(internal_info) << "Ext. data path:  " << ConfigurablePaths::getExternalDataPathString() << endl;
153        orxout(internal_info) << "Config path:     " << ConfigurablePaths::getConfigPathString() << endl;
154        orxout(internal_info) << "Log path:        " << ConfigurablePaths::getLogPathString() << endl;
155
156        // create a signal handler
[2896]157        // This call is placed as soon as possible, but after the directories are set
[8423]158        this->signalHandler_ = new SignalHandler();
[10624]159        this->signalHandler_->doCatch(ApplicationPaths::getExecutablePathString(), ConfigurablePaths::getLogPathString() + "orxonox_crash.log");
[2896]160
[3280]161#ifdef ORXONOX_PLATFORM_WINDOWS
162        // limit the main thread to the first core so that QueryPerformanceCounter doesn't jump
163        // do this after ogre has initialised. Somehow Ogre changes the settings again (not through
164        // the timer though).
[6021]165        int limitToCPU = CommandLineParser::getValue("limitToCPU");
[3280]166        if (limitToCPU > 0)
167            setThreadAffinity(static_cast<unsigned int>(limitToCPU));
168#endif
169
[2896]170        // Manage ini files and set the default settings file (usually orxonox.ini)
[8858]171        orxout(internal_info) << "Loading config:" << endl;
[8423]172        this->configFileManager_ = new ConfigFileManager();
[2896]173        this->configFileManager_->setFilename(ConfigFileType::Settings,
[9550]174            CommandLineParser::getValue("settingsFile").get<std::string>());
[2896]175
[3280]176        // Required as well for the config values
[8858]177        orxout(internal_info) << "Loading language:" << endl;
[8423]178        this->languageInstance_ = new Language();
[2896]179
[10624]180        // initialize root context
[11071]181        Context::setRootContext(new Context(nullptr));
[10624]182
[6417]183        // Do this soon after the ConfigFileManager has been created to open up the
184        // possibility to configure everything below here
[8858]185        orxout(internal_info) << "configuring Core" << endl;
[10624]186        this->config_ = new CoreConfig();
[6417]187
[8858]188        // Set the correct log path and rewrite the log file with the correct log levels
[10624]189        OutputManager::getInstance().getLogWriter()->setLogDirectory(ConfigurablePaths::getLogPathString());
[8858]190
[8351]191#if !defined(ORXONOX_PLATFORM_APPLE) && !defined(ORXONOX_USE_WINMAIN)
192        // Create persistent IO console
[10624]193        if (CommandLineParser::getValue("noIOConsole").get<bool>() == false && this->config_->getStartIOConsole())
[6746]194        {
[8858]195            orxout(internal_info) << "creating IO console" << endl;
[8423]196            this->ioConsole_ = new IOConsole();
[8858]197        }
[8351]198#endif
[6105]199
[5695]200        // creates the class hierarchy for all classes with factories
[8858]201        orxout(internal_info) << "creating class hierarchy" << endl;
[10624]202        this->staticInitHandler_->initInstances(this->rootModule_);
203        this->staticInitHandler_->setInitInstances(true);
[5695]204
[10624]205        // Create plugin manager and search for plugins
206        this->pluginManager_ = new PluginManager();
207        this->pluginManager_->findPlugins();
208
209        // Loader
210        this->loaderInstance_ = new Loader();
211
[5781]212        // Load OGRE excluding the renderer and the render window
[8858]213        orxout(internal_info) << "creating GraphicsManager:" << endl;
[8423]214        this->graphicsManager_ = new GraphicsManager(false);
[5781]215
216        // initialise Tcl
[10624]217        this->tclBind_ = new TclBind(ConfigurablePaths::getDataPathString());
[8423]218        this->tclThreadManager_ = new TclThreadManager(tclBind_->getTclInterpreter());
[5781]219
[5929]220        // Create singletons that always exist (in other libraries)
[8858]221        orxout(internal_info) << "creating root scope:" << endl;
[10624]222        this->rootScope_ = new Scope<ScopeID::ROOT>();
[7401]223
224        // Generate documentation instead of normal run?
225        std::string docFilename;
226        CommandLineParser::getValue("generateDoc", &docFilename);
227        if (!docFilename.empty())
228        {
229            std::ofstream docFile(docFilename.c_str());
230            if (docFile.is_open())
231            {
232                CommandLineParser::generateDoc(docFile);
233                docFile.close();
234            }
235            else
[8858]236                orxout(internal_error) << "Could not open file for documentation writing" << endl;
[7401]237        }
[8858]238
239        orxout(internal_status) << "finished initializing Core object" << endl;
[1505]240    }
241
[8423]242    void Core::destroy()
[1505]243    {
[8858]244        orxout(internal_status) << "destroying Core object..." << endl;
245
[8423]246        safeObjectDelete(&graphicsScope_);
247        safeObjectDelete(&guiManager_);
248        safeObjectDelete(&inputManager_);
249        safeObjectDelete(&graphicsManager_);
250        safeObjectDelete(&rootScope_);
251        safeObjectDelete(&tclThreadManager_);
252        safeObjectDelete(&tclBind_);
253        safeObjectDelete(&ioConsole_);
[10624]254        safeObjectDelete(&loaderInstance_);
255        safeObjectDelete(&config_);
[8423]256        safeObjectDelete(&languageInstance_);
257        safeObjectDelete(&configFileManager_);
258        safeObjectDelete(&signalHandler_);
[10624]259        safeObjectDelete(&pluginManager_);
260        Context::getRootContext()->unregisterObject(); // unregister context from object lists - otherwise the root context would be destroyed while unloading the root module
261        if (this->rootModule_)
262        {
263            StaticInitializationManager::getInstance().unloadModule(this->rootModule_);
264            this->rootModule_->deleteAllStaticallyInitializedInstances();
265        }
266        if (this->staticInitHandler_)
267            StaticInitializationManager::getInstance().removeHandler(this->staticInitHandler_);
268        Context::destroyRootContext();
269        safeObjectDelete(&rootModule_);
270        safeObjectDelete(&staticInitHandler_);
271        delete &StaticInitializationManager::getInstance();
[8423]272        safeObjectDelete(&dynLibManager_);
[10624]273        safeObjectDelete(&configurablePaths_);
274        safeObjectDelete(&applicationPaths_);
[2896]275
[8858]276        orxout(internal_status) << "finished destroying Core object" << endl;
[8729]277    }
278
[10624]279    void Core::loadModules()
[6417]280    {
[10624]281        orxout(internal_info) << "Loading modules:" << endl;
[6417]282
[11692]283        const std::map<std::string, std::string>& modulePaths = ApplicationPaths::getInstance().getModulePaths();
284        for (const std::pair<std::string, std::string>& modulePath : modulePaths)
[10624]285        {
[11692]286            ModuleInstance* module = new ModuleInstance(modulePath.second);
[10624]287            this->loadModule(module);
288            this->modules_.push_back(module);
289        }
290
291        orxout(internal_info) << "finished loading modules" << endl;
[6417]292    }
293
[10624]294    void Core::loadModule(ModuleInstance* module)
[8729]295    {
[10624]296        orxout(internal_info) << "Loading module " << module->getLibraryName() << "..." << endl;
[8729]297
[10624]298        try
299        {
300            ModuleInstance::setCurrentModuleInstance(module);
301            DynLib* dynLib = this->dynLibManager_->load(module->getLibraryName());
302            module->setDynLib(dynLib);
303
304            StaticInitializationManager::getInstance().loadModule(module);
305        }
306        catch (...)
307        {
308            orxout(user_error) << "Couldn't load module \"" << module->getLibraryName() << "\": " << Exception::handleMessage() << endl;
309        }
[6417]310    }
311
[10624]312    void Core::unloadModules()
[6417]313    {
[11071]314        for (ModuleInstance* module : this->modules_)
[6417]315        {
[10624]316            this->unloadModule(module);
317            delete module;
[6417]318        }
[10624]319        this->modules_.clear();
[6417]320    }
321
[10624]322    void Core::unloadModule(ModuleInstance* module)
323    {
324        orxout(internal_info) << "Unloading module " << module->getLibraryName() << "..." << endl;
325
326        StaticInitializationManager::getInstance().unloadModule(module);
327
328        module->deleteAllStaticallyInitializedInstances();
[11691]329        if (module->getDynLib()) {
330            this->dynLibManager_->unload(module->getDynLib());
331            module->setDynLib(nullptr);
332        }
[10624]333    }
334
[5781]335    void Core::loadGraphics()
336    {
[8858]337        orxout(internal_info) << "loading graphics in Core" << endl;
[9550]338
[5781]339        // Any exception should trigger this, even in upgradeToGraphics (see its remarks)
[10624]340        Loki::ScopeGuard unloader = Loki::MakeObjGuard(*this, &Core::unloadGraphics, true);
[5781]341
342        // Upgrade OGRE to receive a render window
[7175]343        try
344        {
345            graphicsManager_->upgradeToGraphics();
346        }
[7872]347        catch (const InitialisationFailedException&)
[7868]348        {
349            // Exit the application if the Ogre config dialog was canceled
[8858]350            orxout(user_error) << Exception::handleMessage() << endl;
[7868]351            exit(EXIT_FAILURE);
352        }
[7175]353        catch (...)
354        {
355            // Recovery from this is very difficult. It requires to completely
356            // destroy Ogre related objects and load again (without graphics).
357            // However since Ogre 1.7 there seems to be a problem when Ogre
358            // throws an exception and the graphics engine then gets destroyed
359            // and reloaded between throw and catch (access violation in MSVC).
360            // That's why we abort completely and only display the exception.
[8858]361            orxout(user_error) << "An exception occurred during upgrade to graphics. "
362                               << "That is unrecoverable. The message was:" << endl
363                               << Exception::handleMessage() << endl;
[7175]364            abort();
365        }
[5781]366
367        // Calls the InputManager which sets up the input devices.
[8423]368        inputManager_ = new InputManager();
[5781]369
[5929]370        // Load the CEGUI interface
[8423]371        guiManager_ = new GUIManager(inputManager_->getMousePosition());
[5781]372
[5929]373        bGraphicsLoaded_ = true;
374        GameMode::bShowsGraphics_s = true;
375
376        // Load some sort of a debug overlay (only denoted by its name, "debug.oxo")
377        graphicsManager_->loadDebugOverlay();
378
379        // Create singletons associated with graphics (in other libraries)
[8858]380        orxout(internal_info) << "creating graphics scope:" << endl;
[10624]381        graphicsScope_ = new Scope<ScopeID::GRAPHICS>();
[5929]382
[5781]383        unloader.Dismiss();
[8858]384
385        orxout(internal_info) << "finished loading graphics in Core" << endl;
[5781]386    }
387
[10624]388    void Core::unloadGraphics(bool loadGraphicsManagerWithoutRenderer)
[5781]389    {
[8858]390        orxout(internal_info) << "unloading graphics in Core" << endl;
391
[10624]392        if (this->graphicsManager_)
393            this->graphicsManager_->unloadDebugOverlay();
394
[8423]395        safeObjectDelete(&graphicsScope_);
396        safeObjectDelete(&guiManager_);
397        safeObjectDelete(&inputManager_);
398        safeObjectDelete(&graphicsManager_);
[5781]399
400        // Load Ogre::Root again, but without the render system
401        try
[10624]402        {
403            if (loadGraphicsManagerWithoutRenderer)
404                this->graphicsManager_ = new GraphicsManager(false);
405        }
[5781]406        catch (...)
407        {
[8858]408            orxout(user_error) << "An exception occurred during 'unloadGraphics':" << Exception::handleMessage() << endl
409                               << "Another exception might be being handled which may lead to undefined behaviour!" << endl
410                               << "Terminating the program." << endl;
[5781]411            abort();
412        }
413
414        bGraphicsLoaded_ = false;
[5929]415        GameMode::bShowsGraphics_s = false;
[5781]416    }
417
[1505]418    /**
[2896]419    @note
420        The code of this function has been copied and adjusted from OGRE, an open source graphics engine.
421            (Object-oriented Graphics Rendering Engine)
422        For the latest info, see http://www.ogre3d.org/
423
424        Copyright (c) 2000-2008 Torus Knot Software Ltd
425
426        OGRE is licensed under the LGPL. For more info, see OGRE license.
[2710]427    */
[2896]428    void Core::setThreadAffinity(int limitToCPU)
[2710]429    {
[3280]430#ifdef ORXONOX_PLATFORM_WINDOWS
431
[2896]432        if (limitToCPU <= 0)
433            return;
[2710]434
[2896]435        unsigned int coreNr = limitToCPU - 1;
436        // Get the current process core mask
[11115]437        ULONG_PTR procMask;
438        ULONG_PTR sysMask;
[2896]439#  if _MSC_VER >= 1400 && defined (_M_X64)
440        GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&procMask, (PDWORD_PTR)&sysMask);
441#  else
442        GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);
443#  endif
[2710]444
[2896]445        // If procMask is 0, consider there is only one core available
446        // (using 0 as procMask will cause an infinite loop below)
447        if (procMask == 0)
448            procMask = 1;
449
450        // if the core specified with coreNr is not available, take the lowest one
451        if (!(procMask & (1 << coreNr)))
452            coreNr = 0;
453
454        // Find the lowest core that this process uses and coreNr suggests
455        DWORD threadMask = 1;
456        while ((threadMask & procMask) == 0 || (threadMask < (1u << coreNr)))
457            threadMask <<= 1;
458
459        // Set affinity to the first core
460        SetThreadAffinityMask(GetCurrentThread(), threadMask);
461#endif
[2710]462    }
463
[5695]464    void Core::preUpdate(const Clock& time)
[2896]465    {
[10624]466        // Update UpdateListeners before general ticking
[11071]467        for (UpdateListener* listener : ObjectList<UpdateListener>())
468            listener->preUpdate(time);
[5781]469        if (this->bGraphicsLoaded_)
470        {
[6417]471            // Process input events
472            this->inputManager_->preUpdate(time);
473            // Update GUI
474            this->guiManager_->preUpdate(time);
[5781]475        }
[6417]476        // Process console events and status line
[11071]477        if (this->ioConsole_ != nullptr)
[6746]478            this->ioConsole_->preUpdate(time);
[6417]479        // Process thread commands
480        this->tclThreadManager_->preUpdate(time);
[2896]481    }
[3370]482
[5695]483    void Core::postUpdate(const Clock& time)
[3370]484    {
[10624]485        // Update UpdateListeners just before rendering
[11071]486        for (UpdateListener* listener : ObjectList<UpdateListener>())
487            listener->postUpdate(time);
[5781]488        if (this->bGraphicsLoaded_)
489        {
490            // Render (doesn't throw)
[6417]491            this->graphicsManager_->postUpdate(time);
[5781]492        }
[3370]493    }
[1505]494}
Note: See TracBrowser for help on using the repository browser.