Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/skybox2/src/libraries/core/Core.cc @ 7214

Last change on this file since 7214 was 6858, checked in by dafrick, 15 years ago

Made noCaption feature needed for skybox much nice. :D

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