Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/cpp11_v2/src/libraries/core/Core.cc @ 10990

Last change on this file since 10990 was 10919, checked in by landauf, 8 years ago

use range-based for-loop where it makes sense (e.g. ObjectList)

  • Property svn:eol-style set to native
File size: 18.3 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  = nullptr;
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_(nullptr)
98        , configurablePaths_(nullptr)
99        , dynLibManager_(nullptr)
100        , signalHandler_(nullptr)
101        , configFileManager_(nullptr)
102        , languageInstance_(nullptr)
103        , loaderInstance_(nullptr)
104        , ioConsole_(nullptr)
105        , tclBind_(nullptr)
106        , tclThreadManager_(nullptr)
107        , rootScope_(nullptr)
108        , graphicsManager_(nullptr)
109        , inputManager_(nullptr)
110        , guiManager_(nullptr)
111        , graphicsScope_(nullptr)
112        , bGraphicsLoaded_(false)
113        , staticInitHandler_(nullptr)
114        , pluginManager_(nullptr)
115        , rootModule_(nullptr)
116        , config_(nullptr)
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(nullptr));
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 (const std::string& modulePath : modulePaths)
282        {
283            ModuleInstance* module = new ModuleInstance(modulePath);
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 (ModuleInstance* module : this->modules_)
312        {
313            this->unloadModule(module);
314            delete module;
315        }
316        this->modules_.clear();
317    }
318
319    void Core::unloadModule(ModuleInstance* module)
320    {
321        orxout(internal_info) << "Unloading module " << module->getLibraryName() << "..." << endl;
322
323        StaticInitializationManager::getInstance().unloadModule(module);
324
325        module->deleteAllStaticallyInitializedInstances();
326        this->dynLibManager_->unload(module->getDynLib());
327        module->setDynLib(nullptr);
328    }
329
330    void Core::loadGraphics()
331    {
332        orxout(internal_info) << "loading graphics in Core" << endl;
333
334        // Any exception should trigger this, even in upgradeToGraphics (see its remarks)
335        Loki::ScopeGuard unloader = Loki::MakeObjGuard(*this, &Core::unloadGraphics, true);
336
337        // Upgrade OGRE to receive a render window
338        try
339        {
340            graphicsManager_->upgradeToGraphics();
341        }
342        catch (const InitialisationFailedException&)
343        {
344            // Exit the application if the Ogre config dialog was canceled
345            orxout(user_error) << Exception::handleMessage() << endl;
346            exit(EXIT_FAILURE);
347        }
348        catch (...)
349        {
350            // Recovery from this is very difficult. It requires to completely
351            // destroy Ogre related objects and load again (without graphics).
352            // However since Ogre 1.7 there seems to be a problem when Ogre
353            // throws an exception and the graphics engine then gets destroyed
354            // and reloaded between throw and catch (access violation in MSVC).
355            // That's why we abort completely and only display the exception.
356            orxout(user_error) << "An exception occurred during upgrade to graphics. "
357                               << "That is unrecoverable. The message was:" << endl
358                               << Exception::handleMessage() << endl;
359            abort();
360        }
361
362        // Calls the InputManager which sets up the input devices.
363        inputManager_ = new InputManager();
364
365        // Load the CEGUI interface
366        guiManager_ = new GUIManager(inputManager_->getMousePosition());
367
368        bGraphicsLoaded_ = true;
369        GameMode::bShowsGraphics_s = true;
370
371        // Load some sort of a debug overlay (only denoted by its name, "debug.oxo")
372        graphicsManager_->loadDebugOverlay();
373
374        // Create singletons associated with graphics (in other libraries)
375        orxout(internal_info) << "creating graphics scope:" << endl;
376        graphicsScope_ = new Scope<ScopeID::GRAPHICS>();
377
378        unloader.Dismiss();
379
380        orxout(internal_info) << "finished loading graphics in Core" << endl;
381    }
382
383    void Core::unloadGraphics(bool loadGraphicsManagerWithoutRenderer)
384    {
385        orxout(internal_info) << "unloading graphics in Core" << endl;
386
387        if (this->graphicsManager_)
388            this->graphicsManager_->unloadDebugOverlay();
389
390        safeObjectDelete(&graphicsScope_);
391        safeObjectDelete(&guiManager_);
392        safeObjectDelete(&inputManager_);
393        safeObjectDelete(&graphicsManager_);
394
395        // Load Ogre::Root again, but without the render system
396        try
397        {
398            if (loadGraphicsManagerWithoutRenderer)
399                this->graphicsManager_ = new GraphicsManager(false);
400        }
401        catch (...)
402        {
403            orxout(user_error) << "An exception occurred during 'unloadGraphics':" << Exception::handleMessage() << endl
404                               << "Another exception might be being handled which may lead to undefined behaviour!" << endl
405                               << "Terminating the program." << endl;
406            abort();
407        }
408
409        bGraphicsLoaded_ = false;
410        GameMode::bShowsGraphics_s = false;
411    }
412
413    /**
414    @note
415        The code of this function has been copied and adjusted from OGRE, an open source graphics engine.
416            (Object-oriented Graphics Rendering Engine)
417        For the latest info, see http://www.ogre3d.org/
418
419        Copyright (c) 2000-2008 Torus Knot Software Ltd
420
421        OGRE is licensed under the LGPL. For more info, see OGRE license.
422    */
423    void Core::setThreadAffinity(int limitToCPU)
424    {
425#ifdef ORXONOX_PLATFORM_WINDOWS
426
427        if (limitToCPU <= 0)
428            return;
429
430        unsigned int coreNr = limitToCPU - 1;
431        // Get the current process core mask
432        DWORD procMask;
433        DWORD sysMask;
434#  if _MSC_VER >= 1400 && defined (_M_X64)
435        GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&procMask, (PDWORD_PTR)&sysMask);
436#  else
437        GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);
438#  endif
439
440        // If procMask is 0, consider there is only one core available
441        // (using 0 as procMask will cause an infinite loop below)
442        if (procMask == 0)
443            procMask = 1;
444
445        // if the core specified with coreNr is not available, take the lowest one
446        if (!(procMask & (1 << coreNr)))
447            coreNr = 0;
448
449        // Find the lowest core that this process uses and coreNr suggests
450        DWORD threadMask = 1;
451        while ((threadMask & procMask) == 0 || (threadMask < (1u << coreNr)))
452            threadMask <<= 1;
453
454        // Set affinity to the first core
455        SetThreadAffinityMask(GetCurrentThread(), threadMask);
456#endif
457    }
458
459    void Core::preUpdate(const Clock& time)
460    {
461        // Update UpdateListeners before general ticking
462        for (UpdateListener* listener : ObjectList<UpdateListener>())
463            listener->preUpdate(time);
464        if (this->bGraphicsLoaded_)
465        {
466            // Process input events
467            this->inputManager_->preUpdate(time);
468            // Update GUI
469            this->guiManager_->preUpdate(time);
470        }
471        // Process console events and status line
472        if (this->ioConsole_ != nullptr)
473            this->ioConsole_->preUpdate(time);
474        // Process thread commands
475        this->tclThreadManager_->preUpdate(time);
476    }
477
478    void Core::postUpdate(const Clock& time)
479    {
480        // Update UpdateListeners just before rendering
481        for (UpdateListener* listener : ObjectList<UpdateListener>())
482            listener->postUpdate(time);
483        if (this->bGraphicsLoaded_)
484        {
485            // Render (doesn't throw)
486            this->graphicsManager_->postUpdate(time);
487        }
488    }
489}
Note: See TracBrowser for help on using the repository browser.