Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 9859 was 9667, checked in by landauf, 11 years ago

merged core6 back to trunk

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