Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/libraries/core/Core.cc @ 10782

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

merged branch core7 back to trunk

  • Property svn:eol-style set to native
File size: 18.5 KB
Line 
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
24 *      Reto Grieder
25 *   Co-authors:
26 *      ...
27 *
28 */
29
30/**
31@file
32@brief
33    Implementation of the Core singleton with its global variables (avoids boost include)
34*/
35
36#include "Core.h"
37
38#include <cassert>
39#include <cstdlib>
40#include <ctime>
41#include <fstream>
42#include <vector>
43
44#ifdef ORXONOX_PLATFORM_WINDOWS
45#  ifndef WIN32_LEAN_AND_MEAN
46#    define WIN32_LEAN_AND_MEAN
47#  endif
48#  include <windows.h>
49#  undef min
50#  undef max
51#endif
52
53#include "util/Clock.h"
54#include "util/Output.h"
55#include "util/Exception.h"
56#include "util/SignalHandler.h"
57#include "util/output/LogWriter.h"
58#include "util/output/OutputManager.h"
59#include "core/singleton/Scope.h"
60#include "ApplicationPaths.h"
61#include "ConfigurablePaths.h"
62#include "commandline/CommandLineIncludes.h"
63#include "config/ConfigFileManager.h"
64#include "GameMode.h"
65#include "GraphicsManager.h"
66#include "GUIManager.h"
67#include "Language.h"
68#include "Loader.h"
69#include "LuaState.h"
70#include "command/IOConsole.h"
71#include "command/TclBind.h"
72#include "command/TclThreadManager.h"
73#include "input/InputManager.h"
74#include "object/ObjectList.h"
75#include "module/DynLibManager.h"
76#include "module/ModuleInstance.h"
77#include "module/StaticInitializationManager.h"
78#include "module/PluginManager.h"
79#include "CoreStaticInitializationHandler.h"
80#include "UpdateListener.h"
81
82namespace orxonox
83{
84    //! Static pointer to the singleton
85    Core* Core::singletonPtr_s  = 0;
86
87    SetCommandLineArgument(settingsFile, "orxonox.ini").information("THE configuration file");
88#if !defined(ORXONOX_PLATFORM_APPLE) && !defined(ORXONOX_USE_WINMAIN)
89    SetCommandLineSwitch(noIOConsole).information("Use this if you don't want to use the IOConsole (for instance for Lua debugging)");
90#endif
91
92#ifdef ORXONOX_PLATFORM_WINDOWS
93    SetCommandLineArgument(limitToCPU, 0).information("Limits the program to one CPU/core (1, 2, 3, etc.). Default is off = 0.");
94#endif
95
96    Core::Core(const std::string& cmdLine)
97        : applicationPaths_(NULL)
98        , configurablePaths_(NULL)
99        , dynLibManager_(NULL)
100        , signalHandler_(NULL)
101        , configFileManager_(NULL)
102        , languageInstance_(NULL)
103        , loaderInstance_(NULL)
104        , ioConsole_(NULL)
105        , tclBind_(NULL)
106        , tclThreadManager_(NULL)
107        , rootScope_(NULL)
108        , graphicsManager_(NULL)
109        , inputManager_(NULL)
110        , guiManager_(NULL)
111        , graphicsScope_(NULL)
112        , bGraphicsLoaded_(false)
113        , staticInitHandler_(NULL)
114        , pluginManager_(NULL)
115        , rootModule_(NULL)
116        , config_(NULL)
117        , destructionHelper_(this)
118    {
119        orxout(internal_status) << "initializing Core object..." << endl;
120
121        // Set the hard coded fixed paths
122        this->applicationPaths_ = new ApplicationPaths();
123
124        // Create a new dynamic library manager
125        this->dynLibManager_ = new DynLibManager();
126
127        // create handler for static initialization
128        new StaticInitializationManager(); // create singleton
129        this->staticInitHandler_ = new CoreStaticInitializationHandler();
130        StaticInitializationManager::getInstance().addHandler(this->staticInitHandler_);
131
132        // load root module (all libraries which are linked to the executable, including core, network, and orxonox)
133        this->rootModule_ = ModuleInstance::getCurrentModuleInstance();
134        StaticInitializationManager::getInstance().loadModule(this->rootModule_);
135
136        // Parse command line arguments AFTER the modules have been loaded (static code!)
137        CommandLineParser::parse(cmdLine);
138
139        // Set configurable paths like log, config and media
140        this->configurablePaths_ = new ConfigurablePaths();
141        this->configurablePaths_->setConfigurablePaths(ApplicationPaths::getInstance());
142
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;
146        orxout(internal_info) << "Plugins path:    " << ApplicationPaths::getPluginPathString() << endl;
147
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
154        // This call is placed as soon as possible, but after the directories are set
155        this->signalHandler_ = new SignalHandler();
156        this->signalHandler_->doCatch(ApplicationPaths::getExecutablePathString(), ConfigurablePaths::getLogPathString() + "orxonox_crash.log");
157
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).
162        int limitToCPU = CommandLineParser::getValue("limitToCPU");
163        if (limitToCPU > 0)
164            setThreadAffinity(static_cast<unsigned int>(limitToCPU));
165#endif
166
167        // Manage ini files and set the default settings file (usually orxonox.ini)
168        orxout(internal_info) << "Loading config:" << endl;
169        this->configFileManager_ = new ConfigFileManager();
170        this->configFileManager_->setFilename(ConfigFileType::Settings,
171            CommandLineParser::getValue("settingsFile").get<std::string>());
172
173        // Required as well for the config values
174        orxout(internal_info) << "Loading language:" << endl;
175        this->languageInstance_ = new Language();
176
177        // initialize root context
178        Context::setRootContext(new Context(NULL));
179
180        // Do this soon after the ConfigFileManager has been created to open up the
181        // possibility to configure everything below here
182        orxout(internal_info) << "configuring Core" << endl;
183        this->config_ = new CoreConfig();
184
185        // Set the correct log path and rewrite the log file with the correct log levels
186        OutputManager::getInstance().getLogWriter()->setLogDirectory(ConfigurablePaths::getLogPathString());
187
188#if !defined(ORXONOX_PLATFORM_APPLE) && !defined(ORXONOX_USE_WINMAIN)
189        // Create persistent IO console
190        if (CommandLineParser::getValue("noIOConsole").get<bool>() == false && this->config_->getStartIOConsole())
191        {
192            orxout(internal_info) << "creating IO console" << endl;
193            this->ioConsole_ = new IOConsole();
194        }
195#endif
196
197        // creates the class hierarchy for all classes with factories
198        orxout(internal_info) << "creating class hierarchy" << endl;
199        this->staticInitHandler_->initInstances(this->rootModule_);
200        this->staticInitHandler_->setInitInstances(true);
201
202        // Create plugin manager and search for plugins
203        this->pluginManager_ = new PluginManager();
204        this->pluginManager_->findPlugins();
205
206        // Loader
207        this->loaderInstance_ = new Loader();
208
209        // Load OGRE excluding the renderer and the render window
210        orxout(internal_info) << "creating GraphicsManager:" << endl;
211        this->graphicsManager_ = new GraphicsManager(false);
212
213        // initialise Tcl
214        this->tclBind_ = new TclBind(ConfigurablePaths::getDataPathString());
215        this->tclThreadManager_ = new TclThreadManager(tclBind_->getTclInterpreter());
216
217        // Create singletons that always exist (in other libraries)
218        orxout(internal_info) << "creating root scope:" << endl;
219        this->rootScope_ = new Scope<ScopeID::ROOT>();
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
233                orxout(internal_error) << "Could not open file for documentation writing" << endl;
234        }
235
236        orxout(internal_status) << "finished initializing Core object" << endl;
237    }
238
239    void Core::destroy()
240    {
241        orxout(internal_status) << "destroying Core object..." << endl;
242
243        safeObjectDelete(&graphicsScope_);
244        safeObjectDelete(&guiManager_);
245        safeObjectDelete(&inputManager_);
246        safeObjectDelete(&graphicsManager_);
247        safeObjectDelete(&rootScope_);
248        safeObjectDelete(&tclThreadManager_);
249        safeObjectDelete(&tclBind_);
250        safeObjectDelete(&ioConsole_);
251        safeObjectDelete(&loaderInstance_);
252        safeObjectDelete(&config_);
253        safeObjectDelete(&languageInstance_);
254        safeObjectDelete(&configFileManager_);
255        safeObjectDelete(&signalHandler_);
256        safeObjectDelete(&pluginManager_);
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        {
260            StaticInitializationManager::getInstance().unloadModule(this->rootModule_);
261            this->rootModule_->deleteAllStaticallyInitializedInstances();
262        }
263        if (this->staticInitHandler_)
264            StaticInitializationManager::getInstance().removeHandler(this->staticInitHandler_);
265        Context::destroyRootContext();
266        safeObjectDelete(&rootModule_);
267        safeObjectDelete(&staticInitHandler_);
268        delete &StaticInitializationManager::getInstance();
269        safeObjectDelete(&dynLibManager_);
270        safeObjectDelete(&configurablePaths_);
271        safeObjectDelete(&applicationPaths_);
272
273        orxout(internal_status) << "finished destroying Core object" << endl;
274    }
275
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        {
283            ModuleInstance* module = new ModuleInstance(*it);
284            this->loadModule(module);
285            this->modules_.push_back(module);
286        }
287
288        orxout(internal_info) << "finished loading modules" << endl;
289    }
290
291    void Core::loadModule(ModuleInstance* module)
292    {
293        orxout(internal_info) << "Loading module " << module->getLibraryName() << "..." << endl;
294
295        try
296        {
297            ModuleInstance::setCurrentModuleInstance(module);
298            DynLib* dynLib = this->dynLibManager_->load(module->getLibraryName());
299            module->setDynLib(dynLib);
300
301            StaticInitializationManager::getInstance().loadModule(module);
302        }
303        catch (...)
304        {
305            orxout(user_error) << "Couldn't load module \"" << module->getLibraryName() << "\": " << Exception::handleMessage() << endl;
306        }
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    {
322        orxout(internal_info) << "Unloading module " << module->getLibraryName() << "..." << endl;
323
324        StaticInitializationManager::getInstance().unloadModule(module);
325
326        module->deleteAllStaticallyInitializedInstances();
327        this->dynLibManager_->unload(module->getDynLib());
328        module->setDynLib(NULL);
329    }
330
331    void Core::loadGraphics()
332    {
333        orxout(internal_info) << "loading graphics in Core" << endl;
334
335        // Any exception should trigger this, even in upgradeToGraphics (see its remarks)
336        Loki::ScopeGuard unloader = Loki::MakeObjGuard(*this, &Core::unloadGraphics, true);
337
338        // Upgrade OGRE to receive a render window
339        try
340        {
341            graphicsManager_->upgradeToGraphics();
342        }
343        catch (const InitialisationFailedException&)
344        {
345            // Exit the application if the Ogre config dialog was canceled
346            orxout(user_error) << Exception::handleMessage() << endl;
347            exit(EXIT_FAILURE);
348        }
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.
357            orxout(user_error) << "An exception occurred during upgrade to graphics. "
358                               << "That is unrecoverable. The message was:" << endl
359                               << Exception::handleMessage() << endl;
360            abort();
361        }
362
363        // Calls the InputManager which sets up the input devices.
364        inputManager_ = new InputManager();
365
366        // Load the CEGUI interface
367        guiManager_ = new GUIManager(inputManager_->getMousePosition());
368
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)
376        orxout(internal_info) << "creating graphics scope:" << endl;
377        graphicsScope_ = new Scope<ScopeID::GRAPHICS>();
378
379        unloader.Dismiss();
380
381        orxout(internal_info) << "finished loading graphics in Core" << endl;
382    }
383
384    void Core::unloadGraphics(bool loadGraphicsManagerWithoutRenderer)
385    {
386        orxout(internal_info) << "unloading graphics in Core" << endl;
387
388        if (this->graphicsManager_)
389            this->graphicsManager_->unloadDebugOverlay();
390
391        safeObjectDelete(&graphicsScope_);
392        safeObjectDelete(&guiManager_);
393        safeObjectDelete(&inputManager_);
394        safeObjectDelete(&graphicsManager_);
395
396        // Load Ogre::Root again, but without the render system
397        try
398        {
399            if (loadGraphicsManagerWithoutRenderer)
400                this->graphicsManager_ = new GraphicsManager(false);
401        }
402        catch (...)
403        {
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;
407            abort();
408        }
409
410        bGraphicsLoaded_ = false;
411        GameMode::bShowsGraphics_s = false;
412    }
413
414    /**
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.
423    */
424    void Core::setThreadAffinity(int limitToCPU)
425    {
426#ifdef ORXONOX_PLATFORM_WINDOWS
427
428        if (limitToCPU <= 0)
429            return;
430
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
440
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
458    }
459
460    void Core::preUpdate(const Clock& time)
461    {
462        // Update UpdateListeners before general ticking
463        for (ObjectList<UpdateListener>::iterator it = ObjectList<UpdateListener>::begin(); it != ObjectList<UpdateListener>::end(); ++it)
464            it->preUpdate(time);
465        if (this->bGraphicsLoaded_)
466        {
467            // Process input events
468            this->inputManager_->preUpdate(time);
469            // Update GUI
470            this->guiManager_->preUpdate(time);
471        }
472        // Process console events and status line
473        if (this->ioConsole_ != NULL)
474            this->ioConsole_->preUpdate(time);
475        // Process thread commands
476        this->tclThreadManager_->preUpdate(time);
477    }
478
479    void Core::postUpdate(const Clock& time)
480    {
481        // Update UpdateListeners just before rendering
482        for (ObjectList<UpdateListener>::iterator it = ObjectList<UpdateListener>::begin(); it != ObjectList<UpdateListener>::end(); ++it)
483            it->postUpdate(time);
484        if (this->bGraphicsLoaded_)
485        {
486            // Render (doesn't throw)
487            this->graphicsManager_->postUpdate(time);
488        }
489    }
490}
Note: See TracBrowser for help on using the repository browser.