Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/doc/src/libraries/core/Core.cc @ 7335

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

Added separate page for a commandline argument reference.
It's not too useful, but better than nothing.

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