Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/gui/src/core/Core.cc @ 2846

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

Moving game clock from Core to Game.
Other small fixes.

  • Property svn:eol-style set to native
File size: 19.8 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 Implementation of the Core class.
33*/
34
35#include "Core.h"
36
37#include <cassert>
38#include <fstream>
39#include <cstdlib>
40#include <cstdio>
41#include <boost/filesystem.hpp>
42
43#ifdef ORXONOX_PLATFORM_WINDOWS
44#  ifndef WIN32_LEAN_AND_MEAN
45#    define WIN32_LEAN_AND_MEAN
46#  endif
47#  include <windows.h>
48#elif defined(ORXONOX_PLATFORM_APPLE)
49#  include <sys/param.h>
50#  include <mach-o/dyld.h>
51#else /* Linux */
52#  include <sys/types.h>
53#  include <unistd.h>
54#endif
55
56#include "SpecialConfig.h"
57#include "util/Debug.h"
58#include "util/Exception.h"
59#include "util/SignalHandler.h"
60#include "Clock.h"
61#include "CommandExecutor.h"
62#include "CommandLine.h"
63#include "ConfigFileManager.h"
64#include "ConfigValueIncludes.h"
65#include "CoreIncludes.h"
66#include "Factory.h"
67#include "Identifier.h"
68#include "Language.h"
69#include "LuaBind.h"
70#include "Shell.h"
71#include "TclBind.h"
72#include "TclThreadManager.h"
73
74namespace orxonox
75{
76    //! Path to the parent directory of the ones above if program was installed with relativ pahts
77    static boost::filesystem::path rootPath_g;
78    static boost::filesystem::path executablePath_g;            //!< Path to the executable
79    static boost::filesystem::path mediaPath_g;                 //!< Path to the media file folder
80    static boost::filesystem::path configPath_g;                //!< Path to the config file folder
81    static boost::filesystem::path logPath_g;                   //!< Path to the log file folder
82
83    bool Core::bShowsGraphics_s = false;
84    bool Core::bHasServer_s     = false;
85    bool Core::bIsClient_s      = false;
86    bool Core::bIsStandalone_s  = false;
87    bool Core::bIsMaster_s      = false;
88
89    Core* Core::singletonRef_s  = 0;
90
91    SetCommandLineArgument(mediaPath, "").information("PATH");
92    SetCommandLineArgument(writingPathSuffix, "").information("DIR");
93    SetCommandLineArgument(settingsFile, "orxonox.ini");
94    SetCommandLineArgument(limitToCPU, 0).information("0: off | #cpu");
95
96    Core::Core()
97    {
98        RegisterRootObject(Core);
99
100        assert(Core::singletonRef_s == 0);
101        Core::singletonRef_s = this;
102    }
103
104    void Core::initialise(int argc, char** argv)
105    {
106        // Parse command line arguments fist
107        try
108        {
109            CommandLine::parseAll(argc, argv);
110        }
111        catch (ArgumentException& ex)
112        {
113            COUT(1) << ex.what() << std::endl;
114            COUT(0) << "Usage:" << std::endl << "orxonox " << CommandLine::getUsageInformation() << std::endl;
115        }
116
117        // limit the main thread to the first core so that QueryPerformanceCounter doesn't jump
118        // do this after ogre has initialised. Somehow Ogre changes the settings again (not through
119        // the timer though).
120        int limitToCPU = CommandLine::getValue("limitToCPU");
121        if (limitToCPU > 0)
122            setThreadAffinity((unsigned int)limitToCPU);
123
124        // Determine and set the location of the executable
125        setExecutablePath();
126
127        // Determine whether we have an installed or a binary dir run
128        // The latter occurs when simply running from the build directory
129        checkDevBuild();
130
131        // Make sure the directories we write in exist or else make them
132        createDirectories();
133
134        // create a signal handler (only active for linux)
135        // This call is placed as soon as possible, but after the directories are set
136        this->signalHandler_ = new SignalHandler();
137        this->signalHandler_->doCatch(executablePath_g.string(), Core::getLogPathString() + "orxonox_crash.log");
138
139        // Set the correct log path. Before this call, /tmp (Unix) or %TEMP% was used
140        OutputHandler::getOutStream().setLogPath(Core::getLogPathString());
141
142        // Manage ini files and set the default settings file (usually orxonox.ini)
143        this->configFileManager_ = new ConfigFileManager();
144        this->configFileManager_->setFilename(ConfigFileType::Settings,
145            CommandLine::getValue("settingsFile").getString());
146
147        this->languageInstance_ = new Language();
148
149        // Do this soon after the ConfigFileManager has been created to open up the
150        // possibility to configure everything below here
151        this->setConfigValues();
152
153        // Possible media path override by the command line
154        if (!CommandLine::getArgument("mediaPath")->hasDefaultValue())
155        {
156            //std::string mediaPath = CommandLine::getValue("mediaPath");
157            Core::tsetMediaPath(CommandLine::getValue("mediaPath"));
158        }
159
160        // Create the lua interface
161        this->luaBind_ = new LuaBind();
162
163        // initialise Tcl
164        this->tclBind_ = new TclBind(Core::getMediaPathString());
165        this->tclThreadManager_ = new TclThreadManager(tclBind_->getTclInterpreter());
166
167        // create a shell
168        this->shell_ = new Shell();
169
170        // creates the class hierarchy for all classes with factories
171        Factory::createClassHierarchy();
172       
173        this->loaded_ = true;
174    }
175
176    /**
177        @brief Sets the bool to true to avoid static functions accessing a deleted object.
178    */
179    Core::~Core()
180    {
181        this->loaded_ = false;
182
183        delete this->shell_;
184        delete this->tclThreadManager_;
185        delete this->tclBind_;
186        delete this->luaBind_;
187        delete this->languageInstance_;
188        delete this->configFileManager_;
189        delete this->signalHandler_;
190
191        // Destroy command line arguments
192        CommandLine::destroyAllArguments();
193        // Also delete external console command that don't belong to an Identifier
194        CommandExecutor::destroyExternalCommands();
195
196        assert(Core::singletonRef_s);
197        Core::singletonRef_s = 0;
198    }
199
200    /**
201        @brief Function to collect the SetConfigValue-macro calls.
202    */
203    void Core::setConfigValues()
204    {
205#ifdef NDEBUG
206        const unsigned int defaultLevelConsole = 1;
207        const unsigned int defaultLevelLogfile = 3;
208        const unsigned int defaultLevelShell   = 1;
209#else
210        const unsigned int defaultLevelConsole = 3;
211        const unsigned int defaultLevelLogfile = 4;
212        const unsigned int defaultLevelShell   = 3;
213#endif
214        SetConfigValue(softDebugLevelConsole_, defaultLevelConsole)
215            .description("The maximal level of debug output shown in the console").callback(this, &Core::debugLevelChanged);
216        SetConfigValue(softDebugLevelLogfile_, defaultLevelLogfile)
217            .description("The maximal level of debug output shown in the logfile").callback(this, &Core::debugLevelChanged);
218        SetConfigValue(softDebugLevelShell_, defaultLevelShell)
219            .description("The maximal level of debug output shown in the ingame shell").callback(this, &Core::debugLevelChanged);
220
221        SetConfigValue(language_, Language::getLanguage().defaultLanguage_).description("The language of the ingame text").callback(this, &Core::languageChanged);
222        SetConfigValue(bInitializeRandomNumberGenerator_, true).description("If true, all random actions are different each time you start the game").callback(this, &Core::initializeRandomNumberGenerator);
223
224        SetConfigValue(mediaPathString_, mediaPath_g.string())
225            .description("Relative path to the game data.").callback(this, &Core::mediaPathChanged);
226    }
227
228    /**
229        @brief Callback function if the debug level has changed.
230    */
231    void Core::debugLevelChanged()
232    {
233        // softDebugLevel_ is the maximum of the 3 variables
234        this->softDebugLevel_ = this->softDebugLevelConsole_;
235        if (this->softDebugLevelLogfile_ > this->softDebugLevel_)
236            this->softDebugLevel_ = this->softDebugLevelLogfile_;
237        if (this->softDebugLevelShell_ > this->softDebugLevel_)
238            this->softDebugLevel_ = this->softDebugLevelShell_;
239
240        OutputHandler::setSoftDebugLevel(OutputHandler::LD_All,     this->softDebugLevel_);
241        OutputHandler::setSoftDebugLevel(OutputHandler::LD_Console, this->softDebugLevelConsole_);
242        OutputHandler::setSoftDebugLevel(OutputHandler::LD_Logfile, this->softDebugLevelLogfile_);
243        OutputHandler::setSoftDebugLevel(OutputHandler::LD_Shell,   this->softDebugLevelShell_);
244    }
245
246    /**
247        @brief Callback function if the language has changed.
248    */
249    void Core::languageChanged()
250    {
251        // Read the translation file after the language was configured
252        Language::getLanguage().readTranslatedLanguageFile();
253    }
254
255    /**
256    @brief
257        Callback function if the media path has changed.
258    */
259    void Core::mediaPathChanged()
260    {
261        mediaPath_g = boost::filesystem::path(this->mediaPathString_);
262    }
263
264    /**
265        @brief Returns the softDebugLevel for the given device (returns a default-value if the class ist right about to be created).
266        @param device The device
267        @return The softDebugLevel
268    */
269    int Core::getSoftDebugLevel(OutputHandler::OutputDevice device)
270    {
271        switch (device)
272        {
273        case OutputHandler::LD_All:
274            return Core::getInstance().softDebugLevel_;
275        case OutputHandler::LD_Console:
276            return Core::getInstance().softDebugLevelConsole_;
277        case OutputHandler::LD_Logfile:
278            return Core::getInstance().softDebugLevelLogfile_;
279        case OutputHandler::LD_Shell:
280            return Core::getInstance().softDebugLevelShell_;
281        default:
282            assert(0);
283            return 2;
284        }
285    }
286
287     /**
288        @brief Sets the softDebugLevel for the given device. Please use this only temporary and restore the value afterwards, as it overrides the configured value.
289        @param device The device
290        @param level The level
291    */
292     void Core::setSoftDebugLevel(OutputHandler::OutputDevice device, int level)
293     {
294        if (device == OutputHandler::LD_All)
295            Core::getInstance().softDebugLevel_ = level;
296        else if (device == OutputHandler::LD_Console)
297            Core::getInstance().softDebugLevelConsole_ = level;
298        else if (device == OutputHandler::LD_Logfile)
299            Core::getInstance().softDebugLevelLogfile_ = level;
300        else if (device == OutputHandler::LD_Shell)
301            Core::getInstance().softDebugLevelShell_ = level;
302
303        OutputHandler::setSoftDebugLevel(device, level);
304     }
305
306    /**
307        @brief Returns the configured language.
308    */
309    const std::string& Core::getLanguage()
310    {
311        return Core::getInstance().language_;
312    }
313
314    /**
315        @brief Sets the language in the config-file back to the default.
316    */
317    void Core::resetLanguage()
318    {
319        Core::getInstance().resetLanguageIntern();
320    }
321
322    /**
323        @brief Sets the language in the config-file back to the default.
324    */
325    void Core::resetLanguageIntern()
326    {
327        ResetConfigValue(language_);
328    }
329
330    /**
331    @brief
332        Temporary sets the media path
333    @param path
334        The new media path
335    */
336    void Core::_tsetMediaPath(const std::string& path)
337    {
338        ModifyConfigValue(mediaPathString_, tset, path);
339    }
340
341    /*static*/ const boost::filesystem::path& Core::getMediaPath()
342    {
343        return mediaPath_g;
344    }
345    /*static*/ std::string Core::getMediaPathString()
346    {
347        return mediaPath_g.string() + '/';
348    }
349
350    /*static*/ const boost::filesystem::path& Core::getConfigPath()
351    {
352        return configPath_g;
353    }
354    /*static*/ std::string Core::getConfigPathString()
355    {
356        return configPath_g.string() + '/';
357    }
358
359    /*static*/ const boost::filesystem::path& Core::getLogPath()
360    {
361        return logPath_g;
362    }
363    /*static*/ std::string Core::getLogPathString()
364    {
365        return logPath_g.string() + '/';
366    }
367
368    void Core::initializeRandomNumberGenerator()
369    {
370        static bool bInitialized = false;
371        if (!bInitialized && this->bInitializeRandomNumberGenerator_)
372        {
373            srand(time(0));
374            rand();
375            bInitialized = true;
376        }
377    }
378
379
380    /**
381    @note
382        The code of this function has been copied and adjusted from OGRE, an open source graphics engine.
383            (Object-oriented Graphics Rendering Engine)
384        For the latest info, see http://www.ogre3d.org/
385
386        Copyright (c) 2000-2008 Torus Knot Software Ltd
387
388        OGRE is licensed under the LGPL. For more info, see OGRE license.
389    */
390    void Core::setThreadAffinity(int limitToCPU)
391    {
392        if (limitToCPU <= 0)
393            return;
394
395#ifdef ORXONOX_PLATFORM_WINDOWS
396        unsigned int coreNr = limitToCPU - 1;
397        // Get the current process core mask
398        DWORD procMask;
399        DWORD sysMask;
400#  if _MSC_VER >= 1400 && defined (_M_X64)
401        GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&procMask, (PDWORD_PTR)&sysMask);
402#  else
403        GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);
404#  endif
405
406        // If procMask is 0, consider there is only one core available
407        // (using 0 as procMask will cause an infinite loop below)
408        if (procMask == 0)
409            procMask = 1;
410
411        // if the core specified with coreNr is not available, take the lowest one
412        if (!(procMask & (1 << coreNr)))
413            coreNr = 0;
414
415        // Find the lowest core that this process uses and coreNr suggests
416        DWORD threadMask = 1;
417        while ((threadMask & procMask) == 0 || (threadMask < (1u << coreNr)))
418            threadMask <<= 1;
419
420        // Set affinity to the first core
421        SetThreadAffinityMask(GetCurrentThread(), threadMask);
422#endif
423    }
424
425    /**
426    @brief
427        Compares the executable path with the working directory
428    */
429    void Core::setExecutablePath()
430    {
431#ifdef ORXONOX_PLATFORM_WINDOWS
432        // get executable module
433        TCHAR buffer[1024];
434        if (GetModuleFileName(NULL, buffer, 1024) == 0)
435            ThrowException(General, "Could not retrieve executable path.");
436
437#elif defined(ORXONOX_PLATFORM_APPLE)
438        char buffer[1024];
439        unsigned long path_len = 1023;
440        if (_NSGetExecutablePath(buffer, &path_len))
441            ThrowException(General, "Could not retrieve executable path.");
442
443#else /* Linux */
444        /* written by Nicolai Haehnle <prefect_@gmx.net> */
445
446        /* Get our PID and build the name of the link in /proc */
447        char linkname[64]; /* /proc/<pid>/exe */
448        if (snprintf(linkname, sizeof(linkname), "/proc/%i/exe", getpid()) < 0)
449        {
450            /* This should only happen on large word systems. I'm not sure
451               what the proper response is here.
452               Since it really is an assert-like condition, aborting the
453               program seems to be in order. */
454            assert(false);
455        }
456
457        /* Now read the symbolic link */
458        char buffer[1024];
459        int ret;
460        ret = readlink(linkname, buffer, 1024);
461        /* In case of an error, leave the handling up to the caller */
462        if (ret == -1)
463            ThrowException(General, "Could not retrieve executable path.");
464
465        /* Ensure proper NUL termination */
466        buffer[ret] = 0;
467#endif
468
469        executablePath_g = boost::filesystem::path(buffer);
470#ifndef ORXONOX_PLATFORM_APPLE
471        executablePath_g = executablePath_g.branch_path(); // remove executable name
472#endif
473    }
474
475    /**
476    @brief
477        Checks for "orxonox_dev_build.keep_me" in the executable diretory.
478        If found it means that this is not an installed run, hence we
479        don't write the logs and config files to ~/.orxonox
480    */
481    void Core::checkDevBuild()
482    {
483        if (boost::filesystem::exists(executablePath_g / "orxonox_dev_build.keep_me"))
484        {
485            COUT(1) << "Running from the build tree." << std::endl;
486            Core::isDevBuild_ = true;
487            mediaPath_g  = ORXONOX_MEDIA_DEV_PATH;
488            configPath_g = ORXONOX_CONFIG_DEV_PATH;
489            logPath_g    = ORXONOX_LOG_DEV_PATH;
490        }
491        else
492        {
493#ifdef INSTALL_COPYABLE // --> relative paths
494            // Also set the root path
495            boost::filesystem::path relativeExecutablePath(ORXONOX_RUNTIME_INSTALL_PATH);
496            rootPath_g = executablePath_g;
497            while (!boost::filesystem::equivalent(rootPath_g / relativeExecutablePath, executablePath_g) || rootPath_g.empty())
498                rootPath_g = rootPath_g.branch_path();
499            if (rootPath_g.empty())
500                ThrowException(General, "Could not derive a root directory. Might the binary installation directory contain '..' when taken relative to the installation prefix path?");
501
502            // Using paths relative to the install prefix, complete them
503            mediaPath_g  = rootPath_g / ORXONOX_MEDIA_INSTALL_PATH;
504            configPath_g = rootPath_g / ORXONOX_CONFIG_INSTALL_PATH;
505            logPath_g    = rootPath_g / ORXONOX_LOG_INSTALL_PATH;
506#else
507            // There is no root path, so don't set it at all
508
509            mediaPath_g  = ORXONOX_MEDIA_INSTALL_PATH;
510
511            // Get user directory
512#  ifdef ORXONOX_PLATFORM_UNIX /* Apple? */
513            char* userDataPathPtr(getenv("HOME"));
514#  else
515            char* userDataPathPtr(getenv("APPDATA"));
516#  endif
517            if (userDataPathPtr == NULL)
518                ThrowException(General, "Could not retrieve user data path.");
519            boost::filesystem::path userDataPath(userDataPathPtr);
520            userDataPath /= ".orxonox";
521
522            configPath_g = userDataPath / ORXONOX_CONFIG_INSTALL_PATH;
523            logPath_g    = userDataPath / ORXONOX_LOG_INSTALL_PATH;
524#endif
525        }
526
527        // Option to put all the config and log files in a separate folder
528        if (!CommandLine::getArgument("writingPathSuffix")->hasDefaultValue())
529        {
530            std::string directory(CommandLine::getValue("writingPathSuffix").getString());
531            configPath_g = configPath_g / directory;
532            logPath_g    = logPath_g    / directory;
533        }
534    }
535
536    /*
537    @brief
538        Checks for the log and the config directory and creates them
539        if necessary. Otherwise me might have problems opening those files.
540    */
541    void Core::createDirectories()
542    {
543        std::vector<std::pair<boost::filesystem::path, std::string> > directories;
544        directories.push_back(std::pair<boost::filesystem::path, std::string>
545            (boost::filesystem::path(configPath_g), "config"));
546        directories.push_back(std::pair<boost::filesystem::path, std::string>
547            (boost::filesystem::path(logPath_g),    "log"));
548
549        for (std::vector<std::pair<boost::filesystem::path, std::string> >::iterator it = directories.begin();
550            it != directories.end(); ++it)
551        {
552            if (boost::filesystem::exists(it->first) && !boost::filesystem::is_directory(it->first))
553            {
554                ThrowException(General, std::string("The ") + it->second + " directory has been preoccupied by a file! \
555                                         Please remove " + it->first.string());
556            }
557            if (boost::filesystem::create_directories(it->first)) // function may not return true at all (bug?)
558            {
559                COUT(4) << "Created " << it->second << " directory" << std::endl;
560            }
561        }
562    }
563
564    void Core::update(const Clock& time)
565    {
566        this->tclThreadManager_->update(time);
567    }
568}
Note: See TracBrowser for help on using the repository browser.