Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

statically initialized instances are now registered with a type. CoreStaticInitializationHandler initializes all instances in core, NetworkStaticInitializationHandler initializes all instances in network.

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