Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

Changing the Core::bDevMode_ should also change the log levels to appropriate values.
For an exact description of the behaviour, see documentation of Core::devModeChanged().

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