Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

Loader is now a singleton instead of a static class. fixes issue with statically initialized ClassTreeMask (which again requires a BaseObject-Identifier)

  • Property svn:eol-style set to native
File size: 21.0 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"
[8858]56#include "util/output/LogWriter.h"
[9550]57#include "util/output/OutputManager.h"
[6417]58#include "util/Scope.h"
[7284]59#include "util/ScopedSingletonManager.h"
[2896]60#include "util/SignalHandler.h"
[5929]61#include "PathConfig.h"
[10345]62#include "commandline/CommandLineIncludes.h"
[9667]63#include "config/ConfigFileManager.h"
64#include "config/ConfigValueIncludes.h"
[2896]65#include "CoreIncludes.h"
[5693]66#include "DynLibManager.h"
[5781]67#include "GameMode.h"
68#include "GraphicsManager.h"
69#include "GUIManager.h"
[9667]70#include "class/Identifier.h"
[1505]71#include "Language.h"
[10392]72#include "Loader.h"
[5695]73#include "LuaState.h"
[10347]74#include "command/ConsoleCommandManager.h"
[7284]75#include "command/IOConsole.h"
76#include "command/TclBind.h"
77#include "command/TclThreadManager.h"
[5781]78#include "input/InputManager.h"
[9667]79#include "object/ObjectList.h"
[10342]80#include "module/ModuleInstance.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
[9667]96    // register Core as an abstract class to avoid problems if the class hierarchy is created within Core-constructor
[10362]97    RegisterAbstractClass(Core).inheritsFrom<Configurable>();
[9667]98
[3323]99    Core::Core(const std::string& cmdLine)
[8423]100        : pathConfig_(NULL)
101        , dynLibManager_(NULL)
102        , signalHandler_(NULL)
103        , configFileManager_(NULL)
104        , languageInstance_(NULL)
[10392]105        , loaderInstance_(NULL)
[8423]106        , ioConsole_(NULL)
107        , tclBind_(NULL)
108        , tclThreadManager_(NULL)
109        , rootScope_(NULL)
110        , graphicsManager_(NULL)
111        , inputManager_(NULL)
112        , guiManager_(NULL)
113        , graphicsScope_(NULL)
[5781]114        , bGraphicsLoaded_(false)
[6746]115        , bStartIOConsole_(true)
[7870]116        , lastLevelTimestamp_(0)
117        , ogreConfigTimestamp_(0)
[8366]118        , bDevMode_(false)
[8423]119        , destructionHelper_(this)
[3280]120    {
[8858]121        orxout(internal_status) << "initializing Core object..." << endl;
122
[5693]123        // Set the hard coded fixed paths
[8423]124        this->pathConfig_ = new PathConfig();
[3280]125
[5693]126        // Create a new dynamic library manager
[8423]127        this->dynLibManager_ = new DynLibManager();
[2896]128
[5693]129        // Load modules
[8858]130        orxout(internal_info) << "Loading modules:" << endl;
[5929]131        const std::vector<std::string>& modulePaths = this->pathConfig_->getModulePaths();
132        for (std::vector<std::string>::const_iterator it = modulePaths.begin(); it != modulePaths.end(); ++it)
[5693]133        {
[5929]134            try
[5693]135            {
[5929]136                this->dynLibManager_->load(*it);
[5693]137            }
[5929]138            catch (...)
139            {
[8858]140                orxout(user_error) << "Couldn't load module \"" << *it << "\": " << Exception::handleMessage() << endl;
[5929]141            }
[5693]142        }
143
[10345]144        // TODO: initialize CommandLineParser here
[10352]145        // TODO: initialize ConsoleCommandManager here
[10342]146        ModuleInstance::getCurrentModuleInstance()->loadAllStaticallyInitializedInstances();
147
[5693]148        // Parse command line arguments AFTER the modules have been loaded (static code!)
[8729]149        CommandLineParser::parse(cmdLine);
[5693]150
151        // Set configurable paths like log, config and media
[5929]152        this->pathConfig_->setConfigurablePaths();
[5693]153
[8858]154        orxout(internal_info) << "Root path:       " << PathConfig::getRootPathString() << endl;
155        orxout(internal_info) << "Executable path: " << PathConfig::getExecutablePathString() << endl;
156        orxout(internal_info) << "Data path:       " << PathConfig::getDataPathString() << endl;
157        orxout(internal_info) << "Ext. data path:  " << PathConfig::getExternalDataPathString() << endl;
158        orxout(internal_info) << "Config path:     " << PathConfig::getConfigPathString() << endl;
159        orxout(internal_info) << "Log path:        " << PathConfig::getLogPathString() << endl;
160        orxout(internal_info) << "Modules path:    " << PathConfig::getModulePathString() << endl;
161
[6105]162        // create a signal handler (only active for Linux)
[2896]163        // This call is placed as soon as possible, but after the directories are set
[8423]164        this->signalHandler_ = new SignalHandler();
[5929]165        this->signalHandler_->doCatch(PathConfig::getExecutablePathString(), PathConfig::getLogPathString() + "orxonox_crash.log");
[2896]166
[3280]167#ifdef ORXONOX_PLATFORM_WINDOWS
168        // limit the main thread to the first core so that QueryPerformanceCounter doesn't jump
169        // do this after ogre has initialised. Somehow Ogre changes the settings again (not through
170        // the timer though).
[6021]171        int limitToCPU = CommandLineParser::getValue("limitToCPU");
[3280]172        if (limitToCPU > 0)
173            setThreadAffinity(static_cast<unsigned int>(limitToCPU));
174#endif
175
[2896]176        // Manage ini files and set the default settings file (usually orxonox.ini)
[8858]177        orxout(internal_info) << "Loading config:" << endl;
[8423]178        this->configFileManager_ = new ConfigFileManager();
[2896]179        this->configFileManager_->setFilename(ConfigFileType::Settings,
[9550]180            CommandLineParser::getValue("settingsFile").get<std::string>());
[2896]181
[3280]182        // Required as well for the config values
[8858]183        orxout(internal_info) << "Loading language:" << endl;
[8423]184        this->languageInstance_ = new Language();
[2896]185
[6417]186        // Do this soon after the ConfigFileManager has been created to open up the
187        // possibility to configure everything below here
[9667]188        RegisterObject(Core);
[8858]189        orxout(internal_info) << "configuring Core" << endl;
[6417]190        this->setConfigValues();
191
[8858]192        // Set the correct log path and rewrite the log file with the correct log levels
[9550]193        OutputManager::getInstance().getLogWriter()->setLogDirectory(PathConfig::getLogPathString());
[8858]194
[8351]195#if !defined(ORXONOX_PLATFORM_APPLE) && !defined(ORXONOX_USE_WINMAIN)
196        // Create persistent IO console
[9550]197        if (CommandLineParser::getValue("noIOConsole").get<bool>())
[6746]198        {
199            ModifyConfigValue(bStartIOConsole_, tset, false);
200        }
201        if (this->bStartIOConsole_)
[8858]202        {
203            orxout(internal_info) << "creating IO console" << endl;
[8423]204            this->ioConsole_ = new IOConsole();
[8858]205        }
[8351]206#endif
[6105]207
[5695]208        // creates the class hierarchy for all classes with factories
[8858]209        orxout(internal_info) << "creating class hierarchy" << endl;
[9667]210        IdentifierManager::getInstance().createClassHierarchy();
[5695]211
[10392]212        // Loader
213        this->loaderInstance_ = new Loader();
214
[5781]215        // Load OGRE excluding the renderer and the render window
[8858]216        orxout(internal_info) << "creating GraphicsManager:" << endl;
[8423]217        this->graphicsManager_ = new GraphicsManager(false);
[5781]218
219        // initialise Tcl
[8423]220        this->tclBind_ = new TclBind(PathConfig::getDataPathString());
221        this->tclThreadManager_ = new TclThreadManager(tclBind_->getTclInterpreter());
[5781]222
[5929]223        // Create singletons that always exist (in other libraries)
[8858]224        orxout(internal_info) << "creating root scope:" << endl;
[8423]225        this->rootScope_ = new Scope<ScopeID::Root>();
[7401]226
227        // Generate documentation instead of normal run?
228        std::string docFilename;
229        CommandLineParser::getValue("generateDoc", &docFilename);
230        if (!docFilename.empty())
231        {
232            std::ofstream docFile(docFilename.c_str());
233            if (docFile.is_open())
234            {
235                CommandLineParser::generateDoc(docFile);
236                docFile.close();
237            }
238            else
[8858]239                orxout(internal_error) << "Could not open file for documentation writing" << endl;
[7401]240        }
[8858]241
242        orxout(internal_status) << "finished initializing Core object" << endl;
[1505]243    }
244
[8423]245    void Core::destroy()
[1505]246    {
[8858]247        orxout(internal_status) << "destroying Core object..." << endl;
248
[6417]249        // Remove us from the object lists again to avoid problems when destroying them
250        this->unregisterObject();
[8423]251
252        safeObjectDelete(&graphicsScope_);
253        safeObjectDelete(&guiManager_);
254        safeObjectDelete(&inputManager_);
255        safeObjectDelete(&graphicsManager_);
256        safeObjectDelete(&rootScope_);
257        safeObjectDelete(&tclThreadManager_);
258        safeObjectDelete(&tclBind_);
259        safeObjectDelete(&ioConsole_);
[10392]260        safeObjectDelete(&loaderInstance_);
[8423]261        safeObjectDelete(&languageInstance_);
262        safeObjectDelete(&configFileManager_);
[10346]263        ConsoleCommandManager::destroyAll();
[9667]264        Context::setRootContext(NULL);
265        IdentifierManager::getInstance().destroyAllIdentifiers();
[8423]266        safeObjectDelete(&signalHandler_);
267        safeObjectDelete(&dynLibManager_);
268        safeObjectDelete(&pathConfig_);
[2896]269
[8858]270        orxout(internal_status) << "finished destroying Core object" << endl;
[8729]271    }
272
[6417]273    //! Function to collect the SetConfigValue-macro calls.
274    void Core::setConfigValues()
275    {
[9550]276        SetConfigValueExternal(OutputManager::getInstance().getLogWriter()->configurableMaxLevel_,
277                               OutputManager::getInstance().getLogWriter()->getConfigurableSectionName(),
278                               OutputManager::getInstance().getLogWriter()->getConfigurableMaxLevelName(),
279                               OutputManager::getInstance().getLogWriter()->configurableMaxLevel_)
[8858]280            .description("The maximum level of output shown in the log file")
[9550]281            .callback(static_cast<BaseWriter*>(OutputManager::getInstance().getLogWriter()), &BaseWriter::changedConfigurableLevel);
282        SetConfigValueExternal(OutputManager::getInstance().getLogWriter()->configurableAdditionalContextsMaxLevel_,
283                               OutputManager::getInstance().getLogWriter()->getConfigurableSectionName(),
284                               OutputManager::getInstance().getLogWriter()->getConfigurableAdditionalContextsMaxLevelName(),
285                               OutputManager::getInstance().getLogWriter()->configurableAdditionalContextsMaxLevel_)
[8858]286            .description("The maximum level of output shown in the log file for additional contexts")
[9550]287            .callback(static_cast<BaseWriter*>(OutputManager::getInstance().getLogWriter()), &BaseWriter::changedConfigurableAdditionalContextsLevel);
288        SetConfigValueExternal(OutputManager::getInstance().getLogWriter()->configurableAdditionalContexts_,
289                               OutputManager::getInstance().getLogWriter()->getConfigurableSectionName(),
290                               OutputManager::getInstance().getLogWriter()->getConfigurableAdditionalContextsName(),
291                               OutputManager::getInstance().getLogWriter()->configurableAdditionalContexts_)
[8858]292            .description("Additional output contexts shown in the log file")
[9550]293            .callback(static_cast<BaseWriter*>(OutputManager::getInstance().getLogWriter()), &BaseWriter::changedConfigurableAdditionalContexts);
[6417]294
[8366]295        SetConfigValue(bDevMode_, PathConfig::buildDirectoryRun())
[8729]296            .description("Developer mode. If not set, hides some things from the user to not confuse him.")
297            .callback(this, &Core::devModeChanged);
[6417]298        SetConfigValue(language_, Language::getInstance().defaultLanguage_)
299            .description("The language of the in game text")
300            .callback(this, &Core::languageChanged);
301        SetConfigValue(bInitRandomNumberGenerator_, true)
302            .description("If true, all random actions are different each time you start the game")
303            .callback(this, &Core::initRandomNumberGenerator);
[6746]304        SetConfigValue(bStartIOConsole_, true)
305            .description("Set to false if you don't want to use the IOConsole (for Lua debugging for instance)");
[7870]306        SetConfigValue(lastLevelTimestamp_, 0)
307            .description("Timestamp when the last level was started.");
308        SetConfigValue(ogreConfigTimestamp_, 0)
309            .description("Timestamp when the ogre config file was changed.");
[6417]310    }
311
[8729]312    /** Callback function for changes in the dev mode that affect debug levels.
313        The function behaves according to these rules:
314        - 'normal' mode is defined based on where the program was launched: if
315          the launch path was the build directory, development mode \c on is
316          normal, otherwise normal means development mode \c off.
317        - Debug levels should not be hard configured (\c config instead of
318          \c tconfig) in non 'normal' mode to avoid strange behaviour.
319        - Changing the development mode from 'normal' to the other state will
320          immediately change the debug levels to predefined values which can be
321          reconfigured with \c tconfig.
322    @note
323        The debug levels for the IOConsole and the InGameConsole can be found
324        in the Shell class. The same rules apply.
325    */
326    void Core::devModeChanged()
327    {
328        // Inform listeners
329        ObjectList<DevModeListener>::iterator it = ObjectList<DevModeListener>::begin();
330        for (; it != ObjectList<DevModeListener>::end(); ++it)
331            it->devModeChanged(bDevMode_);
332    }
333
[6417]334    //! Callback function if the language has changed.
335    void Core::languageChanged()
336    {
337        // Read the translation file after the language was configured
338        Language::getInstance().readTranslatedLanguageFile();
339    }
340
341    void Core::initRandomNumberGenerator()
342    {
343        static bool bInitialized = false;
344        if (!bInitialized && this->bInitRandomNumberGenerator_)
345        {
346            srand(static_cast<unsigned int>(time(0)));
347            rand();
348            bInitialized = true;
349        }
350    }
351
[5781]352    void Core::loadGraphics()
353    {
[8858]354        orxout(internal_info) << "loading graphics in Core" << endl;
[9550]355
[5781]356        // Any exception should trigger this, even in upgradeToGraphics (see its remarks)
357        Loki::ScopeGuard unloader = Loki::MakeObjGuard(*this, &Core::unloadGraphics);
358
359        // Upgrade OGRE to receive a render window
[7175]360        try
361        {
362            graphicsManager_->upgradeToGraphics();
363        }
[7872]364        catch (const InitialisationFailedException&)
[7868]365        {
366            // Exit the application if the Ogre config dialog was canceled
[8858]367            orxout(user_error) << Exception::handleMessage() << endl;
[7868]368            exit(EXIT_FAILURE);
369        }
[7175]370        catch (...)
371        {
372            // Recovery from this is very difficult. It requires to completely
373            // destroy Ogre related objects and load again (without graphics).
374            // However since Ogre 1.7 there seems to be a problem when Ogre
375            // throws an exception and the graphics engine then gets destroyed
376            // and reloaded between throw and catch (access violation in MSVC).
377            // That's why we abort completely and only display the exception.
[8858]378            orxout(user_error) << "An exception occurred during upgrade to graphics. "
379                               << "That is unrecoverable. The message was:" << endl
380                               << Exception::handleMessage() << endl;
[7175]381            abort();
382        }
[5781]383
384        // Calls the InputManager which sets up the input devices.
[8423]385        inputManager_ = new InputManager();
[5781]386
[5929]387        // Load the CEGUI interface
[8423]388        guiManager_ = new GUIManager(inputManager_->getMousePosition());
[5781]389
[5929]390        bGraphicsLoaded_ = true;
391        GameMode::bShowsGraphics_s = true;
392
393        // Load some sort of a debug overlay (only denoted by its name, "debug.oxo")
394        graphicsManager_->loadDebugOverlay();
395
396        // Create singletons associated with graphics (in other libraries)
[8858]397        orxout(internal_info) << "creating graphics scope:" << endl;
[8423]398        graphicsScope_ = new Scope<ScopeID::Graphics>();
[5929]399
[5781]400        unloader.Dismiss();
[8858]401
402        orxout(internal_info) << "finished loading graphics in Core" << endl;
[5781]403    }
404
405    void Core::unloadGraphics()
406    {
[8858]407        orxout(internal_info) << "unloading graphics in Core" << endl;
408
[8423]409        safeObjectDelete(&graphicsScope_);
410        safeObjectDelete(&guiManager_);
411        safeObjectDelete(&inputManager_);
412        safeObjectDelete(&graphicsManager_);
[5781]413
414        // Load Ogre::Root again, but without the render system
415        try
[8423]416            { this->graphicsManager_ = new GraphicsManager(false); }
[5781]417        catch (...)
418        {
[8858]419            orxout(user_error) << "An exception occurred during 'unloadGraphics':" << Exception::handleMessage() << endl
420                               << "Another exception might be being handled which may lead to undefined behaviour!" << endl
421                               << "Terminating the program." << endl;
[5781]422            abort();
423        }
424
425        bGraphicsLoaded_ = false;
[5929]426        GameMode::bShowsGraphics_s = false;
[5781]427    }
428
[6417]429    //! Sets the language in the config-file back to the default.
430    void Core::resetLanguage()
[1505]431    {
[6417]432        ResetConfigValue(language_);
[1505]433    }
434
435    /**
[2896]436    @note
437        The code of this function has been copied and adjusted from OGRE, an open source graphics engine.
438            (Object-oriented Graphics Rendering Engine)
439        For the latest info, see http://www.ogre3d.org/
440
441        Copyright (c) 2000-2008 Torus Knot Software Ltd
442
443        OGRE is licensed under the LGPL. For more info, see OGRE license.
[2710]444    */
[2896]445    void Core::setThreadAffinity(int limitToCPU)
[2710]446    {
[3280]447#ifdef ORXONOX_PLATFORM_WINDOWS
448
[2896]449        if (limitToCPU <= 0)
450            return;
[2710]451
[2896]452        unsigned int coreNr = limitToCPU - 1;
453        // Get the current process core mask
454        DWORD procMask;
455        DWORD sysMask;
456#  if _MSC_VER >= 1400 && defined (_M_X64)
457        GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&procMask, (PDWORD_PTR)&sysMask);
458#  else
459        GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);
460#  endif
[2710]461
[2896]462        // If procMask is 0, consider there is only one core available
463        // (using 0 as procMask will cause an infinite loop below)
464        if (procMask == 0)
465            procMask = 1;
466
467        // if the core specified with coreNr is not available, take the lowest one
468        if (!(procMask & (1 << coreNr)))
469            coreNr = 0;
470
471        // Find the lowest core that this process uses and coreNr suggests
472        DWORD threadMask = 1;
473        while ((threadMask & procMask) == 0 || (threadMask < (1u << coreNr)))
474            threadMask <<= 1;
475
476        // Set affinity to the first core
477        SetThreadAffinityMask(GetCurrentThread(), threadMask);
478#endif
[2710]479    }
480
[5695]481    void Core::preUpdate(const Clock& time)
[2896]482    {
[6417]483        // Update singletons before general ticking
484        ScopedSingletonManager::preUpdate<ScopeID::Root>(time);
[5781]485        if (this->bGraphicsLoaded_)
486        {
[6417]487            // Process input events
488            this->inputManager_->preUpdate(time);
489            // Update GUI
490            this->guiManager_->preUpdate(time);
491            // Update singletons before general ticking
492            ScopedSingletonManager::preUpdate<ScopeID::Graphics>(time);
[5781]493        }
[6417]494        // Process console events and status line
[6746]495        if (this->ioConsole_ != NULL)
496            this->ioConsole_->preUpdate(time);
[6417]497        // Process thread commands
498        this->tclThreadManager_->preUpdate(time);
[2896]499    }
[3370]500
[5695]501    void Core::postUpdate(const Clock& time)
[3370]502    {
[6417]503        // Update singletons just before rendering
504        ScopedSingletonManager::postUpdate<ScopeID::Root>(time);
[5781]505        if (this->bGraphicsLoaded_)
506        {
[6417]507            // Update singletons just before rendering
508            ScopedSingletonManager::postUpdate<ScopeID::Graphics>(time);
[5781]509            // Render (doesn't throw)
[6417]510            this->graphicsManager_->postUpdate(time);
[5781]511        }
[3370]512    }
[7870]513
514    void Core::updateLastLevelTimestamp()
515    {
516        ModifyConfigValue(lastLevelTimestamp_, set, static_cast<long long>(time(NULL)));
517    }
518
519    void Core::updateOgreConfigTimestamp()
520    {
521        ModifyConfigValue(ogreConfigTimestamp_, set, static_cast<long long>(time(NULL)));
522    }
[8729]523
524
[10362]525    RegisterAbstractClass(DevModeListener).inheritsFrom<Listable>();
[9667]526
[8729]527    DevModeListener::DevModeListener()
528    {
[9667]529        RegisterObject(DevModeListener);
[8729]530    }
[1505]531}
Note: See TracBrowser for help on using the repository browser.