Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/core7/src/libraries/core/Core.cc @ 10580

Last change on this file since 10580 was 10552, checked in by landauf, 9 years ago

added PluginManager to load/unload plugins at runtime

  • 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"
[10540]56#include "util/SignalHandler.h"
[8858]57#include "util/output/LogWriter.h"
[9550]58#include "util/output/OutputManager.h"
[10407]59#include "core/singleton/Scope.h"
[10509]60#include "ApplicationPaths.h"
61#include "ConfigurablePaths.h"
[10345]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"
[10392]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"
[10540]75#include "module/DynLibManager.h"
[10342]76#include "module/ModuleInstance.h"
[10532]77#include "module/StaticInitializationManager.h"
[10552]78#include "module/PluginManager.h"
[10532]79#include "CoreStaticInitializationHandler.h"
[10413]80#include "UpdateListener.h"
[1505]81
82namespace orxonox
83{
[3196]84    //! Static pointer to the singleton
[3370]85    Core* Core::singletonPtr_s  = 0;
[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
[3323]96    Core::Core(const std::string& cmdLine)
[10509]97        : applicationPaths_(NULL)
98        , configurablePaths_(NULL)
[8423]99        , dynLibManager_(NULL)
100        , signalHandler_(NULL)
101        , configFileManager_(NULL)
102        , languageInstance_(NULL)
[10392]103        , loaderInstance_(NULL)
[8423]104        , ioConsole_(NULL)
105        , tclBind_(NULL)
106        , tclThreadManager_(NULL)
107        , rootScope_(NULL)
108        , graphicsManager_(NULL)
109        , inputManager_(NULL)
110        , guiManager_(NULL)
111        , graphicsScope_(NULL)
[5781]112        , bGraphicsLoaded_(false)
[10532]113        , staticInitHandler_(NULL)
[10552]114        , pluginManager_(NULL)
[10518]115        , rootModule_(NULL)
[10479]116        , config_(NULL)
[8423]117        , destructionHelper_(this)
[3280]118    {
[8858]119        orxout(internal_status) << "initializing Core object..." << endl;
120
[5693]121        // Set the hard coded fixed paths
[10509]122        this->applicationPaths_ = new ApplicationPaths();
[3280]123
[5693]124        // Create a new dynamic library manager
[8423]125        this->dynLibManager_ = new DynLibManager();
[2896]126
[10543]127        // create handler for static initialization
[10542]128        new StaticInitializationManager(); // create singleton
[10535]129        this->staticInitHandler_ = new CoreStaticInitializationHandler();
130        StaticInitializationManager::getInstance().addHandler(this->staticInitHandler_);
131
[10543]132        // load root module (all libraries which are linked to the executable, including core, network, and orxonox)
[10518]133        this->rootModule_ = ModuleInstance::getCurrentModuleInstance();
[10535]134        StaticInitializationManager::getInstance().loadModule(this->rootModule_);
[10342]135
[5693]136        // Parse command line arguments AFTER the modules have been loaded (static code!)
[8729]137        CommandLineParser::parse(cmdLine);
[5693]138
139        // Set configurable paths like log, config and media
[10509]140        this->configurablePaths_ = new ConfigurablePaths();
141        this->configurablePaths_->setConfigurablePaths(ApplicationPaths::getInstance());
[5693]142
[10509]143        orxout(internal_info) << "Root path:       " << ApplicationPaths::getRootPathString() << endl;
144        orxout(internal_info) << "Executable path: " << ApplicationPaths::getExecutablePathString() << endl;
145        orxout(internal_info) << "Modules path:    " << ApplicationPaths::getModulePathString() << endl;
[10547]146        orxout(internal_info) << "Plugins path:    " << ApplicationPaths::getPluginPathString() << endl;
[8858]147
[10509]148        orxout(internal_info) << "Data path:       " << ConfigurablePaths::getDataPathString() << endl;
149        orxout(internal_info) << "Ext. data path:  " << ConfigurablePaths::getExternalDataPathString() << endl;
150        orxout(internal_info) << "Config path:     " << ConfigurablePaths::getConfigPathString() << endl;
151        orxout(internal_info) << "Log path:        " << ConfigurablePaths::getLogPathString() << endl;
152
153        // create a signal handler
[2896]154        // This call is placed as soon as possible, but after the directories are set
[8423]155        this->signalHandler_ = new SignalHandler();
[10509]156        this->signalHandler_->doCatch(ApplicationPaths::getExecutablePathString(), ConfigurablePaths::getLogPathString() + "orxonox_crash.log");
[2896]157
[3280]158#ifdef ORXONOX_PLATFORM_WINDOWS
159        // limit the main thread to the first core so that QueryPerformanceCounter doesn't jump
160        // do this after ogre has initialised. Somehow Ogre changes the settings again (not through
161        // the timer though).
[6021]162        int limitToCPU = CommandLineParser::getValue("limitToCPU");
[3280]163        if (limitToCPU > 0)
164            setThreadAffinity(static_cast<unsigned int>(limitToCPU));
165#endif
166
[2896]167        // Manage ini files and set the default settings file (usually orxonox.ini)
[8858]168        orxout(internal_info) << "Loading config:" << endl;
[8423]169        this->configFileManager_ = new ConfigFileManager();
[2896]170        this->configFileManager_->setFilename(ConfigFileType::Settings,
[9550]171            CommandLineParser::getValue("settingsFile").get<std::string>());
[2896]172
[3280]173        // Required as well for the config values
[8858]174        orxout(internal_info) << "Loading language:" << endl;
[8423]175        this->languageInstance_ = new Language();
[2896]176
[10543]177        // initialize root context
178        Context::setRootContext(new Context(NULL));
179
[6417]180        // Do this soon after the ConfigFileManager has been created to open up the
181        // possibility to configure everything below here
[8858]182        orxout(internal_info) << "configuring Core" << endl;
[10479]183        this->config_ = new CoreConfig();
[6417]184
[8858]185        // Set the correct log path and rewrite the log file with the correct log levels
[10509]186        OutputManager::getInstance().getLogWriter()->setLogDirectory(ConfigurablePaths::getLogPathString());
[8858]187
[8351]188#if !defined(ORXONOX_PLATFORM_APPLE) && !defined(ORXONOX_USE_WINMAIN)
189        // Create persistent IO console
[10479]190        if (CommandLineParser::getValue("noIOConsole").get<bool>() == false && this->config_->getStartIOConsole())
[6746]191        {
[8858]192            orxout(internal_info) << "creating IO console" << endl;
[8423]193            this->ioConsole_ = new IOConsole();
[8858]194        }
[8351]195#endif
[6105]196
[5695]197        // creates the class hierarchy for all classes with factories
[8858]198        orxout(internal_info) << "creating class hierarchy" << endl;
[10535]199        this->staticInitHandler_->initInstances(this->rootModule_);
200        this->staticInitHandler_->setInitInstances(true);
[5695]201
[10552]202        // Create plugin manager and search for plugins
203        this->pluginManager_ = new PluginManager();
204        this->pluginManager_->findPlugins();
205
[10392]206        // Loader
207        this->loaderInstance_ = new Loader();
208
[5781]209        // Load OGRE excluding the renderer and the render window
[8858]210        orxout(internal_info) << "creating GraphicsManager:" << endl;
[8423]211        this->graphicsManager_ = new GraphicsManager(false);
[5781]212
213        // initialise Tcl
[10509]214        this->tclBind_ = new TclBind(ConfigurablePaths::getDataPathString());
[8423]215        this->tclThreadManager_ = new TclThreadManager(tclBind_->getTclInterpreter());
[5781]216
[5929]217        // Create singletons that always exist (in other libraries)
[8858]218        orxout(internal_info) << "creating root scope:" << endl;
[10464]219        this->rootScope_ = new Scope<ScopeID::ROOT>();
[7401]220
221        // Generate documentation instead of normal run?
222        std::string docFilename;
223        CommandLineParser::getValue("generateDoc", &docFilename);
224        if (!docFilename.empty())
225        {
226            std::ofstream docFile(docFilename.c_str());
227            if (docFile.is_open())
228            {
229                CommandLineParser::generateDoc(docFile);
230                docFile.close();
231            }
232            else
[8858]233                orxout(internal_error) << "Could not open file for documentation writing" << endl;
[7401]234        }
[8858]235
236        orxout(internal_status) << "finished initializing Core object" << endl;
[1505]237    }
238
[8423]239    void Core::destroy()
[1505]240    {
[8858]241        orxout(internal_status) << "destroying Core object..." << endl;
242
[8423]243        safeObjectDelete(&graphicsScope_);
244        safeObjectDelete(&guiManager_);
245        safeObjectDelete(&inputManager_);
246        safeObjectDelete(&graphicsManager_);
247        safeObjectDelete(&rootScope_);
248        safeObjectDelete(&tclThreadManager_);
249        safeObjectDelete(&tclBind_);
250        safeObjectDelete(&ioConsole_);
[10392]251        safeObjectDelete(&loaderInstance_);
[10479]252        safeObjectDelete(&config_);
[8423]253        safeObjectDelete(&languageInstance_);
254        safeObjectDelete(&configFileManager_);
[10527]255        safeObjectDelete(&signalHandler_);
[10552]256        safeObjectDelete(&pluginManager_);
[10527]257        Context::getRootContext()->unregisterObject(); // unregister context from object lists - otherwise the root context would be destroyed while unloading the root module
258        if (this->rootModule_)
259        {
[10535]260            StaticInitializationManager::getInstance().unloadModule(this->rootModule_);
[10527]261            this->rootModule_->deleteAllStaticallyInitializedInstances();
262        }
[10532]263        if (this->staticInitHandler_)
264            StaticInitializationManager::getInstance().removeHandler(this->staticInitHandler_);
[10544]265        Context::destroyRootContext();
[10527]266        safeObjectDelete(&rootModule_);
[10532]267        safeObjectDelete(&staticInitHandler_);
[10542]268        delete &StaticInitializationManager::getInstance();
[8423]269        safeObjectDelete(&dynLibManager_);
[10509]270        safeObjectDelete(&configurablePaths_);
271        safeObjectDelete(&applicationPaths_);
[2896]272
[8858]273        orxout(internal_status) << "finished destroying Core object" << endl;
[8729]274    }
275
[10518]276    void Core::loadModules()
277    {
278        orxout(internal_info) << "Loading modules:" << endl;
279
280        const std::vector<std::string>& modulePaths = ApplicationPaths::getInstance().getModulePaths();
281        for (std::vector<std::string>::const_iterator it = modulePaths.begin(); it != modulePaths.end(); ++it)
282        {
[10550]283            ModuleInstance* module = new ModuleInstance(*it);
284            this->loadModule(module);
285            this->modules_.push_back(module);
[10518]286        }
287
288        orxout(internal_info) << "finished loading modules" << endl;
289    }
290
291    void Core::loadModule(ModuleInstance* module)
292    {
[10549]293        orxout(internal_info) << "Loading module " << module->getLibraryName() << "..." << endl;
[10527]294
[10550]295        try
296        {
297            ModuleInstance::setCurrentModuleInstance(module);
298            DynLib* dynLib = this->dynLibManager_->load(module->getLibraryName());
299            module->setDynLib(dynLib);
[10532]300
[10550]301            StaticInitializationManager::getInstance().loadModule(module);
302        }
303        catch (...)
304        {
305            orxout(user_error) << "Couldn't load module \"" << module->getLibraryName() << "\": " << Exception::handleMessage() << endl;
306        }
[10518]307    }
308
309    void Core::unloadModules()
310    {
311        for (std::list<ModuleInstance*>::iterator it = this->modules_.begin(); it != this->modules_.end(); ++it)
312        {
313            ModuleInstance* module = (*it);
314            this->unloadModule(module);
315            delete module;
316        }
317        this->modules_.clear();
318    }
319
320    void Core::unloadModule(ModuleInstance* module)
321    {
[10551]322        orxout(internal_info) << "Unloading module " << module->getLibraryName() << "..." << endl;
[10527]323
[10532]324        StaticInitializationManager::getInstance().unloadModule(module);
325
[10518]326        module->deleteAllStaticallyInitializedInstances();
327        this->dynLibManager_->unload(module->getDynLib());
328        module->setDynLib(NULL);
329    }
330
[5781]331    void Core::loadGraphics()
332    {
[8858]333        orxout(internal_info) << "loading graphics in Core" << endl;
[9550]334
[5781]335        // Any exception should trigger this, even in upgradeToGraphics (see its remarks)
[10524]336        Loki::ScopeGuard unloader = Loki::MakeObjGuard(*this, &Core::unloadGraphics, true);
[5781]337
338        // Upgrade OGRE to receive a render window
[7175]339        try
340        {
341            graphicsManager_->upgradeToGraphics();
342        }
[7872]343        catch (const InitialisationFailedException&)
[7868]344        {
345            // Exit the application if the Ogre config dialog was canceled
[8858]346            orxout(user_error) << Exception::handleMessage() << endl;
[7868]347            exit(EXIT_FAILURE);
348        }
[7175]349        catch (...)
350        {
351            // Recovery from this is very difficult. It requires to completely
352            // destroy Ogre related objects and load again (without graphics).
353            // However since Ogre 1.7 there seems to be a problem when Ogre
354            // throws an exception and the graphics engine then gets destroyed
355            // and reloaded between throw and catch (access violation in MSVC).
356            // That's why we abort completely and only display the exception.
[8858]357            orxout(user_error) << "An exception occurred during upgrade to graphics. "
358                               << "That is unrecoverable. The message was:" << endl
359                               << Exception::handleMessage() << endl;
[7175]360            abort();
361        }
[5781]362
363        // Calls the InputManager which sets up the input devices.
[8423]364        inputManager_ = new InputManager();
[5781]365
[5929]366        // Load the CEGUI interface
[8423]367        guiManager_ = new GUIManager(inputManager_->getMousePosition());
[5781]368
[5929]369        bGraphicsLoaded_ = true;
370        GameMode::bShowsGraphics_s = true;
371
372        // Load some sort of a debug overlay (only denoted by its name, "debug.oxo")
373        graphicsManager_->loadDebugOverlay();
374
375        // Create singletons associated with graphics (in other libraries)
[8858]376        orxout(internal_info) << "creating graphics scope:" << endl;
[10464]377        graphicsScope_ = new Scope<ScopeID::GRAPHICS>();
[5929]378
[5781]379        unloader.Dismiss();
[8858]380
381        orxout(internal_info) << "finished loading graphics in Core" << endl;
[5781]382    }
383
[10524]384    void Core::unloadGraphics(bool loadGraphicsManagerWithoutRenderer)
[5781]385    {
[8858]386        orxout(internal_info) << "unloading graphics in Core" << endl;
387
[10525]388        if (this->graphicsManager_)
389            this->graphicsManager_->unloadDebugOverlay();
390
[8423]391        safeObjectDelete(&graphicsScope_);
392        safeObjectDelete(&guiManager_);
393        safeObjectDelete(&inputManager_);
394        safeObjectDelete(&graphicsManager_);
[5781]395
396        // Load Ogre::Root again, but without the render system
397        try
[10524]398        {
399            if (loadGraphicsManagerWithoutRenderer)
400                this->graphicsManager_ = new GraphicsManager(false);
401        }
[5781]402        catch (...)
403        {
[8858]404            orxout(user_error) << "An exception occurred during 'unloadGraphics':" << Exception::handleMessage() << endl
405                               << "Another exception might be being handled which may lead to undefined behaviour!" << endl
406                               << "Terminating the program." << endl;
[5781]407            abort();
408        }
409
410        bGraphicsLoaded_ = false;
[5929]411        GameMode::bShowsGraphics_s = false;
[5781]412    }
413
[1505]414    /**
[2896]415    @note
416        The code of this function has been copied and adjusted from OGRE, an open source graphics engine.
417            (Object-oriented Graphics Rendering Engine)
418        For the latest info, see http://www.ogre3d.org/
419
420        Copyright (c) 2000-2008 Torus Knot Software Ltd
421
422        OGRE is licensed under the LGPL. For more info, see OGRE license.
[2710]423    */
[2896]424    void Core::setThreadAffinity(int limitToCPU)
[2710]425    {
[3280]426#ifdef ORXONOX_PLATFORM_WINDOWS
427
[2896]428        if (limitToCPU <= 0)
429            return;
[2710]430
[2896]431        unsigned int coreNr = limitToCPU - 1;
432        // Get the current process core mask
433        DWORD procMask;
434        DWORD sysMask;
435#  if _MSC_VER >= 1400 && defined (_M_X64)
436        GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&procMask, (PDWORD_PTR)&sysMask);
437#  else
438        GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);
439#  endif
[2710]440
[2896]441        // If procMask is 0, consider there is only one core available
442        // (using 0 as procMask will cause an infinite loop below)
443        if (procMask == 0)
444            procMask = 1;
445
446        // if the core specified with coreNr is not available, take the lowest one
447        if (!(procMask & (1 << coreNr)))
448            coreNr = 0;
449
450        // Find the lowest core that this process uses and coreNr suggests
451        DWORD threadMask = 1;
452        while ((threadMask & procMask) == 0 || (threadMask < (1u << coreNr)))
453            threadMask <<= 1;
454
455        // Set affinity to the first core
456        SetThreadAffinityMask(GetCurrentThread(), threadMask);
457#endif
[2710]458    }
459
[5695]460    void Core::preUpdate(const Clock& time)
[2896]461    {
[10413]462        // Update UpdateListeners before general ticking
463        for (ObjectList<UpdateListener>::iterator it = ObjectList<UpdateListener>::begin(); it != ObjectList<UpdateListener>::end(); ++it)
464            it->preUpdate(time);
[5781]465        if (this->bGraphicsLoaded_)
466        {
[6417]467            // Process input events
468            this->inputManager_->preUpdate(time);
469            // Update GUI
470            this->guiManager_->preUpdate(time);
[5781]471        }
[6417]472        // Process console events and status line
[6746]473        if (this->ioConsole_ != NULL)
474            this->ioConsole_->preUpdate(time);
[6417]475        // Process thread commands
476        this->tclThreadManager_->preUpdate(time);
[2896]477    }
[3370]478
[5695]479    void Core::postUpdate(const Clock& time)
[3370]480    {
[10413]481        // Update UpdateListeners just before rendering
482        for (ObjectList<UpdateListener>::iterator it = ObjectList<UpdateListener>::begin(); it != ObjectList<UpdateListener>::end(); ++it)
483            it->postUpdate(time);
[5781]484        if (this->bGraphicsLoaded_)
485        {
486            // Render (doesn't throw)
[6417]487            this->graphicsManager_->postUpdate(time);
[5781]488        }
[3370]489    }
[1505]490}
Note: See TracBrowser for help on using the repository browser.