Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/console/src/libraries/core/Core.cc @ 5994

Last change on this file since 5994 was 5994, checked in by rgrieder, 15 years ago

Changed Output concept a little bit to allow for more general use.
Every output (log) target has to be implemented as OutputListener. There is already a LogFileWriter and a MemoryLogWriter (stores ALL the log in a vector and provides iterators).
The OutputListener has a unique and constant name, a stream pointer and a soft debug level (that can only be changed via OutputHandler::setSoftDebugLevel(name, level)).
This concept doesn't require the OutputBuffer anymore, so I deleted it.

The adjustments in the Shell are just preliminary for this commit.

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