Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

made ConsoleCommandManager a singleton.

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