Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 6105 was 6105, checked in by rgrieder, 14 years ago

Merged console branch back to trunk.

  • 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 "CommandExecutor.h"
56#include "CommandLineParser.h"
57#include "ConfigFileManager.h"
58#include "ConfigValueIncludes.h"
59#include "CoreIncludes.h"
60#include "DynLibManager.h"
61#include "GameMode.h"
62#include "GraphicsManager.h"
63#include "GUIManager.h"
64#include "Identifier.h"
65#include "Language.h"
66#include "IOConsole.h"
67#include "LuaState.h"
68#include "ScopedSingletonManager.h"
69#include "TclBind.h"
70#include "TclThreadManager.h"
71#include "input/InputManager.h"
72
73namespace orxonox
74{
75    //! Static pointer to the singleton
76    Core* Core::singletonPtr_s  = 0;
77
78    SetCommandLineArgument(settingsFile, "orxonox.ini").information("THE configuration file");
79#ifdef ORXONOX_PLATFORM_WINDOWS
80    SetCommandLineArgument(limitToCPU, 0).information("Limits the program to one cpu/core (1, 2, 3, etc.). 0 turns it off (default)");
81#endif
82
83    /**
84    @brief
85        Helper class for the Core singleton: we cannot derive
86        Core from OrxonoxClass because we need to handle the Identifier
87        destruction in the Core destructor.
88    */
89    class CoreConfiguration : public OrxonoxClass
90    {
91    public:
92        CoreConfiguration()
93        {
94        }
95
96        void initialise()
97        {
98            RegisterRootObject(CoreConfiguration);
99            this->setConfigValues();
100        }
101
102        /**
103            @brief Function to collect the SetConfigValue-macro calls.
104        */
105        void setConfigValues()
106        {
107#ifdef ORXONOX_RELEASE
108            const unsigned int defaultLevelLogFile = 3;
109#else
110            const unsigned int defaultLevelLogFile = 4;
111#endif
112            SetConfigValueGeneric(ConfigFileType::Settings, softDebugLevelLogFile_, "softDebugLevelLogFile", "OutputHandler", defaultLevelLogFile)
113                .description("The maximum level of debug output shown in the log file");
114            OutputHandler::getInstance().setSoftDebugLevel(OutputHandler::logFileOutputListenerName_s, this->softDebugLevelLogFile_);
115
116            SetConfigValue(language_, Language::getInstance().defaultLanguage_)
117                .description("The language of the in game text")
118                .callback(this, &CoreConfiguration::languageChanged);
119            SetConfigValue(bInitializeRandomNumberGenerator_, true)
120                .description("If true, all random actions are different each time you start the game")
121                .callback(this, &CoreConfiguration::initializeRandomNumberGenerator);
122        }
123
124        /**
125            @brief Callback function if the language has changed.
126        */
127        void languageChanged()
128        {
129            // Read the translation file after the language was configured
130            Language::getInstance().readTranslatedLanguageFile();
131        }
132
133        /**
134            @brief Sets the language in the config-file back to the default.
135        */
136        void resetLanguage()
137        {
138            ResetConfigValue(language_);
139        }
140
141        void initializeRandomNumberGenerator()
142        {
143            static bool bInitialized = false;
144            if (!bInitialized && this->bInitializeRandomNumberGenerator_)
145            {
146                srand(static_cast<unsigned int>(time(0)));
147                rand();
148                bInitialized = true;
149            }
150        }
151
152        int softDebugLevelLogFile_;                     //!< The debug level for the log file (belongs to OutputHandler)
153        std::string language_;                          //!< The language
154        bool bInitializeRandomNumberGenerator_;         //!< If true, srand(time(0)) is called
155    };
156
157
158    Core::Core(const std::string& cmdLine)
159        // Cleanup guard for identifier destruction (incl. XMLPort, configValues, consoleCommands)
160        : identifierDestroyer_(Identifier::destroyAllIdentifiers)
161        // Cleanup guard for external console commands that don't belong to an Identifier
162        , consoleCommandDestroyer_(CommandExecutor::destroyExternalCommands)
163        , configuration_(new CoreConfiguration()) // Don't yet create config values!
164        , bGraphicsLoaded_(false)
165    {
166        // Set the hard coded fixed paths
167        this->pathConfig_.reset(new PathConfig());
168
169        // Create a new dynamic library manager
170        this->dynLibManager_.reset(new DynLibManager());
171
172        // Load modules
173        const std::vector<std::string>& modulePaths = this->pathConfig_->getModulePaths();
174        for (std::vector<std::string>::const_iterator it = modulePaths.begin(); it != modulePaths.end(); ++it)
175        {
176            try
177            {
178                this->dynLibManager_->load(*it);
179            }
180            catch (...)
181            {
182                COUT(1) << "Couldn't load module \"" << *it << "\": " << Exception::handleMessage() << std::endl;
183            }
184        }
185
186        // Parse command line arguments AFTER the modules have been loaded (static code!)
187        CommandLineParser::parseCommandLine(cmdLine);
188
189        // Set configurable paths like log, config and media
190        this->pathConfig_->setConfigurablePaths();
191
192        // create a signal handler (only active for Linux)
193        // This call is placed as soon as possible, but after the directories are set
194        this->signalHandler_.reset(new SignalHandler());
195        this->signalHandler_->doCatch(PathConfig::getExecutablePathString(), PathConfig::getLogPathString() + "orxonox_crash.log");
196
197        // Set the correct log path. Before this call, /tmp (Unix) or %TEMP% (Windows) was used
198        OutputHandler::getInstance().setLogPath(PathConfig::getLogPathString());
199
200        // Parse additional options file now that we know its path
201        CommandLineParser::parseFile();
202
203#ifdef ORXONOX_PLATFORM_WINDOWS
204        // limit the main thread to the first core so that QueryPerformanceCounter doesn't jump
205        // do this after ogre has initialised. Somehow Ogre changes the settings again (not through
206        // the timer though).
207        int limitToCPU = CommandLineParser::getValue("limitToCPU");
208        if (limitToCPU > 0)
209            setThreadAffinity(static_cast<unsigned int>(limitToCPU));
210#endif
211
212        // Manage ini files and set the default settings file (usually orxonox.ini)
213        this->configFileManager_.reset(new ConfigFileManager());
214        this->configFileManager_->setFilename(ConfigFileType::Settings,
215            CommandLineParser::getValue("settingsFile").getString());
216
217        // Required as well for the config values
218        this->languageInstance_.reset(new Language());
219
220        // create persistent io console
221        this->ioConsole_.reset(new IOConsole());
222
223        // creates the class hierarchy for all classes with factories
224        Identifier::createClassHierarchy();
225
226        // Do this soon after the ConfigFileManager has been created to open up the
227        // possibility to configure everything below here
228        this->configuration_->initialise();
229
230        // Load OGRE excluding the renderer and the render window
231        this->graphicsManager_.reset(new GraphicsManager(false));
232
233        // initialise Tcl
234        this->tclBind_.reset(new TclBind(PathConfig::getDataPathString()));
235        this->tclThreadManager_.reset(new TclThreadManager(tclBind_->getTclInterpreter()));
236
237        // Create singletons that always exist (in other libraries)
238        this->rootScope_.reset(new Scope<ScopeID::Root>());
239    }
240
241    /**
242    @brief
243        All destruction code is handled by scoped_ptrs and ScopeGuards.
244    */
245    Core::~Core()
246    {
247    }
248
249    void Core::loadGraphics()
250    {
251        // Any exception should trigger this, even in upgradeToGraphics (see its remarks)
252        Loki::ScopeGuard unloader = Loki::MakeObjGuard(*this, &Core::unloadGraphics);
253
254        // Upgrade OGRE to receive a render window
255        graphicsManager_->upgradeToGraphics();
256
257        // Calls the InputManager which sets up the input devices.
258        inputManager_.reset(new InputManager());
259
260        // Load the CEGUI interface
261        guiManager_.reset(new GUIManager(graphicsManager_->getRenderWindow(),
262            inputManager_->getMousePosition(), graphicsManager_->isFullScreen()));
263
264        bGraphicsLoaded_ = true;
265        GameMode::bShowsGraphics_s = true;
266
267        // Load some sort of a debug overlay (only denoted by its name, "debug.oxo")
268        graphicsManager_->loadDebugOverlay();
269
270        // Create singletons associated with graphics (in other libraries)
271        graphicsScope_.reset(new Scope<ScopeID::Graphics>());
272
273        unloader.Dismiss();
274    }
275
276    void Core::unloadGraphics()
277    {
278        this->graphicsScope_.reset();
279        this->guiManager_.reset();
280        this->inputManager_.reset();
281        this->graphicsManager_.reset();
282
283        // Load Ogre::Root again, but without the render system
284        try
285            { this->graphicsManager_.reset(new GraphicsManager(false)); }
286        catch (...)
287        {
288            COUT(0) << "An exception occurred during 'unloadGraphics':" << Exception::handleMessage() << std::endl
289                    << "Another exception might be being handled which may lead to undefined behaviour!" << std::endl
290                    << "Terminating the program." << std::endl;
291            abort();
292        }
293
294        bGraphicsLoaded_ = false;
295        GameMode::bShowsGraphics_s = false;
296    }
297
298    /**
299        @brief Returns the configured language.
300    */
301    /*static*/ const std::string& Core::getLanguage()
302    {
303        return Core::getInstance().configuration_->language_;
304    }
305
306    /**
307        @brief Sets the language in the config-file back to the default.
308    */
309    /*static*/ void Core::resetLanguage()
310    {
311        Core::getInstance().configuration_->resetLanguage();
312    }
313
314    /**
315    @note
316        The code of this function has been copied and adjusted from OGRE, an open source graphics engine.
317            (Object-oriented Graphics Rendering Engine)
318        For the latest info, see http://www.ogre3d.org/
319
320        Copyright (c) 2000-2008 Torus Knot Software Ltd
321
322        OGRE is licensed under the LGPL. For more info, see OGRE license.
323    */
324    void Core::setThreadAffinity(int limitToCPU)
325    {
326#ifdef ORXONOX_PLATFORM_WINDOWS
327
328        if (limitToCPU <= 0)
329            return;
330
331        unsigned int coreNr = limitToCPU - 1;
332        // Get the current process core mask
333        DWORD procMask;
334        DWORD sysMask;
335#  if _MSC_VER >= 1400 && defined (_M_X64)
336        GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&procMask, (PDWORD_PTR)&sysMask);
337#  else
338        GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);
339#  endif
340
341        // If procMask is 0, consider there is only one core available
342        // (using 0 as procMask will cause an infinite loop below)
343        if (procMask == 0)
344            procMask = 1;
345
346        // if the core specified with coreNr is not available, take the lowest one
347        if (!(procMask & (1 << coreNr)))
348            coreNr = 0;
349
350        // Find the lowest core that this process uses and coreNr suggests
351        DWORD threadMask = 1;
352        while ((threadMask & procMask) == 0 || (threadMask < (1u << coreNr)))
353            threadMask <<= 1;
354
355        // Set affinity to the first core
356        SetThreadAffinityMask(GetCurrentThread(), threadMask);
357#endif
358    }
359
360    void Core::preUpdate(const Clock& time)
361    {
362        // singletons from other libraries
363        ScopedSingletonManager::update<ScopeID::Root>(time);
364        if (this->bGraphicsLoaded_)
365        {
366            // process input events
367            this->inputManager_->update(time);
368            // process gui events
369            this->guiManager_->update(time);
370            // graphics singletons from other libraries
371            ScopedSingletonManager::update<ScopeID::Graphics>(time);
372        }
373        // process console text
374        this->ioConsole_->update(time);
375        // process thread commands
376        this->tclThreadManager_->update(time);
377    }
378
379    void Core::postUpdate(const Clock& time)
380    {
381        if (this->bGraphicsLoaded_)
382        {
383            // Render (doesn't throw)
384            this->graphicsManager_->update(time);
385        }
386    }
387}
Note: See TracBrowser for help on using the repository browser.