Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

StaticallyInitializedInstances are now responsible to delete the wrapped object.

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