Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: sandbox/src/libraries/core/Core.cc @ 6497

Last change on this file since 6497 was 6038, checked in by rgrieder, 15 years ago

Synchronised sandbox with current code trunk. There should be a few bug fixes.

  • Property svn:eol-style set to native
File size: 13.2 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 <vector>
40
41#ifdef ORXONOX_PLATFORM_WINDOWS
42#  ifndef WIN32_LEAN_AND_MEAN
43#    define WIN32_LEAN_AND_MEAN
44#  endif
45#  include <windows.h>
46#  undef min
47#  undef max
48#endif
49
50#include "util/Clock.h"
51#include "util/Debug.h"
52#include "util/Exception.h"
53#include "util/SignalHandler.h"
54#include "PathConfig.h"
55#include "CommandLineParser.h"
56#include "ConfigFileManager.h"
57#include "ConfigValueIncludes.h"
58#include "CoreIncludes.h"
59#include "DynLibManager.h"
60#include "Identifier.h"
61#include "Language.h"
62#include "LuaState.h"
63
64namespace orxonox
65{
66    //! Static pointer to the singleton
67    Core* Core::singletonPtr_s  = 0;
68
69    SetCommandLineArgument(settingsFile, "orxonox.ini").information("THE configuration file");
70#ifdef ORXONOX_PLATFORM_WINDOWS
71    SetCommandLineArgument(limitToCPU, 0).information("Limits the program to one cpu/core (1, 2, 3, etc.). 0 turns it off (default)");
72#endif
73
74    /**
75    @brief
76        Helper class for the Core singleton: we cannot derive
77        Core from OrxonoxClass because we need to handle the Identifier
78        destruction in the Core destructor.
79    */
80    class CoreConfiguration : public OrxonoxClass
81    {
82    public:
83        CoreConfiguration()
84        {
85        }
86
87        void initialise()
88        {
89            RegisterRootObject(CoreConfiguration);
90            this->setConfigValues();
91        }
92
93        /**
94            @brief Function to collect the SetConfigValue-macro calls.
95        */
96        void setConfigValues()
97        {
98#ifdef NDEBUG
99            const unsigned int defaultLevelConsole = 1;
100            const unsigned int defaultLevelLogfile = 3;
101            const unsigned int defaultLevelShell   = 1;
102#else
103            const unsigned int defaultLevelConsole = 3;
104            const unsigned int defaultLevelLogfile = 4;
105            const unsigned int defaultLevelShell   = 3;
106#endif
107            SetConfigValue(softDebugLevelConsole_, defaultLevelConsole)
108                .description("The maximal level of debug output shown in the console")
109                .callback(this, &CoreConfiguration::debugLevelChanged);
110            SetConfigValue(softDebugLevelLogfile_, defaultLevelLogfile)
111                .description("The maximal level of debug output shown in the logfile")
112                .callback(this, &CoreConfiguration::debugLevelChanged);
113            SetConfigValue(softDebugLevelShell_, defaultLevelShell)
114                .description("The maximal level of debug output shown in the ingame shell")
115                .callback(this, &CoreConfiguration::debugLevelChanged);
116
117            SetConfigValue(language_, Language::getInstance().defaultLanguage_)
118                .description("The language of the ingame text")
119                .callback(this, &CoreConfiguration::languageChanged);
120            SetConfigValue(bInitializeRandomNumberGenerator_, true)
121                .description("If true, all random actions are different each time you start the game")
122                .callback(this, &CoreConfiguration::initializeRandomNumberGenerator);
123        }
124
125        /**
126            @brief Callback function if the debug level has changed.
127        */
128        void debugLevelChanged()
129        {
130            // softDebugLevel_ is the maximum of the 3 variables
131            this->softDebugLevel_ = this->softDebugLevelConsole_;
132            if (this->softDebugLevelLogfile_ > this->softDebugLevel_)
133                this->softDebugLevel_ = this->softDebugLevelLogfile_;
134            if (this->softDebugLevelShell_ > this->softDebugLevel_)
135                this->softDebugLevel_ = this->softDebugLevelShell_;
136
137            OutputHandler::setSoftDebugLevel(OutputHandler::LD_All,     this->softDebugLevel_);
138            OutputHandler::setSoftDebugLevel(OutputHandler::LD_Console, this->softDebugLevelConsole_);
139            OutputHandler::setSoftDebugLevel(OutputHandler::LD_Logfile, this->softDebugLevelLogfile_);
140            OutputHandler::setSoftDebugLevel(OutputHandler::LD_Shell,   this->softDebugLevelShell_);
141        }
142
143        /**
144            @brief Callback function if the language has changed.
145        */
146        void languageChanged()
147        {
148            // Read the translation file after the language was configured
149            Language::getInstance().readTranslatedLanguageFile();
150        }
151
152        /**
153            @brief Sets the language in the config-file back to the default.
154        */
155        void resetLanguage()
156        {
157            ResetConfigValue(language_);
158        }
159
160        void initializeRandomNumberGenerator()
161        {
162            static bool bInitialized = false;
163            if (!bInitialized && this->bInitializeRandomNumberGenerator_)
164            {
165                srand(static_cast<unsigned int>(time(0)));
166                rand();
167                bInitialized = true;
168            }
169        }
170
171        int softDebugLevel_;                            //!< The debug level
172        int softDebugLevelConsole_;                     //!< The debug level for the console
173        int softDebugLevelLogfile_;                     //!< The debug level for the logfile
174        int softDebugLevelShell_;                       //!< The debug level for the ingame shell
175        std::string language_;                          //!< The language
176        bool bInitializeRandomNumberGenerator_;         //!< If true, srand(time(0)) is called
177    };
178
179
180    Core::Core(const std::string& cmdLine)
181        // Cleanup guard for identifier destruction (incl. XMLPort, configValues, consoleCommands)
182        : identifierDestroyer_(Identifier::destroyAllIdentifiers)
183        , configuration_(new CoreConfiguration()) // Don't yet create config values!
184    {
185        // Set the hard coded fixed paths
186        this->pathConfig_.reset(new PathConfig());
187
188        // Create a new dynamic library manager
189        this->dynLibManager_.reset(new DynLibManager());
190
191        // Load modules
192        const std::vector<std::string>& modulePaths = this->pathConfig_->getModulePaths();
193        for (std::vector<std::string>::const_iterator it = modulePaths.begin(); it != modulePaths.end(); ++it)
194        {
195            try
196            {
197                this->dynLibManager_->load(*it);
198            }
199            catch (...)
200            {
201                COUT(1) << "Couldn't load module \"" << *it << "\": " << Exception::handleMessage() << std::endl;
202            }
203        }
204
205        // Parse command line arguments AFTER the modules have been loaded (static code!)
206        CommandLineParser::parseCommandLine(cmdLine);
207
208        // Set configurable paths like log, config and media
209        this->pathConfig_->setConfigurablePaths();
210
211        // create a signal handler (only active for linux)
212        // This call is placed as soon as possible, but after the directories are set
213        this->signalHandler_.reset(new SignalHandler());
214        this->signalHandler_->doCatch(PathConfig::getExecutablePathString(), PathConfig::getLogPathString() + "orxonox_crash.log");
215
216        // Set the correct log path. Before this call, /tmp (Unix) or %TEMP% was used
217        OutputHandler::getOutStream().setLogPath(PathConfig::getLogPathString());
218
219        // Parse additional options file now that we know its path
220        CommandLineParser::parseFile();
221
222#ifdef ORXONOX_PLATFORM_WINDOWS
223        // limit the main thread to the first core so that QueryPerformanceCounter doesn't jump
224        // do this after ogre has initialised. Somehow Ogre changes the settings again (not through
225        // the timer though).
226        int limitToCPU = CommandLineParser::getValue("limitToCPU");
227        if (limitToCPU > 0)
228            setThreadAffinity(static_cast<unsigned int>(limitToCPU));
229#endif
230
231        // Manage ini files and set the default settings file (usually orxonox.ini)
232        this->configFileManager_.reset(new ConfigFileManager());
233        this->configFileManager_->setFilename(ConfigFileType::Settings,
234            CommandLineParser::getValue("settingsFile").getString());
235
236        // Required as well for the config values
237        this->languageInstance_.reset(new Language());
238
239        // creates the class hierarchy for all classes with factories
240        Identifier::createClassHierarchy();
241
242        // Do this soon after the ConfigFileManager has been created to open up the
243        // possibility to configure everything below here
244        this->configuration_->initialise();
245    }
246
247    /**
248    @brief
249        All destruction code is handled by scoped_ptrs and ScopeGuards.
250    */
251    Core::~Core()
252    {
253    }
254
255    /**
256        @brief Returns the softDebugLevel for the given device (returns a default-value if the class is right about to be created).
257        @param device The device
258        @return The softDebugLevel
259    */
260    /*static*/ int Core::getSoftDebugLevel(OutputHandler::OutputDevice device)
261    {
262        switch (device)
263        {
264        case OutputHandler::LD_All:
265            return Core::getInstance().configuration_->softDebugLevel_;
266        case OutputHandler::LD_Console:
267            return Core::getInstance().configuration_->softDebugLevelConsole_;
268        case OutputHandler::LD_Logfile:
269            return Core::getInstance().configuration_->softDebugLevelLogfile_;
270        case OutputHandler::LD_Shell:
271            return Core::getInstance().configuration_->softDebugLevelShell_;
272        default:
273            assert(0);
274            return 2;
275        }
276    }
277
278     /**
279        @brief Sets the softDebugLevel for the given device. Please use this only temporary and restore the value afterwards, as it overrides the configured value.
280        @param device The device
281        @param level The level
282    */
283    /*static*/ void Core::setSoftDebugLevel(OutputHandler::OutputDevice device, int level)
284    {
285        if (device == OutputHandler::LD_All)
286            Core::getInstance().configuration_->softDebugLevel_ = level;
287        else if (device == OutputHandler::LD_Console)
288            Core::getInstance().configuration_->softDebugLevelConsole_ = level;
289        else if (device == OutputHandler::LD_Logfile)
290            Core::getInstance().configuration_->softDebugLevelLogfile_ = level;
291        else if (device == OutputHandler::LD_Shell)
292            Core::getInstance().configuration_->softDebugLevelShell_ = level;
293
294        OutputHandler::setSoftDebugLevel(device, level);
295    }
296
297    /**
298        @brief Returns the configured language.
299    */
300    /*static*/ const std::string& Core::getLanguage()
301    {
302        return Core::getInstance().configuration_->language_;
303    }
304
305    /**
306        @brief Sets the language in the config-file back to the default.
307    */
308    /*static*/ void Core::resetLanguage()
309    {
310        Core::getInstance().configuration_->resetLanguage();
311    }
312
313    /**
314    @note
315        The code of this function has been copied and adjusted from OGRE, an open source graphics engine.
316            (Object-oriented Graphics Rendering Engine)
317        For the latest info, see http://www.ogre3d.org/
318
319        Copyright (c) 2000-2008 Torus Knot Software Ltd
320
321        OGRE is licensed under the LGPL. For more info, see OGRE license.
322    */
323    void Core::setThreadAffinity(int limitToCPU)
324    {
325#ifdef ORXONOX_PLATFORM_WINDOWS
326
327        if (limitToCPU <= 0)
328            return;
329
330        unsigned int coreNr = limitToCPU - 1;
331        // Get the current process core mask
332        DWORD procMask;
333        DWORD sysMask;
334#  if _MSC_VER >= 1400 && defined (_M_X64)
335        GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&procMask, (PDWORD_PTR)&sysMask);
336#  else
337        GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);
338#  endif
339
340        // If procMask is 0, consider there is only one core available
341        // (using 0 as procMask will cause an infinite loop below)
342        if (procMask == 0)
343            procMask = 1;
344
345        // if the core specified with coreNr is not available, take the lowest one
346        if (!(procMask & (1 << coreNr)))
347            coreNr = 0;
348
349        // Find the lowest core that this process uses and coreNr suggests
350        DWORD threadMask = 1;
351        while ((threadMask & procMask) == 0 || (threadMask < (1u << coreNr)))
352            threadMask <<= 1;
353
354        // Set affinity to the first core
355        SetThreadAffinityMask(GetCurrentThread(), threadMask);
356#endif
357    }
358
359    void Core::preUpdate(const Clock& time)
360    {
361    }
362
363    void Core::postUpdate(const Clock& time)
364    {
365    }
366}
Note: See TracBrowser for help on using the repository browser.