Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/unity_build/src/libraries/core/Core.cc @ 8520

Last change on this file since 8520 was 8520, checked in by rgrieder, 13 years ago

Removed useless and possibly confusion feature: specifying a file with additional command line arguments.
If we ever have too many command line arguments, then something is wrong anyway. And configuring a dedicated server should be done with config values (but a different file).
In general, always prefer config values to CommandLineArguments.

  • 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/Debug.h"
55#include "util/Exception.h"
56#include "util/Scope.h"
57#include "util/ScopedSingletonManager.h"
58#include "util/SignalHandler.h"
59#include "PathConfig.h"
60#include "CommandLineParser.h"
61#include "ConfigFileManager.h"
62#include "ConfigValueIncludes.h"
63#include "CoreIncludes.h"
64#include "DynLibManager.h"
65#include "GameMode.h"
66#include "GraphicsManager.h"
67#include "GUIManager.h"
68#include "Identifier.h"
69#include "Language.h"
70#include "LuaState.h"
71#include "command/ConsoleCommand.h"
72#include "command/IOConsole.h"
73#include "command/TclBind.h"
74#include "command/TclThreadManager.h"
75#include "input/InputManager.h"
76
77namespace orxonox
78{
79    //! Static pointer to the singleton
80    Core* Core::singletonPtr_s  = 0;
81
82    SetCommandLineArgument(settingsFile, "orxonox.ini").information("THE configuration file");
83#if !defined(ORXONOX_PLATFORM_APPLE) && !defined(ORXONOX_USE_WINMAIN)
84    SetCommandLineSwitch(noIOConsole).information("Use this if you don't want to use the IOConsole (for instance for Lua debugging)");
85#endif
86
87#ifdef ORXONOX_PLATFORM_WINDOWS
88    SetCommandLineArgument(limitToCPU, 1).information("Limits the program to one CPU/core (1, 2, 3, etc.). Default is the first core (faster than off)");
89#endif
90
91    Core::Core(const std::string& cmdLine)
92        : pathConfig_(NULL)
93        , dynLibManager_(NULL)
94        , signalHandler_(NULL)
95        , configFileManager_(NULL)
96        , languageInstance_(NULL)
97        , ioConsole_(NULL)
98        , tclBind_(NULL)
99        , tclThreadManager_(NULL)
100        , rootScope_(NULL)
101        , graphicsManager_(NULL)
102        , inputManager_(NULL)
103        , guiManager_(NULL)
104        , graphicsScope_(NULL)
105        , bGraphicsLoaded_(false)
106        , bStartIOConsole_(true)
107        , lastLevelTimestamp_(0)
108        , ogreConfigTimestamp_(0)
109        , bDevMode_(false)
110        , destructionHelper_(this)
111    {
112        // Set the hard coded fixed paths
113        this->pathConfig_ = new PathConfig();
114
115        // Create a new dynamic library manager
116        this->dynLibManager_ = new DynLibManager();
117
118        // Load modules
119        const std::vector<std::string>& modulePaths = this->pathConfig_->getModulePaths();
120        for (std::vector<std::string>::const_iterator it = modulePaths.begin(); it != modulePaths.end(); ++it)
121        {
122            try
123            {
124                this->dynLibManager_->load(*it);
125            }
126            catch (...)
127            {
128                COUT(1) << "Couldn't load module \"" << *it << "\": " << Exception::handleMessage() << std::endl;
129            }
130        }
131
132        // Parse command line arguments AFTER the modules have been loaded (static code!)
133        CommandLineParser::parse(cmdLine);
134
135        // Set configurable paths like log, config and media
136        this->pathConfig_->setConfigurablePaths();
137
138        // create a signal handler (only active for Linux)
139        // This call is placed as soon as possible, but after the directories are set
140        this->signalHandler_ = new SignalHandler();
141        this->signalHandler_->doCatch(PathConfig::getExecutablePathString(), PathConfig::getLogPathString() + "orxonox_crash.log");
142
143        // Set the correct log path. Before this call, /tmp (Unix) or %TEMP% (Windows) was used
144        OutputHandler::getInstance().setLogPath(PathConfig::getLogPathString());
145
146#ifdef ORXONOX_PLATFORM_WINDOWS
147        // limit the main thread to the first core so that QueryPerformanceCounter doesn't jump
148        // do this after ogre has initialised. Somehow Ogre changes the settings again (not through
149        // the timer though).
150        int limitToCPU = CommandLineParser::getValue("limitToCPU");
151        if (limitToCPU > 0)
152            setThreadAffinity(static_cast<unsigned int>(limitToCPU));
153#endif
154
155        // Manage ini files and set the default settings file (usually orxonox.ini)
156        this->configFileManager_ = new ConfigFileManager();
157        this->configFileManager_->setFilename(ConfigFileType::Settings,
158            CommandLineParser::getValue("settingsFile").getString());
159
160        // Required as well for the config values
161        this->languageInstance_ = new Language();
162
163        // Do this soon after the ConfigFileManager has been created to open up the
164        // possibility to configure everything below here
165        RegisterRootObject(Core);
166        this->setConfigValues();
167        // Rewrite the log file with the correct log levels
168        OutputHandler::getInstance().rewriteLogFile();
169
170#if !defined(ORXONOX_PLATFORM_APPLE) && !defined(ORXONOX_USE_WINMAIN)
171        // Create persistent IO console
172        if (CommandLineParser::getValue("noIOConsole").getBool())
173        {
174            ModifyConfigValue(bStartIOConsole_, tset, false);
175        }
176        if (this->bStartIOConsole_)
177            this->ioConsole_ = new IOConsole();
178#endif
179
180        // creates the class hierarchy for all classes with factories
181        Identifier::createClassHierarchy();
182
183        // Load OGRE excluding the renderer and the render window
184        this->graphicsManager_ = new GraphicsManager(false);
185
186        // initialise Tcl
187        this->tclBind_ = new TclBind(PathConfig::getDataPathString());
188        this->tclThreadManager_ = new TclThreadManager(tclBind_->getTclInterpreter());
189
190        // Create singletons that always exist (in other libraries)
191        this->rootScope_ = new Scope<ScopeID::Root>();
192
193        // Generate documentation instead of normal run?
194        std::string docFilename;
195        CommandLineParser::getValue("generateDoc", &docFilename);
196        if (!docFilename.empty())
197        {
198            std::ofstream docFile(docFilename.c_str());
199            if (docFile.is_open())
200            {
201                CommandLineParser::generateDoc(docFile);
202                docFile.close();
203            }
204            else
205                COUT(0) << "Error: Could not open file for documentation writing" << endl;
206        }
207    }
208
209    void Core::destroy()
210    {
211        // Remove us from the object lists again to avoid problems when destroying them
212        this->unregisterObject();
213
214        safeObjectDelete(&graphicsScope_);
215        safeObjectDelete(&guiManager_);
216        safeObjectDelete(&inputManager_);
217        safeObjectDelete(&graphicsManager_);
218        safeObjectDelete(&rootScope_);
219        safeObjectDelete(&tclThreadManager_);
220        safeObjectDelete(&tclBind_);
221        safeObjectDelete(&ioConsole_);
222        safeObjectDelete(&languageInstance_);
223        safeObjectDelete(&configFileManager_);
224        ConsoleCommand::destroyAll();
225        Identifier::destroyAllIdentifiers();
226        safeObjectDelete(&signalHandler_);
227        safeObjectDelete(&dynLibManager_);
228        safeObjectDelete(&pathConfig_);
229    }
230
231    namespace DefaultLogLevels
232    {
233        struct List
234        {
235            OutputLevel::Value logFile;
236            OutputLevel::Value ioConsole;
237            OutputLevel::Value inGameConsole;
238        };
239
240        using namespace OutputLevel;
241        static const List Dev  = { Debug, Info,  Info  };
242        static const List User = { Info,  Error, Error };
243    }
244
245    //! Function to collect the SetConfigValue-macro calls.
246    void Core::setConfigValues()
247    {
248        // Choose the default levels according to the path Orxonox was started (build directory or not)
249        DefaultLogLevels::List defaultLogLevels = (PathConfig::buildDirectoryRun() ? DefaultLogLevels::Dev : DefaultLogLevels::User);
250
251        SetConfigValueExternal(debugLevelLogFile_, "OutputHandler", "debugLevelLogFile_", defaultLogLevels.logFile)
252            .description("The maximum level of debug output written to the log file");
253        OutputHandler::getInstance().setSoftDebugLevel("LogFile", debugLevelLogFile_);
254
255        SetConfigValueExternal(debugLevelIOConsole_, "OutputHandler", "debugLevelIOConsole_", defaultLogLevels.ioConsole)
256            .description("The maximum level of debug output shown in the IO console");
257        OutputHandler::getInstance().setSoftDebugLevel("IOConsole", debugLevelIOConsole_);
258        // In case we don't start the IOConsole, also configure that simple listener
259        OutputHandler::getInstance().setSoftDebugLevel("Console", debugLevelIOConsole_);
260
261        SetConfigValueExternal(debugLevelIOConsole_, "OutputHandler", "debugLevelInGameConsole_", defaultLogLevels.inGameConsole)
262            .description("The maximum level of debug output shown in the in-game console");
263        OutputHandler::getInstance().setSoftDebugLevel("InGameConsole", debugLevelInGameConsole_);
264
265        SetConfigValue(bDevMode_, PathConfig::buildDirectoryRun())
266            .description("Developer mode. If not set, hides some things from the user to not confuse him.")
267            .callback(this, &Core::devModeChanged);
268        SetConfigValue(language_, Language::getInstance().defaultLanguage_)
269            .description("The language of the in game text")
270            .callback(this, &Core::languageChanged);
271        SetConfigValue(bInitRandomNumberGenerator_, true)
272            .description("If true, all random actions are different each time you start the game")
273            .callback(this, &Core::initRandomNumberGenerator);
274        SetConfigValue(bStartIOConsole_, true)
275            .description("Set to false if you don't want to use the IOConsole (for Lua debugging for instance)");
276        SetConfigValue(lastLevelTimestamp_, 0)
277            .description("Timestamp when the last level was started.");
278        SetConfigValue(ogreConfigTimestamp_, 0)
279            .description("Timestamp when the ogre config file was changed.");
280    }
281
282    /** Callback function for changes in the dev mode that affect debug levels.
283        The function behaves according to these rules:
284        - 'normal' mode is defined based on where the program was launched: if
285          the launch path was the build directory, development mode \c on is
286          normal, otherwise normal means development mode \c off.
287        - Debug levels should not be hard configured (\c config instead of
288          \c tconfig) in non 'normal' mode to avoid strange behaviour.
289        - Changing the development mode from 'normal' to the other state will
290          immediately change the debug levels to predefined values which can be
291          reconfigured with \c tconfig.
292    */
293    void Core::devModeChanged()
294    {
295        bool isNormal = (bDevMode_ == PathConfig::buildDirectoryRun());
296        if (isNormal)
297        {
298            ModifyConfigValue(debugLevelLogFile_,       update);
299            ModifyConfigValue(debugLevelIOConsole_,     update);
300            ModifyConfigValue(debugLevelInGameConsole_, update);
301        }
302        else
303        {
304            DefaultLogLevels::List levels = (bDevMode_ ? DefaultLogLevels::Dev : DefaultLogLevels::User);
305            ModifyConfigValue(debugLevelLogFile_,       tset, levels.logFile);
306            ModifyConfigValue(debugLevelIOConsole_,     tset, levels.ioConsole);
307            ModifyConfigValue(debugLevelInGameConsole_, tset, levels.inGameConsole);
308        }
309    }
310
311    //! Callback function if the language has changed.
312    void Core::languageChanged()
313    {
314        // Read the translation file after the language was configured
315        Language::getInstance().readTranslatedLanguageFile();
316    }
317
318    void Core::initRandomNumberGenerator()
319    {
320        static bool bInitialized = false;
321        if (!bInitialized && this->bInitRandomNumberGenerator_)
322        {
323            srand(static_cast<unsigned int>(time(0)));
324            rand();
325            bInitialized = true;
326        }
327    }
328
329    void Core::loadGraphics()
330    {
331        // Any exception should trigger this, even in upgradeToGraphics (see its remarks)
332        Loki::ScopeGuard unloader = Loki::MakeObjGuard(*this, &Core::unloadGraphics);
333
334        // Upgrade OGRE to receive a render window
335        try
336        {
337            graphicsManager_->upgradeToGraphics();
338        }
339        catch (const InitialisationFailedException&)
340        {
341            // Exit the application if the Ogre config dialog was canceled
342            COUT(1) << Exception::handleMessage() << std::endl;
343            exit(EXIT_FAILURE);
344        }
345        catch (...)
346        {
347            // Recovery from this is very difficult. It requires to completely
348            // destroy Ogre related objects and load again (without graphics).
349            // However since Ogre 1.7 there seems to be a problem when Ogre
350            // throws an exception and the graphics engine then gets destroyed
351            // and reloaded between throw and catch (access violation in MSVC).
352            // That's why we abort completely and only display the exception.
353            COUT(1) << "An exception occurred during upgrade to graphics. "
354                    << "That is unrecoverable. The message was:" << endl
355                    << Exception::handleMessage() << endl;
356            abort();
357        }
358
359        // Calls the InputManager which sets up the input devices.
360        inputManager_ = new InputManager();
361
362        // Load the CEGUI interface
363        guiManager_ = new GUIManager(inputManager_->getMousePosition());
364
365        bGraphicsLoaded_ = true;
366        GameMode::bShowsGraphics_s = true;
367
368        // Load some sort of a debug overlay (only denoted by its name, "debug.oxo")
369        graphicsManager_->loadDebugOverlay();
370
371        // Create singletons associated with graphics (in other libraries)
372        graphicsScope_ = new Scope<ScopeID::Graphics>();
373
374        unloader.Dismiss();
375    }
376
377    void Core::unloadGraphics()
378    {
379        safeObjectDelete(&graphicsScope_);
380        safeObjectDelete(&guiManager_);
381        safeObjectDelete(&inputManager_);
382        safeObjectDelete(&graphicsManager_);
383
384        // Load Ogre::Root again, but without the render system
385        try
386            { this->graphicsManager_ = new GraphicsManager(false); }
387        catch (...)
388        {
389            COUT(0) << "An exception occurred during 'unloadGraphics':" << Exception::handleMessage() << std::endl
390                    << "Another exception might be being handled which may lead to undefined behaviour!" << std::endl
391                    << "Terminating the program." << std::endl;
392            abort();
393        }
394
395        bGraphicsLoaded_ = false;
396        GameMode::bShowsGraphics_s = false;
397    }
398
399    //! Sets the language in the config-file back to the default.
400    void Core::resetLanguage()
401    {
402        ResetConfigValue(language_);
403    }
404
405    /**
406    @note
407        The code of this function has been copied and adjusted from OGRE, an open source graphics engine.
408            (Object-oriented Graphics Rendering Engine)
409        For the latest info, see http://www.ogre3d.org/
410
411        Copyright (c) 2000-2008 Torus Knot Software Ltd
412
413        OGRE is licensed under the LGPL. For more info, see OGRE license.
414    */
415    void Core::setThreadAffinity(int limitToCPU)
416    {
417#ifdef ORXONOX_PLATFORM_WINDOWS
418
419        if (limitToCPU <= 0)
420            return;
421
422        unsigned int coreNr = limitToCPU - 1;
423        // Get the current process core mask
424        DWORD procMask;
425        DWORD sysMask;
426#  if _MSC_VER >= 1400 && defined (_M_X64)
427        GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&procMask, (PDWORD_PTR)&sysMask);
428#  else
429        GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);
430#  endif
431
432        // If procMask is 0, consider there is only one core available
433        // (using 0 as procMask will cause an infinite loop below)
434        if (procMask == 0)
435            procMask = 1;
436
437        // if the core specified with coreNr is not available, take the lowest one
438        if (!(procMask & (1 << coreNr)))
439            coreNr = 0;
440
441        // Find the lowest core that this process uses and coreNr suggests
442        DWORD threadMask = 1;
443        while ((threadMask & procMask) == 0 || (threadMask < (1u << coreNr)))
444            threadMask <<= 1;
445
446        // Set affinity to the first core
447        SetThreadAffinityMask(GetCurrentThread(), threadMask);
448#endif
449    }
450
451    void Core::preUpdate(const Clock& time)
452    {
453        // Update singletons before general ticking
454        ScopedSingletonManager::preUpdate<ScopeID::Root>(time);
455        if (this->bGraphicsLoaded_)
456        {
457            // Process input events
458            this->inputManager_->preUpdate(time);
459            // Update GUI
460            this->guiManager_->preUpdate(time);
461            // Update singletons before general ticking
462            ScopedSingletonManager::preUpdate<ScopeID::Graphics>(time);
463        }
464        // Process console events and status line
465        if (this->ioConsole_ != NULL)
466            this->ioConsole_->preUpdate(time);
467        // Process thread commands
468        this->tclThreadManager_->preUpdate(time);
469    }
470
471    void Core::postUpdate(const Clock& time)
472    {
473        // Update singletons just before rendering
474        ScopedSingletonManager::postUpdate<ScopeID::Root>(time);
475        if (this->bGraphicsLoaded_)
476        {
477            // Update singletons just before rendering
478            ScopedSingletonManager::postUpdate<ScopeID::Graphics>(time);
479            // Render (doesn't throw)
480            this->graphicsManager_->postUpdate(time);
481        }
482    }
483
484    void Core::updateLastLevelTimestamp()
485    {
486        ModifyConfigValue(lastLevelTimestamp_, set, static_cast<long long>(time(NULL)));
487    }
488
489    void Core::updateOgreConfigTimestamp()
490    {
491        ModifyConfigValue(ogreConfigTimestamp_, set, static_cast<long long>(time(NULL)));
492    }
493}
Note: See TracBrowser for help on using the repository browser.