Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

added draft for StaticInitializationHandler

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