Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/core7/src/libraries/core/Core.cc @ 10482

Last change on this file since 10482 was 10480, checked in by landauf, 9 years ago

removed dependency of Language on CoreConfig.

  • Property svn:eol-style set to native
File size: 15.3 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 "core/singleton/Scope.h"
59#include "core/singleton/ScopedSingletonIncludes.h"
60#include "util/SignalHandler.h"
61#include "PathConfig.h"
62#include "commandline/CommandLineIncludes.h"
63#include "config/ConfigFileManager.h"
64#include "DynLibManager.h"
65#include "GameMode.h"
66#include "GraphicsManager.h"
67#include "GUIManager.h"
68#include "class/Identifier.h"
69#include "Language.h"
70#include "Loader.h"
71#include "LuaState.h"
72#include "command/ConsoleCommandManager.h"
73#include "command/IOConsole.h"
74#include "command/TclBind.h"
75#include "command/TclThreadManager.h"
76#include "input/InputManager.h"
77#include "object/ObjectList.h"
78#include "module/ModuleInstance.h"
79#include "UpdateListener.h"
80
81namespace orxonox
82{
83    //! Static pointer to the singleton
84    Core* Core::singletonPtr_s  = 0;
85
86    SetCommandLineArgument(settingsFile, "orxonox.ini").information("THE configuration file");
87#if !defined(ORXONOX_PLATFORM_APPLE) && !defined(ORXONOX_USE_WINMAIN)
88    SetCommandLineSwitch(noIOConsole).information("Use this if you don't want to use the IOConsole (for instance for Lua debugging)");
89#endif
90
91#ifdef ORXONOX_PLATFORM_WINDOWS
92    SetCommandLineArgument(limitToCPU, 0).information("Limits the program to one CPU/core (1, 2, 3, etc.). Default is off = 0.");
93#endif
94
95    Core::Core(const std::string& cmdLine)
96        : pathConfig_(NULL)
97        , dynLibManager_(NULL)
98        , signalHandler_(NULL)
99        , configFileManager_(NULL)
100        , languageInstance_(NULL)
101        , loaderInstance_(NULL)
102        , ioConsole_(NULL)
103        , tclBind_(NULL)
104        , tclThreadManager_(NULL)
105        , rootScope_(NULL)
106        , graphicsManager_(NULL)
107        , inputManager_(NULL)
108        , guiManager_(NULL)
109        , graphicsScope_(NULL)
110        , bGraphicsLoaded_(false)
111        , config_(NULL)
112        , destructionHelper_(this)
113    {
114        orxout(internal_status) << "initializing Core object..." << endl;
115
116        // Set the hard coded fixed paths
117        this->pathConfig_ = new PathConfig();
118
119        // Create a new dynamic library manager
120        this->dynLibManager_ = new DynLibManager();
121
122        // Load modules
123        orxout(internal_info) << "Loading modules:" << endl;
124        const std::vector<std::string>& modulePaths = this->pathConfig_->getModulePaths();
125        for (std::vector<std::string>::const_iterator it = modulePaths.begin(); it != modulePaths.end(); ++it)
126        {
127            try
128            {
129                this->dynLibManager_->load(*it);
130            }
131            catch (...)
132            {
133                orxout(user_error) << "Couldn't load module \"" << *it << "\": " << Exception::handleMessage() << endl;
134            }
135        }
136
137        // TODO: initialize ScopeManager here
138        // TODO: initialize CommandLineParser here
139        // TODO: initialize ConsoleCommandManager here
140        ModuleInstance::getCurrentModuleInstance()->loadAllStaticallyInitializedInstances();
141
142        // Parse command line arguments AFTER the modules have been loaded (static code!)
143        CommandLineParser::parse(cmdLine);
144
145        // Set configurable paths like log, config and media
146        this->pathConfig_->setConfigurablePaths();
147
148        orxout(internal_info) << "Root path:       " << PathConfig::getRootPathString() << endl;
149        orxout(internal_info) << "Executable path: " << PathConfig::getExecutablePathString() << endl;
150        orxout(internal_info) << "Data path:       " << PathConfig::getDataPathString() << endl;
151        orxout(internal_info) << "Ext. data path:  " << PathConfig::getExternalDataPathString() << endl;
152        orxout(internal_info) << "Config path:     " << PathConfig::getConfigPathString() << endl;
153        orxout(internal_info) << "Log path:        " << PathConfig::getLogPathString() << endl;
154        orxout(internal_info) << "Modules path:    " << PathConfig::getModulePathString() << endl;
155
156        // create a signal handler (only active for Linux)
157        // This call is placed as soon as possible, but after the directories are set
158        this->signalHandler_ = new SignalHandler();
159        this->signalHandler_->doCatch(PathConfig::getExecutablePathString(), PathConfig::getLogPathString() + "orxonox_crash.log");
160
161#ifdef ORXONOX_PLATFORM_WINDOWS
162        // limit the main thread to the first core so that QueryPerformanceCounter doesn't jump
163        // do this after ogre has initialised. Somehow Ogre changes the settings again (not through
164        // the timer though).
165        int limitToCPU = CommandLineParser::getValue("limitToCPU");
166        if (limitToCPU > 0)
167            setThreadAffinity(static_cast<unsigned int>(limitToCPU));
168#endif
169
170        // Manage ini files and set the default settings file (usually orxonox.ini)
171        orxout(internal_info) << "Loading config:" << endl;
172        this->configFileManager_ = new ConfigFileManager();
173        this->configFileManager_->setFilename(ConfigFileType::Settings,
174            CommandLineParser::getValue("settingsFile").get<std::string>());
175
176        // Required as well for the config values
177        orxout(internal_info) << "Loading language:" << endl;
178        this->languageInstance_ = new Language();
179
180        // Do this soon after the ConfigFileManager has been created to open up the
181        // possibility to configure everything below here
182        orxout(internal_info) << "configuring Core" << endl;
183        this->config_ = new CoreConfig();
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>() == false && this->config_->getStartIOConsole())
191        {
192            orxout(internal_info) << "creating IO console" << endl;
193            this->ioConsole_ = new IOConsole();
194        }
195#endif
196
197        // creates the class hierarchy for all classes with factories
198        orxout(internal_info) << "creating class hierarchy" << endl;
199        IdentifierManager::getInstance().createClassHierarchy();
200
201        // Loader
202        this->loaderInstance_ = new Loader();
203
204        // Load OGRE excluding the renderer and the render window
205        orxout(internal_info) << "creating GraphicsManager:" << endl;
206        this->graphicsManager_ = new GraphicsManager(false);
207
208        // initialise Tcl
209        this->tclBind_ = new TclBind(PathConfig::getDataPathString());
210        this->tclThreadManager_ = new TclThreadManager(tclBind_->getTclInterpreter());
211
212        // Create singletons that always exist (in other libraries)
213        orxout(internal_info) << "creating root scope:" << endl;
214        this->rootScope_ = new Scope<ScopeID::ROOT>();
215
216        // Generate documentation instead of normal run?
217        std::string docFilename;
218        CommandLineParser::getValue("generateDoc", &docFilename);
219        if (!docFilename.empty())
220        {
221            std::ofstream docFile(docFilename.c_str());
222            if (docFile.is_open())
223            {
224                CommandLineParser::generateDoc(docFile);
225                docFile.close();
226            }
227            else
228                orxout(internal_error) << "Could not open file for documentation writing" << endl;
229        }
230
231        orxout(internal_status) << "finished initializing Core object" << endl;
232    }
233
234    void Core::destroy()
235    {
236        orxout(internal_status) << "destroying Core object..." << endl;
237
238        safeObjectDelete(&graphicsScope_);
239        safeObjectDelete(&guiManager_);
240        safeObjectDelete(&inputManager_);
241        safeObjectDelete(&graphicsManager_);
242        safeObjectDelete(&rootScope_);
243        safeObjectDelete(&tclThreadManager_);
244        safeObjectDelete(&tclBind_);
245        safeObjectDelete(&ioConsole_);
246        safeObjectDelete(&loaderInstance_);
247        safeObjectDelete(&config_);
248        safeObjectDelete(&languageInstance_);
249        safeObjectDelete(&configFileManager_);
250        ConsoleCommandManager::destroyAll();
251        Context::setRootContext(NULL);
252        IdentifierManager::getInstance().destroyAllIdentifiers();
253        safeObjectDelete(&signalHandler_);
254        safeObjectDelete(&dynLibManager_);
255        safeObjectDelete(&pathConfig_);
256
257        orxout(internal_status) << "finished destroying Core object" << endl;
258    }
259
260    void Core::loadGraphics()
261    {
262        orxout(internal_info) << "loading graphics in Core" << endl;
263
264        // Any exception should trigger this, even in upgradeToGraphics (see its remarks)
265        Loki::ScopeGuard unloader = Loki::MakeObjGuard(*this, &Core::unloadGraphics);
266
267        // Upgrade OGRE to receive a render window
268        try
269        {
270            graphicsManager_->upgradeToGraphics();
271        }
272        catch (const InitialisationFailedException&)
273        {
274            // Exit the application if the Ogre config dialog was canceled
275            orxout(user_error) << Exception::handleMessage() << endl;
276            exit(EXIT_FAILURE);
277        }
278        catch (...)
279        {
280            // Recovery from this is very difficult. It requires to completely
281            // destroy Ogre related objects and load again (without graphics).
282            // However since Ogre 1.7 there seems to be a problem when Ogre
283            // throws an exception and the graphics engine then gets destroyed
284            // and reloaded between throw and catch (access violation in MSVC).
285            // That's why we abort completely and only display the exception.
286            orxout(user_error) << "An exception occurred during upgrade to graphics. "
287                               << "That is unrecoverable. The message was:" << endl
288                               << Exception::handleMessage() << endl;
289            abort();
290        }
291
292        // Calls the InputManager which sets up the input devices.
293        inputManager_ = new InputManager();
294
295        // Load the CEGUI interface
296        guiManager_ = new GUIManager(inputManager_->getMousePosition());
297
298        bGraphicsLoaded_ = true;
299        GameMode::bShowsGraphics_s = true;
300
301        // Load some sort of a debug overlay (only denoted by its name, "debug.oxo")
302        graphicsManager_->loadDebugOverlay();
303
304        // Create singletons associated with graphics (in other libraries)
305        orxout(internal_info) << "creating graphics scope:" << endl;
306        graphicsScope_ = new Scope<ScopeID::GRAPHICS>();
307
308        unloader.Dismiss();
309
310        orxout(internal_info) << "finished loading graphics in Core" << endl;
311    }
312
313    void Core::unloadGraphics()
314    {
315        orxout(internal_info) << "unloading graphics in Core" << endl;
316
317        safeObjectDelete(&graphicsScope_);
318        safeObjectDelete(&guiManager_);
319        safeObjectDelete(&inputManager_);
320        safeObjectDelete(&graphicsManager_);
321
322        // Load Ogre::Root again, but without the render system
323        try
324            { this->graphicsManager_ = new GraphicsManager(false); }
325        catch (...)
326        {
327            orxout(user_error) << "An exception occurred during 'unloadGraphics':" << Exception::handleMessage() << endl
328                               << "Another exception might be being handled which may lead to undefined behaviour!" << endl
329                               << "Terminating the program." << endl;
330            abort();
331        }
332
333        bGraphicsLoaded_ = false;
334        GameMode::bShowsGraphics_s = false;
335    }
336
337    /**
338    @note
339        The code of this function has been copied and adjusted from OGRE, an open source graphics engine.
340            (Object-oriented Graphics Rendering Engine)
341        For the latest info, see http://www.ogre3d.org/
342
343        Copyright (c) 2000-2008 Torus Knot Software Ltd
344
345        OGRE is licensed under the LGPL. For more info, see OGRE license.
346    */
347    void Core::setThreadAffinity(int limitToCPU)
348    {
349#ifdef ORXONOX_PLATFORM_WINDOWS
350
351        if (limitToCPU <= 0)
352            return;
353
354        unsigned int coreNr = limitToCPU - 1;
355        // Get the current process core mask
356        DWORD procMask;
357        DWORD sysMask;
358#  if _MSC_VER >= 1400 && defined (_M_X64)
359        GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&procMask, (PDWORD_PTR)&sysMask);
360#  else
361        GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);
362#  endif
363
364        // If procMask is 0, consider there is only one core available
365        // (using 0 as procMask will cause an infinite loop below)
366        if (procMask == 0)
367            procMask = 1;
368
369        // if the core specified with coreNr is not available, take the lowest one
370        if (!(procMask & (1 << coreNr)))
371            coreNr = 0;
372
373        // Find the lowest core that this process uses and coreNr suggests
374        DWORD threadMask = 1;
375        while ((threadMask & procMask) == 0 || (threadMask < (1u << coreNr)))
376            threadMask <<= 1;
377
378        // Set affinity to the first core
379        SetThreadAffinityMask(GetCurrentThread(), threadMask);
380#endif
381    }
382
383    void Core::preUpdate(const Clock& time)
384    {
385        // Update UpdateListeners before general ticking
386        for (ObjectList<UpdateListener>::iterator it = ObjectList<UpdateListener>::begin(); it != ObjectList<UpdateListener>::end(); ++it)
387            it->preUpdate(time);
388        if (this->bGraphicsLoaded_)
389        {
390            // Process input events
391            this->inputManager_->preUpdate(time);
392            // Update GUI
393            this->guiManager_->preUpdate(time);
394        }
395        // Process console events and status line
396        if (this->ioConsole_ != NULL)
397            this->ioConsole_->preUpdate(time);
398        // Process thread commands
399        this->tclThreadManager_->preUpdate(time);
400    }
401
402    void Core::postUpdate(const Clock& time)
403    {
404        // Update UpdateListeners just before rendering
405        for (ObjectList<UpdateListener>::iterator it = ObjectList<UpdateListener>::begin(); it != ObjectList<UpdateListener>::end(); ++it)
406            it->postUpdate(time);
407        if (this->bGraphicsLoaded_)
408        {
409            // Render (doesn't throw)
410            this->graphicsManager_->postUpdate(time);
411        }
412    }
413}
Note: See TracBrowser for help on using the repository browser.