Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

use CoreStaticInitializationHandler to initialize core instances

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