Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

moved command line argument from Main to Core because it is used there

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