Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/core4/src/core/Core.cc @ 3246

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

Added new feature to CommandLine: arguments that cannot be specified in a file.
—optionsFile and —writingPathSuffix are now such arguments (because of obvious dependency problems).

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