Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

fixed code to compile in 64bit mode

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