Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

fixed tests

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