Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

Changeset 5695 for code/trunk/src/core


Ignore:
Timestamp:
Aug 30, 2009, 2:22:00 AM (15 years ago)
Author:
rgrieder
Message:

Merged resource2 branch back to trunk.

IMPORTANT NOTE:
Upon this merge you need to specifically call your data directory "data_extern" when checking it out (when you don't provide a name, it will be just called 'trunk').
The new CMake variable is EXTERNAL_DATA_DIRECTORY. DATA_DIRECTORY now points to the one the source part of the repository.
UPDATE YOUR DATA DIRECTORY AS WELL!!!

Location:
code/trunk
Files:
2 deleted
31 edited
7 copied

Legend:

Unmodified
Added
Removed
  • code/trunk

  • code/trunk/src/core/CMakeLists.txt

    r5693 r5695  
    3232  GUIManager.cc
    3333  Language.cc
    34   LuaBind.cc
     34  LuaState.cc
     35  MemoryArchive.cc
    3536  ObjectListBase.cc
    3637  OrxonoxClass.cc
     38  Resource.cc
    3739  WindowEventListener.cc
    3840
     
    7779  TOLUA_FILES
    7880    CommandExecutor.h
    79     LuaBind.h
     81    Loader.h
     82    LuaState.h
    8083  DEFINE_SYMBOL
    8184    "CORE_SHARED_BUILD"
  • code/trunk/src/core/Clock.h

    r3370 r5695  
    2121 *
    2222 *   Author:
    23  *      Fabian 'x3n' Landau
     23 *      Reto Grieder
    2424 *   Co-authors:
    25  *      Reto Grieder
     25 *      ...
    2626 *
    2727 */
  • code/trunk/src/core/ConfigFileManager.cc

    r3370 r5695  
    4040namespace orxonox
    4141{
    42     const char* const DEFAULT_CONFIG_FILE = "default.ini";
    43 
    44     ConfigFileManager* ConfigFileManager::singletonPtr_s = 0;
    45 
    4642    SetConsoleCommandShortcutExtern(config).argumentCompleter(0, autocompletion::configvalueclasses()).argumentCompleter(1, autocompletion::configvalues()).argumentCompleter(2, autocompletion::configvalue());
    4743    SetConsoleCommandShortcutExtern(tconfig).argumentCompleter(0, autocompletion::configvalueclasses()).argumentCompleter(1, autocompletion::configvalues()).argumentCompleter(2, autocompletion::configvalue());
     
    229225        if (!boost::filesystem::exists(filepath))
    230226        {
    231             // Try to get default one from the media folder
    232             boost::filesystem::path defaultFilepath(Core::getMediaPath() / "defaultConfig" / this->filename_);
     227            // Try to get default one from the data folder
     228            boost::filesystem::path defaultFilepath(Core::getDataPath() / "defaultConfig" / this->filename_);
    233229            if (boost::filesystem::exists(defaultFilepath))
    234230            {
     
    339335    void ConfigFile::save() const
    340336    {
    341         boost::filesystem::path filepath(Core::getConfigPath() / this->filename_);
    342 
    343337        std::ofstream file;
    344         file.open(filepath.string().c_str(), std::fstream::out);
     338        file.open((Core::getConfigPathString() + filename_).c_str(), std::fstream::out);
    345339        file.setf(std::ios::fixed, std::ios::floatfield);
    346340        file.precision(6);
     
    479473    ///////////////////////
    480474
     475    ConfigFileManager* ConfigFileManager::singletonPtr_s = 0;
     476
     477    std::string ConfigFileManager::DEFAULT_CONFIG_FILE = "default.ini";
     478
    481479    ConfigFileManager::ConfigFileManager()
    482480         : mininmalFreeType_(ConfigFileType::numberOfReservedTypes)
  • code/trunk/src/core/ConfigFileManager.h

    r3370 r5695  
    307307            void updateConfigValues(ConfigFileType type);
    308308
     309            static std::string DEFAULT_CONFIG_FILE;
     310
    309311        private:
    310312            ConfigFileManager(const ConfigFileManager&);
  • code/trunk/src/core/ConfigValueContainer.h

    r3301 r5695  
    3131    @brief Definition of the ConfigValueContainer class.
    3232
    33     The ConfigValueContainer class contains all needed informations about a configurable variable:
     33    The ConfigValueContainer class contains all needed information about a configurable variable:
    3434     - the name of the variable
    3535     - the name of the class the variable belongs to
     
    7979
    8080
    81     //! The ConfigValuecontainer contains all needed informations about a configurable variable.
     81    //! The ConfigValuecontainer contains all needed information about a configurable variable.
    8282    /**
    83         The ConfigValueContainer class contains all needed informations about a configurable variable:
     83        The ConfigValueContainer class contains all needed information about a configurable variable:
    8484         - the name of the variable
    8585         - the name of the class the variable belongs to
  • code/trunk/src/core/Core.cc

    r5693 r5695  
    4242#include <boost/version.hpp>
    4343#include <boost/filesystem.hpp>
    44 #include <OgreRenderWindow.h>
    4544
    4645#ifdef ORXONOX_PLATFORM_WINDOWS
     
    7675#include "Identifier.h"
    7776#include "Language.h"
    78 #include "LuaBind.h"
     77#include "LuaState.h"
    7978#include "Shell.h"
    8079#include "TclBind.h"
     
    9493    Core* Core::singletonPtr_s  = 0;
    9594
    96     SetCommandLineArgument(mediaPath, "").information("Path to the media/data files");
     95    SetCommandLineArgument(externalDataPath, "").information("Path to the external data files");
    9796    SetCommandLineOnlyArgument(writingPathSuffix, "").information("Additional subfolder for config and log files");
    9897    SetCommandLineArgument(settingsFile, "orxonox.ini").information("THE configuration file");
     
    119118            this->setConfigValues();
    120119
    121             // Possible media path override by the command line
    122             if (!CommandLine::getArgument("mediaPath")->hasDefaultValue())
    123                 tsetMediaPath(CommandLine::getValue("mediaPath"));
     120            // External data directory only exists for dev runs
     121            if (Core::isDevelopmentRun())
     122            {
     123                // Possible data path override by the command line
     124                if (!CommandLine::getArgument("externalDataPath")->hasDefaultValue())
     125                    tsetExternalDataPath(CommandLine::getValue("externalDataPath"));
     126            }
    124127        }
    125128
     
    154157                .description("If true, all random actions are different each time you start the game")
    155158                .callback(this, &CoreConfiguration::initializeRandomNumberGenerator);
    156 
    157             // Only show this config value for development builds
    158             if (Core::isDevelopmentRun())
    159             {
    160                 SetConfigValue(mediaPathString_, mediaPath_.string())
    161                     .description("Relative path to the game data.")
    162                     .callback(this, &CoreConfiguration::mediaPathChanged);
    163             }
    164159        }
    165160
     
    192187
    193188        /**
    194         @brief
    195             Callback function if the media path has changed.
    196         */
    197         void mediaPathChanged()
    198         {
    199             mediaPath_ = boost::filesystem::path(this->mediaPathString_);
    200         }
    201 
    202         /**
    203189            @brief Sets the language in the config-file back to the default.
    204190        */
     
    210196        /**
    211197        @brief
    212             Temporary sets the media path
     198            Temporary sets the data path
    213199        @param path
    214             The new media path
     200            The new data path
    215201        */
    216         void tsetMediaPath(const std::string& path)
    217         {
    218             if (Core::isDevelopmentRun())
    219             {
    220                 ModifyConfigValue(mediaPathString_, tset, path);
    221             }
    222             else
    223             {
    224                 // Manual 'config' value without the file entry
    225                 mediaPathString_ = path;
    226                 this->mediaPathChanged();
    227             }
     202        void tsetExternalDataPath(const std::string& path)
     203        {
     204            dataPath_ = boost::filesystem::path(path);
    228205        }
    229206
     
    245222        std::string language_;                          //!< The language
    246223        bool bInitializeRandomNumberGenerator_;         //!< If true, srand(time(0)) is called
    247         std::string mediaPathString_;                   //!< Path to the data/media file folder as string
    248224
    249225        //! Path to the parent directory of the ones above if program was installed with relativ pahts
     
    251227        boost::filesystem::path executablePath_;        //!< Path to the executable
    252228        boost::filesystem::path modulePath_;            //!< Path to the modules
    253         boost::filesystem::path mediaPath_;             //!< Path to the media file folder
     229        boost::filesystem::path dataPath_;              //!< Path to the data file folder
     230        boost::filesystem::path externalDataPath_;      //!< Path to the external data file folder
    254231        boost::filesystem::path configPath_;            //!< Path to the config file folder
    255232        boost::filesystem::path logPath_;               //!< Path to the log file folder
     
    276253        {
    277254            // We search for helper files with the following extension
    278             std::string moduleextension = ORXONOX_MODULE_EXTENSION;
     255            std::string moduleextension = specialConfig::moduleExtension;
    279256            size_t moduleextensionlength = moduleextension.size();
    280257
     
    364341        this->languageInstance_.reset(new Language());
    365342
     343        // creates the class hierarchy for all classes with factories
     344        Factory::createClassHierarchy();
     345
    366346        // Do this soon after the ConfigFileManager has been created to open up the
    367347        // possibility to configure everything below here
    368348        this->configuration_->initialise();
    369349
    370         // Create the lua interface
    371         this->luaBind_.reset(new LuaBind());
     350        // Load OGRE excluding the renderer and the render window
     351        this->graphicsManager_.reset(new GraphicsManager(false));
    372352
    373353        // initialise Tcl
    374         this->tclBind_.reset(new TclBind(Core::getMediaPathString()));
     354        this->tclBind_.reset(new TclBind(Core::getDataPathString()));
    375355        this->tclThreadManager_.reset(new TclThreadManager(tclBind_->getTclInterpreter()));
    376356
    377357        // create a shell
    378358        this->shell_.reset(new Shell());
    379 
    380         // creates the class hierarchy for all classes with factories
    381         Factory::createClassHierarchy();
    382359    }
    383360
    384361    /**
    385362    @brief
    386         All destruction code is handled by scoped_ptrs and SimpleScopeGuards.
     363        All destruction code is handled by scoped_ptrs and ScopeGuards.
    387364    */
    388365    Core::~Core()
     
    392369    void Core::loadGraphics()
    393370    {
    394         if (bGraphicsLoaded_)
    395             return;
    396 
    397         // Load OGRE including the render window
    398         scoped_ptr<GraphicsManager> graphicsManager(new GraphicsManager());
    399 
    400         // The render window width and height are used to set up the mouse movement.
    401         size_t windowHnd = 0;
    402         graphicsManager->getRenderWindow()->getCustomAttribute("WINDOW", &windowHnd);
     371        // Any exception should trigger this, even in upgradeToGraphics (see its remarks)
     372        Loki::ScopeGuard unloader = Loki::MakeObjGuard(*this, &Core::unloadGraphics);
     373
     374        // Upgrade OGRE to receive a render window
     375        graphicsManager_->upgradeToGraphics();
    403376
    404377        // Calls the InputManager which sets up the input devices.
    405         scoped_ptr<InputManager> inputManager(new InputManager(windowHnd));
     378        inputManager_.reset(new InputManager());
    406379
    407380        // load the CEGUI interface
    408         guiManager_.reset(new GUIManager(graphicsManager->getRenderWindow()));
    409 
    410         // Dismiss scoped pointers
    411         graphicsManager_.swap(graphicsManager);
    412         inputManager_.swap(inputManager);
     381        guiManager_.reset(new GUIManager(graphicsManager_->getRenderWindow(),
     382            inputManager_->getMousePosition(), graphicsManager_->isFullScreen()));
     383
     384        unloader.Dismiss();
    413385
    414386        bGraphicsLoaded_ = true;
     
    417389    void Core::unloadGraphics()
    418390    {
    419         if (!bGraphicsLoaded_)
    420             return;
    421 
    422391        this->guiManager_.reset();;
    423392        this->inputManager_.reset();;
    424393        this->graphicsManager_.reset();
     394
     395        // Load Ogre::Root again, but without the render system
     396        try
     397            { this->graphicsManager_.reset(new GraphicsManager(false)); }
     398        catch (...)
     399        {
     400            COUT(0) << "An exception occurred during 'new GraphicsManager' while "
     401                    << "another exception was being handled. This will lead to undefined behaviour!" << std::endl
     402                    << "Terminating the program." << std::endl;
     403            abort();
     404        }
    425405
    426406        bGraphicsLoaded_ = false;
     
    485465    }
    486466
    487     /*static*/ void Core::tsetMediaPath(const std::string& path)
    488     {
    489         getInstance().configuration_->tsetMediaPath(path);
    490     }
    491 
    492     /*static*/ const boost::filesystem::path& Core::getMediaPath()
    493     {
    494         return getInstance().configuration_->mediaPath_;
    495     }
    496     /*static*/ std::string Core::getMediaPathString()
    497     {
    498         return getInstance().configuration_->mediaPath_.string() + '/';
     467    /*static*/ void Core::tsetExternalDataPath(const std::string& path)
     468    {
     469        getInstance().configuration_->tsetExternalDataPath(path);
     470    }
     471
     472    /*static*/ const boost::filesystem::path& Core::getDataPath()
     473    {
     474        return getInstance().configuration_->dataPath_;
     475    }
     476    /*static*/ std::string Core::getDataPathString()
     477    {
     478        return getInstance().configuration_->dataPath_.string() + '/';
     479    }
     480
     481    /*static*/ const boost::filesystem::path& Core::getExternalDataPath()
     482    {
     483        return getInstance().configuration_->externalDataPath_;
     484    }
     485    /*static*/ std::string Core::getExternalDataPathString()
     486    {
     487        return getInstance().configuration_->externalDataPath_.string() + '/';
    499488    }
    500489
     
    638627            COUT(1) << "Running from the build tree." << std::endl;
    639628            Core::bDevRun_ = true;
    640             configuration_->modulePath_ = ORXONOX_MODULE_DEV_PATH;
     629            configuration_->modulePath_ = specialConfig::moduleDevDirectory;
    641630        }
    642631        else
     
    646635
    647636            // Also set the root path
    648             boost::filesystem::path relativeExecutablePath(ORXONOX_RUNTIME_INSTALL_PATH);
     637            boost::filesystem::path relativeExecutablePath(specialConfig::defaultRuntimePath);
    649638            configuration_->rootPath_ = configuration_->executablePath_;
    650639            while (!boost::filesystem::equivalent(configuration_->rootPath_ / relativeExecutablePath, configuration_->executablePath_)
     
    655644
    656645            // Module path is fixed as well
    657             configuration_->modulePath_ = configuration_->rootPath_ / ORXONOX_MODULE_INSTALL_PATH;
     646            configuration_->modulePath_ = configuration_->rootPath_ / specialConfig::defaultModulePath;
    658647
    659648#else
     
    661650            // There is no root path, so don't set it at all
    662651            // Module path is fixed as well
    663             configuration_->modulePath_ = ORXONOX_MODULE_INSTALL_PATH;
     652            configuration_->modulePath_ = specialConfig::moduleInstallDirectory;
    664653
    665654#endif
     
    677666        if (Core::isDevelopmentRun())
    678667        {
    679             configuration_->mediaPath_  = ORXONOX_MEDIA_DEV_PATH;
    680             configuration_->configPath_ = ORXONOX_CONFIG_DEV_PATH;
    681             configuration_->logPath_    = ORXONOX_LOG_DEV_PATH;
     668            configuration_->dataPath_  = specialConfig::dataDevDirectory;
     669            configuration_->externalDataPath_ = specialConfig::externalDataDevDirectory;
     670            configuration_->configPath_ = specialConfig::configDevDirectory;
     671            configuration_->logPath_    = specialConfig::logDevDirectory;
    682672        }
    683673        else
     
    687677
    688678            // Using paths relative to the install prefix, complete them
    689             configuration_->mediaPath_  = configuration_->rootPath_ / ORXONOX_MEDIA_INSTALL_PATH;
    690             configuration_->configPath_ = configuration_->rootPath_ / ORXONOX_CONFIG_INSTALL_PATH;
    691             configuration_->logPath_    = configuration_->rootPath_ / ORXONOX_LOG_INSTALL_PATH;
     679            configuration_->dataPath_   = configuration_->rootPath_ / specialConfig::defaultDataPath;
     680            configuration_->configPath_ = configuration_->rootPath_ / specialConfig::defaultConfigPath;
     681            configuration_->logPath_    = configuration_->rootPath_ / specialConfig::defaultLogPath;
    692682
    693683#else
    694684
    695             configuration_->mediaPath_  = ORXONOX_MEDIA_INSTALL_PATH;
     685            configuration_->dataPath_  = specialConfig::dataInstallDirectory;
    696686
    697687            // Get user directory
     
    706696            userDataPath /= ".orxonox";
    707697
    708             configuration_->configPath_ = userDataPath / ORXONOX_CONFIG_INSTALL_PATH;
    709             configuration_->logPath_    = userDataPath / ORXONOX_LOG_INSTALL_PATH;
     698            configuration_->configPath_ = userDataPath / specialConfig::defaultConfigPath;
     699            configuration_->logPath_    = userDataPath / specialConfig::defaultLogPath;
    710700
    711701#endif
     
    741731    }
    742732
    743     bool Core::preUpdate(const Clock& time) throw()
    744     {
    745         std::string exceptionMessage;
    746         try
    747         {
    748             if (this->bGraphicsLoaded_)
    749             {
    750                 // process input events
    751                 this->inputManager_->update(time);
    752                 // process gui events
    753                 this->guiManager_->update(time);
    754             }
    755             // process thread commands
    756             this->tclThreadManager_->update(time);
    757         }
    758         catch (const std::exception& ex)
    759         { exceptionMessage = ex.what(); }
    760         catch (...)
    761         { exceptionMessage = "Unknown exception"; }
    762         if (!exceptionMessage.empty())
    763         {
    764             COUT(0) << "An exception occurred in the Core preUpdate: " << exceptionMessage << std::endl;
    765             COUT(0) << "This should really never happen! Closing the program." << std::endl;
    766             return false;
    767         }
    768         return true;
    769     }
    770 
    771     bool Core::postUpdate(const Clock& time) throw()
    772     {
    773         std::string exceptionMessage;
    774         try
    775         {
    776             if (this->bGraphicsLoaded_)
    777             {
    778                 // Render (doesn't throw)
    779                 this->graphicsManager_->update(time);
    780             }
    781         }
    782         catch (const std::exception& ex)
    783         { exceptionMessage = ex.what(); }
    784         catch (...)
    785         { exceptionMessage = "Unknown exception"; }
    786         if (!exceptionMessage.empty())
    787         {
    788             COUT(0) << "An exception occurred in the Core postUpdate: " << exceptionMessage << std::endl;
    789             COUT(0) << "This should really never happen! Closing the program." << std::endl;
    790             return false;
    791         }
    792         return true;
     733    void Core::preUpdate(const Clock& time)
     734    {
     735        if (this->bGraphicsLoaded_)
     736        {
     737            // process input events
     738            this->inputManager_->update(time);
     739            // process gui events
     740            this->guiManager_->update(time);
     741        }
     742        // process thread commands
     743        this->tclThreadManager_->update(time);
     744    }
     745
     746    void Core::postUpdate(const Clock& time)
     747    {
     748        if (this->bGraphicsLoaded_)
     749        {
     750            // Render (doesn't throw)
     751            this->graphicsManager_->update(time);
     752        }
    793753    }
    794754}
  • code/trunk/src/core/Core.h

    r5693 r5695  
    5151{
    5252    class CoreConfiguration;
    53     using boost::scoped_ptr;
    5453
    5554    /**
     
    5756        The Core class is a singleton used to configure the program basics.
    5857    @details
    59         The class provides information about the media, config and log path.
     58        The class provides information about the data, config and log path.
    6059        It determines those by the use of platform specific functions.
    6160    @remark
     
    6665        typedef Loki::ScopeGuardImpl0<void (*)()> SimpleScopeGuard;
    6766        friend class Singleton<Core>;
     67        friend class Game;
    6868
    6969        public:
     
    8080            void setConfigValues();
    8181
    82             bool preUpdate(const Clock& time) throw();
    83             bool postUpdate(const Clock& time) throw();
    84 
    85             void loadGraphics();
    86             void unloadGraphics();
    87 
    8882            static int   getSoftDebugLevel(OutputHandler::OutputDevice device = OutputHandler::LD_All);
    8983            static void  setSoftDebugLevel(OutputHandler::OutputDevice device, int level);
     
    9185            static void  resetLanguage();
    9286
    93             static void tsetMediaPath(const std::string& path);
    94             //! Returns the path to the config files as boost::filesystem::path
    95             static const boost::filesystem::path& getMediaPath();
     87            static void tsetExternalDataPath(const std::string& path);
     88            //! Returns the path to the data files as boost::filesystem::path
     89            static const boost::filesystem::path& getDataPath();
     90            //! Returns the path to the external data files as boost::filesystem::path
     91            static const boost::filesystem::path& getExternalDataPath();
    9692            //! Returns the path to the config files as boost::filesystem::path
    9793            static const boost::filesystem::path& getConfigPath();
     
    10197            static const boost::filesystem::path& getRootPath();
    10298            //! Returns the path to the data files as std::string
    103             static std::string getMediaPathString();
     99            static std::string getDataPathString();
     100            //! Returns the path to the external data files as std::string
     101            static std::string getExternalDataPathString();
    104102            //! Returns the path to the config files as std::string
    105103            static std::string getConfigPathString();
     
    113111        private:
    114112            Core(const Core&); //!< Don't use (undefined symbol)
     113
     114            void preUpdate(const Clock& time);
     115            void postUpdate(const Clock& time);
     116
     117            void loadGraphics();
     118            void unloadGraphics();
    115119
    116120            void setFixedPaths();
     
    126130            scoped_ptr<Language>          languageInstance_;
    127131            scoped_ptr<CoreConfiguration> configuration_;
    128             scoped_ptr<LuaBind>           luaBind_;
    129132            scoped_ptr<TclBind>           tclBind_;
    130133            scoped_ptr<TclThreadManager>  tclThreadManager_;
  • code/trunk/src/core/CorePrereqs.h

    r5693 r5695  
    135135    class LanguageEntry;
    136136    class Loader;
    137     class LuaBind;
     137    class LuaState;
     138    class MemoryArchive;
     139    class MemoryArchiveFactory;
    138140    class MetaObjectList;
    139141    class MetaObjectListElement;
     
    150152    class OgreWindowEventListener;
    151153    class OrxonoxClass;
     154    struct ResourceInfo;
    152155    class Shell;
    153156    class ShellListener;
     
    225228}
    226229
     230// Ogre
     231namespace Ogre
     232{
     233    class DataStream;
     234    template <class T> class SharedPtr;
     235    typedef SharedPtr<DataStream> DataStreamPtr;
     236}
     237namespace orxonox
     238{
     239    // Import the Ogre::DataStream
     240    using Ogre::DataStream;
     241    using Ogre::DataStreamPtr;
     242}
     243
    227244// CEGUI
    228245namespace CEGUI
  • code/trunk/src/core/DynLibManager.h

    r5693 r5695  
    3434
    3535#include "CorePrereqs.h"
     36
     37#include <map>
     38#include <string>
    3639#include "util/Singleton.h"
    3740
  • code/trunk/src/core/GUIManager.cc

    r3370 r5695  
    2727 *
    2828 */
    29 
    30 /**
    31 @file
    32 @brief
    33     Implementation of the GUIManager class.
    34 */
    3529
    3630#include "GUIManager.h"
     
    4337#include <CEGUIExceptions.h>
    4438#include <CEGUIInputEvent.h>
     39#include <CEGUIMouseCursor.h>
    4540#include <CEGUIResourceProvider.h>
    4641#include <CEGUISystem.h>
     
    5954#include "Core.h"
    6055#include "Clock.h"
    61 #include "LuaBind.h"
     56#include "LuaState.h"
     57#include "Resource.h"
    6258
    6359namespace orxonox
     
    10197    @return true if success, otherwise false
    10298    */
    103     GUIManager::GUIManager(Ogre::RenderWindow* renderWindow)
     99    GUIManager::GUIManager(Ogre::RenderWindow* renderWindow, const std::pair<int, int>& mousePosition, bool bFullScreen)
    104100        : renderWindow_(renderWindow)
    105101        , resourceProvider_(0)
     
    109105        COUT(3) << "Initialising CEGUI." << std::endl;
    110106
    111         try
    112         {
    113             // Note: No SceneManager specified yet
    114             guiRenderer_.reset(new OgreCEGUIRenderer(renderWindow_, Ogre::RENDER_QUEUE_OVERLAY, false, 3000));
    115             resourceProvider_ = guiRenderer_->createResourceProvider();
    116             resourceProvider_->setDefaultResourceGroup("GUI");
    117 
    118             // setup scripting
    119             scriptModule_.reset(new LuaScriptModule());
    120             luaState_ = scriptModule_->getLuaState();
    121 
    122             // Create our own logger to specify the filepath
    123             std::auto_ptr<CEGUILogger> ceguiLogger(new CEGUILogger());
    124             ceguiLogger->setLogFilename(Core::getLogPathString() + "cegui.log");
    125             // set the log level according to ours (translate by subtracting 1)
    126             ceguiLogger->setLoggingLevel(
    127                 static_cast<LoggingLevel>(Core::getSoftDebugLevel(OutputHandler::LD_Logfile) - 1));
    128             this->ceguiLogger_ = ceguiLogger.release();
    129 
    130             // create the CEGUI system singleton
    131             guiSystem_.reset(new System(guiRenderer_.get(), resourceProvider_, 0, scriptModule_.get()));
    132 
    133             // do this after 'new CEGUI::Sytem' because that creates the lua state in the first place
    134             LuaBind::getInstance().openToluaInterfaces(this->luaState_);
    135 
    136             // initialise the basic lua code
    137             this->loadLuaCode();
    138         }
    139         catch (CEGUI::Exception& ex)
    140         {
    141 #if CEGUI_VERSION_MAJOR == 0 && CEGUI_VERSION_MINOR < 6
    142             throw GeneralException(ex.getMessage().c_str());
    143 #else
    144             throw GeneralException(ex.getMessage().c_str(), ex.getLine(),
    145                 ex.getFileName().c_str(), ex.getName().c_str());
    146 #endif
    147         }
    148     }
    149 
    150     /**
    151     @brief
    152         Destructor of the GUIManager
    153 
     107        // Note: No SceneManager specified yet
     108        guiRenderer_.reset(new OgreCEGUIRenderer(renderWindow_, Ogre::RENDER_QUEUE_OVERLAY, false, 3000));
     109        resourceProvider_ = guiRenderer_->createResourceProvider();
     110        resourceProvider_->setDefaultResourceGroup("GUI");
     111
     112        // setup scripting
     113        luaState_.reset(new LuaState());
     114        scriptModule_.reset(new LuaScriptModule(luaState_->getInternalLuaState()));
     115
     116        // Create our own logger to specify the filepath
     117        std::auto_ptr<CEGUILogger> ceguiLogger(new CEGUILogger());
     118        ceguiLogger->setLogFilename(Core::getLogPathString() + "cegui.log");
     119        // set the log level according to ours (translate by subtracting 1)
     120        ceguiLogger->setLoggingLevel(
     121            static_cast<LoggingLevel>(Core::getSoftDebugLevel(OutputHandler::LD_Logfile) - 1));
     122        this->ceguiLogger_ = ceguiLogger.release();
     123
     124        // create the CEGUI system singleton
     125        guiSystem_.reset(new System(guiRenderer_.get(), resourceProvider_, 0, scriptModule_.get()));
     126
     127        // Initialise the basic lua code
     128        rootFileInfo_ = Resource::getInfo("InitialiseGUI.lua", "GUI");
     129        this->luaState_->doFile("InitialiseGUI.lua", "GUI", false);
     130
     131        // Align CEGUI mouse with OIS mouse
     132        guiSystem_->injectMousePosition(mousePosition.first, mousePosition.second);
     133
     134        // Hide the mouse cursor unless playing in fullscreen mode
     135        if (!bFullScreen)
     136            CEGUI::MouseCursor::getSingleton().hide();
     137    }
     138
     139    /**
     140    @brief
    154141        Basically shuts down CEGUI (member smart pointers) but first unloads our Tolua modules.
    155142    */
    156143    GUIManager::~GUIManager()
    157144    {
    158         // destroy our own tolua interfaces
    159         LuaBind::getInstance().closeToluaInterfaces(this->luaState_);
    160     }
    161 
    162     /**
    163     @brief
    164         Calls main Lua script
    165     @todo
    166         This function calls the main Lua script for our GUI.
    167 
    168         Additionally we set the datapath variable in Lua. This is needed so Lua can access the data used for the GUI.
    169     */
    170     void GUIManager::loadLuaCode()
    171     {
    172         // set datapath for GUI data
    173         lua_pushfstring(this->scriptModule_->getLuaState(), Core::getMediaPathString().c_str());
    174         lua_setglobal(this->scriptModule_->getLuaState(), "datapath");
    175         // call main Lua script
    176         this->scriptModule_->executeScriptFile("loadGUI_3.lua", "GUI");
    177145    }
    178146
     
    221189    void GUIManager::executeCode(const std::string& str)
    222190    {
    223         try
    224         {
    225             this->scriptModule_->executeString(str);
    226         }
    227         catch (const CEGUI::Exception& ex)
    228         {
    229             COUT(2) << "CEGUI Error: \"" << ex.getMessage() << "\" while executing code \"" << str << "\"" << std::endl;
    230         }
    231         catch (...)
    232         {
    233             COUT(2) << "Couldn't execute GUI related Lua code due to unknown reasons." << std::endl;
    234         }
     191        this->luaState_->doString(str, rootFileInfo_);
    235192    }
    236193
     
    246203    void GUIManager::showGUI(const std::string& name)
    247204    {
    248         this->executeCode(std::string("showGUI(\"") + name + "\")");
     205        this->luaState_->doString("showGUI(\"" + name + "\")", rootFileInfo_);
    249206    }
    250207
     
    305262    void GUIManager::mouseMoved(IntVector2 abs, IntVector2 rel, IntVector2 clippingSize)
    306263    {
    307         guiSystem_->injectMouseMove(static_cast<float>(rel.x), static_cast<float>(rel.y));
     264        guiSystem_->injectMousePosition(static_cast<float>(abs.x), static_cast<float>(abs.y));
    308265    }
    309266    void GUIManager::mouseScrolled(int abs, int rel)
  • code/trunk/src/core/GUIManager.h

    r5693 r5695  
    2828 */
    2929
    30 /**
    31 @file
    32 @brief
    33     Declaration of the GUIManager class.
    34 */
    35 
    3630#ifndef _GUIManager_H__
    3731#define _GUIManager_H__
     
    4337#include <CEGUIForwardRefs.h>
    4438#include <boost/scoped_ptr.hpp>
     39#include <boost/shared_ptr.hpp>
    4540
    4641#include "util/OgreForwardRefs.h"
     
    6762        friend class Singleton<GUIManager>;
    6863    public:
    69         GUIManager(Ogre::RenderWindow* renderWindow);
     64        GUIManager(Ogre::RenderWindow* renderWindow, const std::pair<int, int>& mousePosition, bool bFullScreen);
    7065        ~GUIManager();
    7166
     
    8782        GUIManager(const GUIManager& instance); //!< private and undefined copy c'tor (this is a singleton class)
    8883
    89         void loadLuaCode();
    90 
    9184        // keyHandler functions
    9285        void keyPressed (const KeyEvent& evt);
     
    9992        void mouseScrolled (int abs, int rel);
    10093
    101         boost::scoped_ptr<CEGUI::OgreCEGUIRenderer> guiRenderer_;       //!< CEGUI's interface to the Ogre Engine
    102         boost::scoped_ptr<CEGUI::LuaScriptModule>   scriptModule_;      //!< CEGUI's script module to use Lua
    103         boost::scoped_ptr<CEGUI::System>            guiSystem_;         //!< CEGUI's main system
    104         Ogre::RenderWindow*                         renderWindow_;      //!< Ogre's render window to give CEGUI access to it
    105         CEGUI::ResourceProvider*                    resourceProvider_;  //!< CEGUI's resource provider
    106         CEGUI::Logger*                              ceguiLogger_;       //!< CEGUI's logger to be able to log CEGUI errors in our log
    107         lua_State*                                  luaState_;          //!< Lua state, access point to the Lua engine
    108         std::map<std::string, PlayerInfo*>          players_;           //!< Stores the player (owner) for each gui
     94        scoped_ptr<CEGUI::OgreCEGUIRenderer> guiRenderer_;      //!< CEGUI's interface to the Ogre Engine
     95        scoped_ptr<LuaState>                 luaState_;         //!< LuaState, access point to the Lua engine
     96        scoped_ptr<CEGUI::LuaScriptModule>   scriptModule_;     //!< CEGUI's script module to use Lua
     97        scoped_ptr<CEGUI::System>            guiSystem_;        //!< CEGUI's main system
     98        shared_ptr<ResourceInfo>             rootFileInfo_;     //!< Resource information about the root script
     99        Ogre::RenderWindow*                  renderWindow_;     //!< Ogre's render window to give CEGUI access to it
     100        CEGUI::ResourceProvider*             resourceProvider_; //!< CEGUI's resource provider
     101        CEGUI::Logger*                       ceguiLogger_;      //!< CEGUI's logger to be able to log CEGUI errors in our log
     102        std::map<std::string, PlayerInfo*>   players_;          //!< Stores the player (owner) for each gui
    109103
    110         static GUIManager*                          singletonPtr_s;     //!< Singleton reference to GUIManager
     104        static GUIManager*                   singletonPtr_s;    //!< Singleton reference to GUIManager
    111105
    112106    };
  • code/trunk/src/core/Game.cc

    r5693 r5695  
    3737#include <exception>
    3838#include <boost/weak_ptr.hpp>
     39#include <CEGUIExceptions.h>
    3940
    4041#include "util/Debug.h"
     
    5455namespace orxonox
    5556{
    56     using boost::shared_ptr;
    57     using boost::weak_ptr;
    58 
    5957    static void stop_game()
    6058        { Game::getInstance().stop(); }
     
    202200
    203201            // Core preUpdate (doesn't throw)
    204             if (!this->core_->preUpdate(*this->gameClock_))
    205             {
     202            try
     203                { this->core_->preUpdate(*this->gameClock_); }
     204            catch (...)
     205            {
     206                COUT(0) << "An exception occurred in the Core preUpdate: " << Game::getExceptionMessage() << std::endl;
     207                COUT(0) << "This should really never happen! Closing the program." << std::endl;
    206208                this->stop();
    207209                break;
     
    212214
    213215            // Core postUpdate (doesn't throw)
    214             if (!this->core_->postUpdate(*this->gameClock_))
    215             {
     216            try
     217                { this->core_->postUpdate(*this->gameClock_); }
     218            catch (...)
     219            {
     220            COUT(0) << "An exception occurred in the Core postUpdate: " << Game::getExceptionMessage() << std::endl;
     221            COUT(0) << "This should really never happen! Closing the program." << std::endl;
    216222                this->stop();
    217223                break;
     
    246252                    this->loadState(requestedStateNode->name_);
    247253                }
    248                 catch (const std::exception& ex)
     254                catch (...)
    249255                {
    250                     COUT(1) << "Error: Loading GameState '" << requestedStateNode->name_ << "' failed: " << ex.what() << std::endl;
     256                    COUT(1) << "Error: Loading GameState '" << requestedStateNode->name_ << "' failed: " << Game::getExceptionMessage() << std::endl;
    251257                    // All scheduled operations have now been rendered inert --> flush them and issue a warning
    252258                    if (this->requestedStateNodes_.size() > 1)
    253                         COUT(1) << "All " << this->requestedStateNodes_.size() - 1 << " scheduled transitions have been ignored." << std::endl;
     259                        COUT(4) << "All " << this->requestedStateNodes_.size() - 1 << " scheduled transitions have been ignored." << std::endl;
    254260                    this->requestedStateNodes_.clear();
    255261                    break;
     
    267273            it != this->loadedStates_.end(); ++it)
    268274        {
    269             std::string exceptionMessage;
    270275            try
    271276            {
    272277                // Add tick time for most of the states
    273                 uint64_t timeBeforeTick;
     278                uint64_t timeBeforeTick = 0;
    274279                if ((*it)->getInfo().bIgnoreTickTime)
    275280                    timeBeforeTick = this->gameClock_->getRealMicroseconds();
     
    278283                    this->subtractTickTime(static_cast<int32_t>(this->gameClock_->getRealMicroseconds() - timeBeforeTick));
    279284            }
    280             catch (const std::exception& ex)
    281             { exceptionMessage = ex.what(); }
    282285            catch (...)
    283             { exceptionMessage = "Unknown exception"; }
    284             if (!exceptionMessage.empty())
    285             {
    286                 COUT(1) << "An exception occurred while updating '" << (*it)->getName() << "': " << exceptionMessage << std::endl;
     286            {
     287                COUT(1) << "An exception occurred while updating '" << (*it)->getName() << "': " << Game::getExceptionMessage() << std::endl;
    287288                COUT(1) << "This should really never happen!" << std::endl;
    288289                COUT(1) << "Unloading all GameStates depending on the one that crashed." << std::endl;
     
    590591            state->deactivate();
    591592        }
     593        catch (...)
     594        {
     595            COUT(2) << "Warning: Unloading GameState '" << name << "' threw an exception: " << Game::getExceptionMessage() << std::endl;
     596            COUT(2) << "         There might be potential resource leaks involved! To avoid this, improve exception-safety." << std::endl;
     597        }
     598        // Check if graphics is still required
     599        if (!bAbort_)
     600        {
     601            bool graphicsRequired = false;
     602            for (unsigned i = 0; i < loadedStates_.size(); ++i)
     603                graphicsRequired |= loadedStates_[i]->getInfo().bGraphicsMode;
     604            if (!graphicsRequired)
     605                this->unloadGraphics();
     606        }
     607        this->bChangingState_ = false;
     608    }
     609
     610    /*static*/ std::string Game::getExceptionMessage()
     611    {
     612        std::string exceptionMessage;
     613        try
     614        {
     615            // rethrow
     616            throw;
     617        }
    592618        catch (const std::exception& ex)
    593619        {
    594             COUT(2) << "Warning: Unloading GameState '" << name << "' threw an exception: " << ex.what() << std::endl;
    595             COUT(2) << "         There might be potential resource leaks involved! To avoid this, improve exception-safety." << std::endl;
    596         }
    597         // Check if graphics is still required
    598         bool graphicsRequired = false;
    599         for (unsigned i = 0; i < loadedStates_.size(); ++i)
    600             graphicsRequired |= loadedStates_[i]->getInfo().bGraphicsMode;
    601         if (!graphicsRequired)
    602             this->unloadGraphics();
    603         this->bChangingState_ = false;
     620            return ex.what();
     621        }
     622        catch (const CEGUI::Exception& ex)
     623        {
     624#if CEGUI_VERSION_MAJOR == 0 && CEGUI_VERSION_MINOR < 6
     625            return GeneralException(ex.getMessage().c_str()).getDescription();
     626#else
     627            return GeneralException(ex.getMessage().c_str(), ex.getLine(),
     628                ex.getFileName().c_str(), ex.getName().c_str()).getDescription();
     629#endif
     630        }
     631        catch (...)
     632        {
     633            return "Unknown exception";
     634        }
    604635    }
    605636
  • code/trunk/src/core/Game.h

    r5693 r5695  
    6262{
    6363    class GameConfiguration;
    64     using boost::scoped_ptr;
    65     using boost::shared_ptr;
    6664
    6765    //! Helper object required before GameStates are being constructed
     
    8583        typedef std::vector<shared_ptr<GameState> > GameStateVector;
    8684        typedef std::map<std::string, shared_ptr<GameState> > GameStateMap;
    87         typedef boost::shared_ptr<GameStateTreeNode> GameStateTreeNodePtr;
     85        typedef shared_ptr<GameStateTreeNode> GameStateTreeNodePtr;
    8886
    8987    public:
     
    157155        // ScopeGuard helper function
    158156        void resetChangingState() { this->bChangingState_ = false; }
     157        /**
     158        @brief
     159            Retrieves information from an exception caught with "..."
     160        @remarks
     161            Never ever call this function without an exception in the stack!
     162        */
     163        static std::string getExceptionMessage();
    159164
    160165        scoped_ptr<Clock>                  gameClock_;
  • code/trunk/src/core/GraphicsManager.cc

    r3370 r5695  
    2828 */
    2929
    30 /**
    31 @file
    32 @brief
    33     Implementation of an partial interface to Ogre.
    34 */
    35 
    3630#include "GraphicsManager.h"
    3731
    3832#include <fstream>
    39 #include <memory>
     33#include <sstream>
    4034#include <boost/filesystem.hpp>
    41 #include <boost/shared_ptr.hpp>
    42 
    43 #include <OgreCompositorManager.h>
    44 #include <OgreConfigFile.h>
     35#include <boost/shared_array.hpp>
     36
     37#include <OgreArchiveFactory.h>
     38#include <OgreArchiveManager.h>
    4539#include <OgreFrameListener.h>
    4640#include <OgreRoot.h>
    4741#include <OgreLogManager.h>
    48 #include <OgreException.h>
    4942#include <OgreRenderWindow.h>
    5043#include <OgreRenderSystem.h>
     44#include <OgreResourceGroupManager.h>
    5145#include <OgreTextureManager.h>
    5246#include <OgreViewport.h>
     
    6458#include "Game.h"
    6559#include "GameMode.h"
     60#include "Loader.h"
     61#include "MemoryArchive.h"
    6662#include "WindowEventListener.h"
     63#include "XMLFile.h"
    6764
    6865namespace orxonox
    6966{
    70     using boost::shared_ptr;
    71 
    7267    class OgreWindowEventListener : public Ogre::WindowEventListener
    7368    {
     
    8984        Non-initialising constructor.
    9085    */
    91     GraphicsManager::GraphicsManager()
    92         : ogreRoot_(0)
    93         , ogreLogger_(0)
     86    GraphicsManager::GraphicsManager(bool bLoadRenderer)
     87        : ogreWindowEventListener_(new OgreWindowEventListener())
     88#if OGRE_VERSION < 0x010600
     89        , memoryArchiveFactory_(new MemoryArchiveFactory())
     90#endif
    9491        , renderWindow_(0)
    9592        , viewport_(0)
    96         , ogreWindowEventListener_(new OgreWindowEventListener())
    9793    {
    9894        RegisterObject(GraphicsManager);
     
    10096        this->setConfigValues();
    10197
    102         // Ogre setup procedure
    103         setupOgre();
    104 
    105         try
    106         {
    107             // load all the required plugins for Ogre
    108             loadOgrePlugins();
    109             // read resource declaration file
    110             this->declareResources();
    111             // Reads ogre config and creates the render window
    112             this->loadRenderer();
    113 
    114             // TODO: Spread this
    115             this->initialiseResources();
    116 
    117             // add console commands
    118             FunctorMember<GraphicsManager>* functor1 = createFunctor(&GraphicsManager::printScreen);
    119             functor1->setObject(this);
    120             ccPrintScreen_ = createConsoleCommand(functor1, "printScreen");
    121             CommandExecutor::addConsoleCommandShortcut(ccPrintScreen_);
    122         }
    123         catch (...)
    124         {
    125             // clean up
    126             delete this->ogreRoot_;
    127             delete this->ogreLogger_;
    128             delete this->ogreWindowEventListener_;
    129             throw;
     98        // Ogre setup procedure (creating Ogre::Root)
     99        this->loadOgreRoot();
     100        // load all the required plugins for Ogre
     101        this->loadOgrePlugins();
     102
     103        // At first, add the root paths of the data directories as resource locations
     104        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(Core::getDataPathString(), "FileSystem", "dataRoot", false);
     105        // Load resources
     106        resources_.reset(new XMLFile("resources.oxr", "dataRoot"));
     107        resources_->setLuaSupport(false);
     108        Loader::open(resources_.get());
     109
     110        // Only for development runs
     111        if (Core::isDevelopmentRun())
     112        {
     113            Ogre::ResourceGroupManager::getSingleton().addResourceLocation(Core::getExternalDataPathString(), "FileSystem", "externalDataRoot", false);
     114            extResources_.reset(new XMLFile("resources.oxr", "externalDataRoot"));
     115            extResources_->setLuaSupport(false);
     116            Loader::open(extResources_.get());
     117        }
     118
     119        if (bLoadRenderer)
     120        {
     121            // Reads the ogre config and creates the render window
     122            this->upgradeToGraphics();
    130123        }
    131124    }
     
    133126    /**
    134127    @brief
    135         Destroys all the Ogre related objects
     128        Destruction is done by the member scoped_ptrs.
    136129    */
    137130    GraphicsManager::~GraphicsManager()
    138131    {
    139 /*
    140         delete this->ccPrintScreen_;
    141 */
    142 
    143         // unload all compositors (this is only necessary because we don't yet destroy all resources!)
    144         Ogre::CompositorManager::getSingleton().removeAll();
    145 
    146         // Delete OGRE main control organ
    147         delete this->ogreRoot_;
    148 
    149         // delete the logManager (since we have created it in the first place).
    150         delete this->ogreLogger_;
    151 
    152         delete this->ogreWindowEventListener_;
     132        Ogre::WindowEventUtilities::removeWindowEventListener(renderWindow_, ogreWindowEventListener_.get());
     133        // TODO: Destroy the console command
    153134    }
    154135
    155136    void GraphicsManager::setConfigValues()
    156137    {
    157         SetConfigValue(resourceFile_,    "resources.cfg")
    158             .description("Location of the resources file in the data path.");
    159138        SetConfigValue(ogreConfigFile_,  "ogre.cfg")
    160139            .description("Location of the Ogre config file");
    161         SetConfigValue(ogrePluginsFolder_, ORXONOX_OGRE_PLUGINS_FOLDER)
     140        SetConfigValue(ogrePluginsDirectory_, specialConfig::ogrePluginsDirectory)
    162141            .description("Folder where the Ogre plugins are located.");
    163         SetConfigValue(ogrePlugins_, ORXONOX_OGRE_PLUGINS)
     142        SetConfigValue(ogrePlugins_, specialConfig::ogrePlugins)
    164143            .description("Comma separated list of all plugins to load.");
    165144        SetConfigValue(ogreLogFile_,     "ogre.log")
     
    173152    }
    174153
     154    /**
     155    @brief
     156        Loads the renderer and creates the render window if not yet done so.
     157    @remarks
     158        This operation is irreversible without recreating the GraphicsManager!
     159        So if it throws you HAVE to recreate the GraphicsManager!!!
     160        It therefore offers almost no exception safety.
     161    */
     162    void GraphicsManager::upgradeToGraphics()
     163    {
     164        if (renderWindow_ != NULL)
     165            return;
     166
     167        this->loadRenderer();
     168
     169#if OGRE_VERSION < 0x010600
     170        // WORKAROUND: There is an incompatibility for particle scripts when trying
     171        // to support both Ogre 1.4 and 1.6. The hacky solution is to create
     172        // scripts for the 1.6 version and then remove the inserted "particle_system"
     173        // keyword. But we need to supply these new scripts as well, which is why
     174        // there is an extra Ogre::Archive dealing with in the memory.
     175        using namespace Ogre;
     176        ArchiveManager::getSingleton().addArchiveFactory(memoryArchiveFactory_.get());
     177        const StringVector& groups = ResourceGroupManager::getSingleton().getResourceGroups();
     178        // Travers all groups
     179        for (StringVector::const_iterator itGroup = groups.begin(); itGroup != groups.end(); ++itGroup)
     180        {
     181            FileInfoListPtr files = ResourceGroupManager::getSingleton().findResourceFileInfo(*itGroup, "*.particle");
     182            for (FileInfoList::const_iterator itFile = files->begin(); itFile != files->end(); ++itFile)
     183            {
     184                // open file
     185                Ogre::DataStreamPtr input = ResourceGroupManager::getSingleton().openResource(itFile->filename, *itGroup, false);
     186                std::stringstream output;
     187                // Parse file and replace "particle_system" with nothing
     188                while (!input->eof())
     189                {
     190                    std::string line = input->getLine();
     191                    size_t pos = line.find("particle_system");
     192                    if (pos != std::string::npos)
     193                    {
     194                        // 15 is the length of "particle_system"
     195                        line.replace(pos, 15, "");
     196                    }
     197                    output << line << std::endl;
     198                }
     199                // Add file to the memory archive
     200                shared_array<char> data(new char[output.str().size()]);
     201                // Debug optimisations
     202                const std::string outputStr = output.str();
     203                char* rawData = data.get();
     204                for (unsigned i = 0; i < outputStr.size(); ++i)
     205                    rawData[i] = outputStr[i];
     206                MemoryArchive::addFile("particle_scripts_ogre_1.4_" + *itGroup, itFile->filename, data, output.str().size());
     207            }
     208            if (!files->empty())
     209            {
     210                // Declare the files, but using a new group
     211                ResourceGroupManager::getSingleton().addResourceLocation("particle_scripts_ogre_1.4_" + *itGroup,
     212                    "Memory", "particle_scripts_ogre_1.4_" + *itGroup);
     213            }
     214        }
     215#endif
     216
     217        // Initialise all resources (do this AFTER the renderer has been loaded!)
     218        // Note: You can only do this once! Ogre will check whether a resource group has
     219        // already been initialised. If you need to load resources later, you will have to
     220        // choose another resource group.
     221        Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
     222    }
     223
     224    /**
     225    @brief
     226        Creates the Ogre Root object and sets up the ogre log.
     227    */
     228    void GraphicsManager::loadOgreRoot()
     229    {
     230        COUT(3) << "Setting up Ogre..." << std::endl;
     231
     232        if (ogreConfigFile_ == "")
     233        {
     234            COUT(2) << "Warning: Ogre config file set to \"\". Defaulting to config.cfg" << std::endl;
     235            ModifyConfigValue(ogreConfigFile_, tset, "config.cfg");
     236        }
     237        if (ogreLogFile_ == "")
     238        {
     239            COUT(2) << "Warning: Ogre log file set to \"\". Defaulting to ogre.log" << std::endl;
     240            ModifyConfigValue(ogreLogFile_, tset, "ogre.log");
     241        }
     242
     243        boost::filesystem::path ogreConfigFilepath(Core::getConfigPath() / this->ogreConfigFile_);
     244        boost::filesystem::path ogreLogFilepath(Core::getLogPath() / this->ogreLogFile_);
     245
     246        // create a new logManager
     247        // Ogre::Root will detect that we've already created a Log
     248        ogreLogger_.reset(new Ogre::LogManager());
     249        COUT(4) << "Ogre LogManager created" << std::endl;
     250
     251        // create our own log that we can listen to
     252        Ogre::Log *myLog;
     253        myLog = ogreLogger_->createLog(ogreLogFilepath.string(), true, false, false);
     254        COUT(4) << "Ogre Log created" << std::endl;
     255
     256        myLog->setLogDetail(Ogre::LL_BOREME);
     257        myLog->addListener(this);
     258
     259        COUT(4) << "Creating Ogre Root..." << std::endl;
     260
     261        // check for config file existence because Ogre displays (caught) exceptions if not
     262        if (!boost::filesystem::exists(ogreConfigFilepath))
     263        {
     264            // create a zero sized file
     265            std::ofstream creator;
     266            creator.open(ogreConfigFilepath.string().c_str());
     267            creator.close();
     268        }
     269
     270        // Leave plugins file empty. We're going to do that part manually later
     271        ogreRoot_.reset(new Ogre::Root("", ogreConfigFilepath.string(), ogreLogFilepath.string()));
     272
     273        COUT(3) << "Ogre set up done." << std::endl;
     274    }
     275
     276    void GraphicsManager::loadOgrePlugins()
     277    {
     278        // just to make sure the next statement doesn't segfault
     279        if (ogrePluginsDirectory_ == "")
     280            ogrePluginsDirectory_ = ".";
     281
     282        boost::filesystem::path folder(ogrePluginsDirectory_);
     283        // Do some SubString magic to get the comma separated list of plugins
     284        SubString plugins(ogrePlugins_, ",", " ", false, '\\', false, '"', false, '(', ')', false, '\0');
     285        // Use backslash paths on Windows! file_string() already does that though.
     286        for (unsigned int i = 0; i < plugins.size(); ++i)
     287            ogreRoot_->loadPlugin((folder / plugins[i]).file_string());
     288    }
     289
     290    void GraphicsManager::loadRenderer()
     291    {
     292        CCOUT(4) << "Configuring Renderer" << std::endl;
     293
     294        if (!ogreRoot_->restoreConfig())
     295            if (!ogreRoot_->showConfigDialog())
     296                ThrowException(InitialisationFailed, "OGRE graphics configuration dialogue failed.");
     297
     298        CCOUT(4) << "Creating render window" << std::endl;
     299
     300        this->renderWindow_ = ogreRoot_->initialise(true, "Orxonox");
     301        // Propagate the size of the new winodw
     302        this->ogreWindowEventListener_->windowResized(renderWindow_);
     303
     304        Ogre::WindowEventUtilities::addWindowEventListener(this->renderWindow_, ogreWindowEventListener_.get());
     305
     306        // create a full screen default viewport
     307        // Note: This may throw when adding a viewport with an existing z-order!
     308        //       But in our case we only have one viewport for now anyway, therefore
     309        //       no ScopeGuards or anything to handle exceptions.
     310        this->viewport_ = this->renderWindow_->addViewport(0, 0);
     311
     312        Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(0);
     313
     314        // add console commands
     315        FunctorMember<GraphicsManager>* functor1 = createFunctor(&GraphicsManager::printScreen);
     316        ccPrintScreen_ = createConsoleCommand(functor1->setObject(this), "printScreen");
     317        CommandExecutor::addConsoleCommandShortcut(ccPrintScreen_);
     318    }
     319
    175320    void GraphicsManager::update(const Clock& time)
    176321    {
     
    207352    {
    208353        this->viewport_->setCamera(camera);
    209     }
    210 
    211     /**
    212     @brief
    213         Creates the Ogre Root object and sets up the ogre log.
    214     */
    215     void GraphicsManager::setupOgre()
    216     {
    217         COUT(3) << "Setting up Ogre..." << std::endl;
    218 
    219         if (ogreConfigFile_ == "")
    220         {
    221             COUT(2) << "Warning: Ogre config file set to \"\". Defaulting to config.cfg" << std::endl;
    222             ModifyConfigValue(ogreConfigFile_, tset, "config.cfg");
    223         }
    224         if (ogreLogFile_ == "")
    225         {
    226             COUT(2) << "Warning: Ogre log file set to \"\". Defaulting to ogre.log" << std::endl;
    227             ModifyConfigValue(ogreLogFile_, tset, "ogre.log");
    228         }
    229 
    230         boost::filesystem::path ogreConfigFilepath(Core::getConfigPath() / this->ogreConfigFile_);
    231         boost::filesystem::path ogreLogFilepath(Core::getLogPath() / this->ogreLogFile_);
    232 
    233         // create a new logManager
    234         // Ogre::Root will detect that we've already created a Log
    235         std::auto_ptr<Ogre::LogManager> logger(new Ogre::LogManager());
    236         COUT(4) << "Ogre LogManager created" << std::endl;
    237 
    238         // create our own log that we can listen to
    239         Ogre::Log *myLog;
    240         myLog = logger->createLog(ogreLogFilepath.string(), true, false, false);
    241         COUT(4) << "Ogre Log created" << std::endl;
    242 
    243         myLog->setLogDetail(Ogre::LL_BOREME);
    244         myLog->addListener(this);
    245 
    246         COUT(4) << "Creating Ogre Root..." << std::endl;
    247 
    248         // check for config file existence because Ogre displays (caught) exceptions if not
    249         if (!boost::filesystem::exists(ogreConfigFilepath))
    250         {
    251             // create a zero sized file
    252             std::ofstream creator;
    253             creator.open(ogreConfigFilepath.string().c_str());
    254             creator.close();
    255         }
    256 
    257         // Leave plugins file empty. We're going to do that part manually later
    258         ogreRoot_ = new Ogre::Root("", ogreConfigFilepath.string(), ogreLogFilepath.string());
    259         // In case that new Root failed the logger gets destroyed because of the std::auto_ptr
    260         ogreLogger_ = logger.release();
    261 
    262         COUT(3) << "Ogre set up done." << std::endl;
    263     }
    264 
    265     void GraphicsManager::loadOgrePlugins()
    266     {
    267         // just to make sure the next statement doesn't segfault
    268         if (ogrePluginsFolder_ == "")
    269             ogrePluginsFolder_ = ".";
    270 
    271         boost::filesystem::path folder(ogrePluginsFolder_);
    272         // Do some SubString magic to get the comma separated list of plugins
    273         SubString plugins(ogrePlugins_, ",", " ", false, '\\', false, '"', false, '(', ')', false, '\0');
    274         // Use backslash paths on Windows! file_string() already does that though.
    275         for (unsigned int i = 0; i < plugins.size(); ++i)
    276             ogreRoot_->loadPlugin((folder / plugins[i]).file_string());
    277     }
    278 
    279     void GraphicsManager::declareResources()
    280     {
    281         CCOUT(4) << "Declaring Resources" << std::endl;
    282         //TODO: Specify layout of data file and maybe use xml-loader
    283         //TODO: Work with ressource groups (should be generated by a special loader)
    284 
    285         if (resourceFile_ == "")
    286         {
    287             COUT(2) << "Warning: Ogre resource file set to \"\". Defaulting to resources.cfg" << std::endl;
    288             ModifyConfigValue(resourceFile_, tset, "resources.cfg");
    289         }
    290 
    291         // Load resource paths from data file using configfile ressource type
    292         Ogre::ConfigFile cf;
    293         try
    294         {
    295             cf.load((Core::getMediaPath() / resourceFile_).string());
    296         }
    297         catch (...)
    298         {
    299             //COUT(1) << ex.getFullDescription() << std::endl;
    300             COUT(0) << "Have you forgotten to set the data path in orxnox.ini?" << std::endl;
    301             throw;
    302         }
    303 
    304         // Go through all sections & settings in the file
    305         Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
    306 
    307         std::string secName, typeName, archName;
    308         while (seci.hasMoreElements())
    309         {
    310             try
    311             {
    312                 secName = seci.peekNextKey();
    313                 Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
    314                 Ogre::ConfigFile::SettingsMultiMap::iterator i;
    315                 for (i = settings->begin(); i != settings->end(); ++i)
    316                 {
    317                     typeName = i->first; // for instance "FileSystem" or "Zip"
    318                     archName = i->second; // name (and location) of archive
    319 
    320                     Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
    321                         (Core::getMediaPath() / archName).string(), typeName, secName);
    322                 }
    323             }
    324             catch (Ogre::Exception& ex)
    325             {
    326                 COUT(1) << ex.getFullDescription() << std::endl;
    327             }
    328         }
    329     }
    330 
    331     void GraphicsManager::loadRenderer()
    332     {
    333         CCOUT(4) << "Configuring Renderer" << std::endl;
    334 
    335         if (!ogreRoot_->restoreConfig())
    336             if (!ogreRoot_->showConfigDialog())
    337                 ThrowException(InitialisationFailed, "OGRE graphics configuration dialogue failed.");
    338 
    339         CCOUT(4) << "Creating render window" << std::endl;
    340 
    341         this->renderWindow_ = ogreRoot_->initialise(true, "Orxonox");
    342         this->ogreWindowEventListener_->windowResized(renderWindow_);
    343 
    344         Ogre::WindowEventUtilities::addWindowEventListener(this->renderWindow_, ogreWindowEventListener_);
    345 
    346         Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(0);
    347 
    348         // create a full screen default viewport
    349         this->viewport_ = this->renderWindow_->addViewport(0, 0);
    350     }
    351 
    352     void GraphicsManager::initialiseResources()
    353     {
    354         CCOUT(4) << "Initialising resources" << std::endl;
    355         //TODO: Do NOT load all the groups, why are we doing that? And do we really do that? initialise != load...
    356         //try
    357         //{
    358             Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
    359             /*Ogre::StringVector str = Ogre::ResourceGroupManager::getSingleton().getResourceGroups();
    360             for (unsigned int i = 0; i < str.size(); i++)
    361             {
    362             Ogre::ResourceGroupManager::getSingleton().loadResourceGroup(str[i]);
    363             }*/
    364         //}
    365         //catch (...)
    366         //{
    367         //    CCOUT(2) << "Error: There was a serious error when initialising the resources." << std::endl;
    368         //    throw;
    369         //}
    370354    }
    371355
     
    406390    }
    407391
     392    size_t GraphicsManager::getRenderWindowHandle()
     393    {
     394        size_t windowHnd = 0;
     395        renderWindow_->getCustomAttribute("WINDOW", &windowHnd);
     396        return windowHnd;
     397    }
     398
     399    bool GraphicsManager::isFullScreen() const
     400    {
     401        Ogre::ConfigOptionMap& options = ogreRoot_->getRenderSystem()->getConfigOptions();
     402        if (options.find("Full Screen") != options.end())
     403        {
     404            if (options["Full Screen"].currentValue == "Yes")
     405                return true;
     406            else
     407                return false;
     408        }
     409        else
     410        {
     411            COUT(0) << "Could not find 'Full Screen' render system option. Fix This!!!" << std::endl;
     412            return false;
     413        }
     414    }
     415
    408416    void GraphicsManager::printScreen()
    409417    {
  • code/trunk/src/core/GraphicsManager.h

    r3370 r5695  
    4242#include <string>
    4343#include <OgreLog.h>
     44#include <boost/scoped_ptr.hpp>
     45#include <boost/shared_ptr.hpp>
     46
    4447#include "util/Singleton.h"
    4548#include "OrxonoxClass.h"
     
    5558        friend class Singleton<GraphicsManager>;
    5659    public:
    57         GraphicsManager();
     60        GraphicsManager(bool bLoadRenderer = true);
    5861        ~GraphicsManager();
    5962
     
    6265        void update(const Clock& time);
    6366
    64         inline Ogre::Viewport* getViewport()
    65             { return this->viewport_; }
    66         inline Ogre::RenderWindow* getRenderWindow()
    67             { return this->renderWindow_; }
     67        Ogre::Viewport* getViewport()         { return this->viewport_; }
     68        Ogre::RenderWindow* getRenderWindow() { return this->renderWindow_; }
     69        size_t getRenderWindowHandle();
     70        bool isFullScreen() const;
     71
     72        void upgradeToGraphics();
     73        bool rendererLoaded() const { return renderWindow_ != NULL; }
    6874
    6975        void setCamera(Ogre::Camera* camera);
     
    7379
    7480        // OGRE initialisation
    75         void setupOgre();
     81        void loadOgreRoot();
    7682        void loadOgrePlugins();
    77         void declareResources();
    7883        void loadRenderer();
    79         void initialiseResources();
    8084
    8185        // event from Ogre::LogListener
     
    8690        void printScreen();
    8791
    88     private:
    89         Ogre::Root*         ogreRoot_;                 //!< Ogre's root
    90         Ogre::LogManager*   ogreLogger_;
     92        scoped_ptr<OgreWindowEventListener> ogreWindowEventListener_; //!< Pimpl to hide OgreWindowUtilities.h
     93#if OGRE_VERSION < 0x010600
     94        scoped_ptr<MemoryArchiveFactory>    memoryArchiveFactory_;    //!< Stores the modified particle scripts
     95#endif
     96        scoped_ptr<Ogre::LogManager>        ogreLogger_;
     97        scoped_ptr<Ogre::Root>              ogreRoot_;                //!< Ogre's root
    9198        Ogre::RenderWindow* renderWindow_;             //!< the one and only render window
    9299        Ogre::Viewport*     viewport_;                 //!< default full size viewport
    93         OgreWindowEventListener* ogreWindowEventListener_; //!< Pimpl to hide OgreWindowUtilities.h
     100
     101        // XML files for the resources
     102        shared_ptr<XMLFile> resources_;                //!< XML with resource locations
     103        shared_ptr<XMLFile> extResources_;             //!< XML with resource locations in the external path (only for dev runs)
    94104
    95105        // config values
    96         std::string         resourceFile_;             //!< resources file name
    97106        std::string         ogreConfigFile_;           //!< ogre config file name
    98         std::string         ogrePluginsFolder_;        //!< Folder where the Ogre plugins are located
     107        std::string         ogrePluginsDirectory_;     //!< Directory where the Ogre plugins are located
    99108        std::string         ogrePlugins_;              //!< Comma separated list of all plugins to load
    100109        std::string         ogreLogFile_;              //!< log file name for Ogre log messages
  • code/trunk/src/core/Identifier.cc

    r3325 r5695  
    138138        if (!this->bCreatedOneObject_ && Identifier::isCreatingHierarchy())
    139139        {
    140             // If no: We have to store the informations and initialize the Identifier
     140            // If no: We have to store the information and initialize the Identifier
    141141            COUT(4) << "*** ClassIdentifier: Register Class in " << this->getName() << "-Singleton -> Initialize Singleton." << std::endl;
    142142            if (bRootClass)
  • code/trunk/src/core/Identifier.h

    r3370 r5695  
    3131    @brief Definition of the Identifier, ClassIdentifier and SubclassIdentifier classes, implementation of the ClassIdentifier and SubclassIdentifier classes.
    3232
    33     The Identifier contains all needed informations about the class it belongs to:
     33    The Identifier contains all needed information about the class it belongs to:
    3434     - the name
    3535     - a list with all objects
     
    7373    // ###       Identifier        ###
    7474    // ###############################
    75     //! The Identifier is used to identify the class of an object and to store informations about the class.
    76     /**
    77         The Identifier contains all needed informations about the class it belongs to:
     75    //! The Identifier is used to identify the class of an object and to store information about the class.
     76    /**
     77        The Identifier contains all needed information about the class it belongs to:
    7878         - the name
    7979         - a list with all objects
     
    335335    /**
    336336        ClassIdentifier is a Singleton, which means that only one object of a given type T exists.
    337         This makes it possible to store informations about a class, sharing them with all
     337        This makes it possible to store information about a class, sharing them with all
    338338        objects of that class without defining static variables in every class.
    339339
  • code/trunk/src/core/Loader.cc

    r3370 r5695  
    2929#include "Loader.h"
    3030
     31#include <sstream>
    3132#include <tinyxml/ticpp.h>
     33#include <boost/scoped_ptr.hpp>
    3234
    3335#include "util/Debug.h"
    3436#include "util/Exception.h"
     37#include "util/StringUtils.h"
    3538#include "BaseObject.h"
    3639#include "Iterator.h"
    3740#include "ObjectList.h"
    38 #include "LuaBind.h"
     41#include "LuaState.h"
    3942#include "Namespace.h"
     43#include "Resource.h"
    4044#include "XMLFile.h"
    4145
     
    118122        Loader::currentMask_s = file->getMask() * mask;
    119123
    120         // let Lua work this out:
    121         LuaBind& lua = LuaBind::getInstance();
    122         lua.clearLuaOutput();
    123         lua.loadFile(file->getFilename(), true);
    124         lua.run();
     124        std::string xmlInput;
     125        if (file->getLuaSupport())
     126        {
     127            // Use the LuaState to replace the XML tags (calls our function)
     128            scoped_ptr<LuaState> luaState(new LuaState());
     129            luaState->setIncludeParser(&Loader::replaceLuaTags);
     130            luaState->includeFile(file->getFilename(), file->getResourceGroup(), false);
     131            xmlInput = luaState->getOutput().str();
     132        }
     133        else
     134        {
     135            shared_ptr<ResourceInfo> info = Resource::getInfo(file->getFilename(), file->getResourceGroup());
     136            if (info == NULL)
     137            {
     138                COUT(1) << "Error: Could not find XML file '" << file->getFilename() << "'." << std::endl;
     139                return false;
     140            }
     141            xmlInput = Resource::open(file->getFilename(), file->getResourceGroup())->getAsString();
     142        }
    125143
    126144        try
     
    129147            COUT(3) << "Mask: " << Loader::currentMask_s << std::endl;
    130148
    131             //ticpp::Document xmlfile(file->getFilename());
    132             //xmlfile.LoadFile();
    133             //ticpp::Element myelement(*Script::getFileString());
    134             ticpp::Document xmlfile;
    135             //xmlfile.ToDocument();
    136             xmlfile.Parse(lua.getLuaOutput(), true);
     149            ticpp::Document xmlfile(file->getFilename());
     150            xmlfile.Parse(xmlInput, true);
    137151
    138152            ticpp::Element rootElement;
     
    208222        return Loader::load(file, mask);
    209223    }
     224
     225    std::string Loader::replaceLuaTags(const std::string& text)
     226    {
     227        // chreate map with all Lua tags
     228        std::map<size_t, bool> luaTags;
     229        {
     230            size_t pos = 0;
     231            while ((pos = text.find("<?lua", pos)) != std::string::npos)
     232                luaTags[pos++] = true;
     233        }
     234        {
     235            size_t pos = 0;
     236            while ((pos = text.find("?>", pos)) != std::string::npos)
     237                luaTags[pos++] = false;
     238        }
     239
     240        // erase all tags from the map that are between two quotes
     241        {
     242            std::map<size_t, bool>::iterator it = luaTags.begin();
     243            std::map<size_t, bool>::iterator it2 = it;
     244            bool bBetweenQuotes = false;
     245            size_t pos = 0;
     246            while ((pos = getNextQuote(text, pos)) != std::string::npos)
     247            {
     248                while ((it != luaTags.end()) && (it->first < pos))
     249                {
     250                    if (bBetweenQuotes)
     251                    {
     252                        it2++;
     253                        if(it->second && !(it2->second) && it2->first < pos)
     254                            it = ++it2;
     255                        else
     256                            luaTags.erase(it++);
     257                    }
     258                    else
     259                        ++it;
     260                }
     261                bBetweenQuotes = !bBetweenQuotes;
     262                pos++;
     263            }
     264        }
     265
     266        // check whether on every opening <?lua tag a closing ?> tag follows
     267        {
     268            bool expectedValue = true;
     269            for (std::map<size_t, bool>::iterator it = luaTags.begin(); it != luaTags.end(); ++it)
     270            {
     271                if (it->second == expectedValue)
     272                    expectedValue = !expectedValue;
     273                else
     274                {
     275                    expectedValue = false;
     276                    break;
     277                }
     278            }
     279            if (!expectedValue)
     280            {
     281                COUT(2) << "Warning: Error in level file" << std::endl;
     282                // todo: errorhandling
     283                return "";
     284            }
     285        }
     286
     287        // Use a stringstream object to speed up the parsing
     288        std::ostringstream output;
     289
     290        // cut the original string into pieces and put them together with print() instead of lua tags
     291        {
     292            std::map<size_t, bool>::iterator it = luaTags.begin();
     293            bool bInPrintFunction = true;
     294            size_t start = 0;
     295            size_t end = 0;
     296
     297            do
     298            {
     299                if (it != luaTags.end())
     300                    end = (*(it++)).first;
     301                else
     302                    end = std::string::npos;
     303
     304                unsigned int equalSignCounter = 0;
     305
     306                if (bInPrintFunction)
     307                {
     308                    // count ['='[ and ]'='] and replace tags with print([[ and ]])
     309                    std::string temp = text.substr(start, end - start);
     310                    {
     311                    size_t pos = 0;
     312                    while ((pos = temp.find('[', pos)) != std::string::npos)
     313                    {
     314                        unsigned int tempCounter = 1;
     315                        size_t tempPos = pos++;
     316                        while(temp[++tempPos] == '=')
     317                        {
     318                            tempCounter++;
     319                        }
     320                        if(temp[tempPos] != '[')
     321                        {
     322                            tempCounter = 0;
     323                        }
     324                        else if(tempCounter == 0)
     325                        {
     326                            tempCounter = 1;
     327                        }
     328                        if (tempCounter > equalSignCounter)
     329                            equalSignCounter = tempCounter;
     330                        }
     331                    }
     332                    {
     333                        size_t pos = 0;
     334                        while ((pos = temp.find(']', pos)) != std::string::npos)
     335                        {
     336                            unsigned int tempCounter = 1;
     337                            size_t tempPos = pos++;
     338                            while(temp[++tempPos] == '=')
     339                            {
     340                                tempCounter++;
     341                            }
     342                            if(temp[tempPos] != ']')
     343                            {
     344                                tempCounter = 0;
     345                            }
     346                            else if(tempCounter == 0)
     347                            {
     348                                tempCounter = 1;
     349                            }
     350                            if (tempCounter > equalSignCounter)
     351                                equalSignCounter = tempCounter;
     352                        }
     353                    }
     354                    std::string equalSigns = "";
     355                    for(unsigned int i = 0; i < equalSignCounter; i++)
     356                    {
     357                        equalSigns += "=";
     358                    }
     359                    output << "print([" + equalSigns + "[" + temp + "]" + equalSigns +"])";
     360                    start = end + 5;
     361                }
     362                else
     363                {
     364                    output << text.substr(start, end - start);
     365                    start = end + 2;
     366                }
     367
     368                bInPrintFunction = !bInPrintFunction;
     369            }
     370            while (end != std::string::npos);
     371        }
     372
     373        return output.str();
     374    }
    210375}
  • code/trunk/src/core/Loader.h

    r3370 r5695  
    5555            static bool reload(const XMLFile* file, const ClassTreeMask& mask = ClassTreeMask());
    5656
     57            static std::string replaceLuaTags(const std::string& text);
     58
    5759            static ClassTreeMask currentMask_s;
    5860
  • code/trunk/src/core/TclBind.cc

    r3370 r5695  
    127127#ifdef DEPENDENCY_PACKAGE_ENABLE
    128128        if (Core::isDevelopmentRun())
    129             return (std::string(ORXONOX_DEP_LIB_PATH) + "/tcl");
     129            return (std::string(specialConfig::dependencyLibraryDirectory) + "/tcl");
    130130        else
    131131            return (Core::getRootPathString() + "lib/tcl");
  • code/trunk/src/core/TclThreadManager.cc

    r3370 r5695  
    5757
    5858    /**
    59         @brief A struct containing all informations about a Tcl-interpreter
     59        @brief A struct containing all information about a Tcl-interpreter
    6060    */
    6161    struct TclInterpreterBundle
  • code/trunk/src/core/XMLFile.h

    r3196 r5695  
    4040    {
    4141        public:
    42             XMLFile(const std::string& filename) : filename_(filename) {}
    43             XMLFile(const std::string& filename, const ClassTreeMask& mask) : filename_(filename), mask_(mask) {};
     42            XMLFile(const std::string& filename, const std::string& resourceGroup = "General")
     43                : filename_(filename)
     44                , group_(resourceGroup)
     45                , bLuaSupport_(true)
     46            { }
     47            XMLFile(const ClassTreeMask& mask, const std::string& filename, const std::string& resourceGroup = "General")
     48                : filename_(filename)
     49                , group_(resourceGroup)
     50                , mask_(mask)
     51                , bLuaSupport_(true)
     52            { }
     53
     54            void setLuaSupport(bool val) { bLuaSupport_ = val; }
    4455
    4556            const std::string& getFilename() const { return this->filename_; }
     57            const std::string& getResourceGroup() const { return this->group_; }
    4658            const ClassTreeMask& getMask() const { return this->mask_; }
     59            bool getLuaSupport() const { return this->bLuaSupport_; }
    4760
    4861        private:
    4962            std::string filename_;
     63            std::string group_;
    5064            ClassTreeMask mask_;
     65            bool bLuaSupport_; // Default is true
    5166    };
    5267}
  • code/trunk/src/core/input/Button.cc

    r3327 r5695  
    5959        nCommands_[1]=0;
    6060        nCommands_[2]=0;
    61         this->configContainer_ = 0;
    6261    }
    6362
  • code/trunk/src/core/input/InputManager.cc

    r3370 r5695  
    4141#include <boost/foreach.hpp>
    4242
     43#include "util/Convert.h"
    4344#include "util/Exception.h"
    4445#include "util/ScopeGuard.h"
     
    4950#include "core/CommandLine.h"
    5051#include "core/Functor.h"
     52#include "core/GraphicsManager.h"
    5153
    5254#include "InputBuffer.h"
     
    8284    // ##########                                        ##########
    8385    // ############################################################
    84     InputManager::InputManager(size_t windowHnd)
     86    InputManager::InputManager()
    8587        : internalState_(Bad)
    8688        , oisInputManager_(0)
    8789        , devices_(2)
    88         , windowHnd_(0)
     90        , bExclusiveMouse_(false)
    8991        , emptyState_(0)
    9092        , keyDetector_(0)
     
    9799        this->setConfigValues();
    98100
    99         this->loadDevices(windowHnd);
     101        this->loadDevices();
    100102
    101103        // Lowest priority empty InputState
     
    147149        Creates the OIS::InputMananger, the keyboard, the mouse and
    148150        the joys ticks. If either of the first two fail, this method throws an exception.
    149     @param windowHnd
    150         The window handle of the render window
    151151    @param windowWidth
    152152        The width of the render window
     
    154154        The height of the render window
    155155    */
    156     void InputManager::loadDevices(size_t windowHnd)
    157     {
    158         CCOUT(3) << "Loading input devices..." << std::endl;
     156    void InputManager::loadDevices()
     157    {
     158        CCOUT(4) << "Loading input devices..." << std::endl;
    159159
    160160        // When loading the devices they should not already be loaded
     
    164164        assert(devices_.size() == InputDeviceEnumerator::FirstJoyStick);
    165165
    166         // store handle internally so we can reload OIS
    167         windowHnd_ = windowHnd;
    168 
     166        // Fill parameter list
    169167        OIS::ParamList paramList;
    170         std::ostringstream windowHndStr;
    171 
    172         // Fill parameter list
    173         windowHndStr << static_cast<unsigned int>(windowHnd);
    174         paramList.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
     168        size_t windowHnd = GraphicsManager::getInstance().getRenderWindowHandle();
     169        paramList.insert(std::make_pair("WINDOW", multi_cast<std::string>(windowHnd)));
    175170#if defined(ORXONOX_PLATFORM_WINDOWS)
    176         //paramList.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_NONEXCLUSIVE")));
    177         //paramList.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_FOREGROUND")));
    178         //paramList.insert(std::make_pair(std::string("w32_keyboard"), std::string("DISCL_NONEXCLUSIVE")));
    179         //paramList.insert(std::make_pair(std::string("w32_keyboard"), std::string("DISCL_FOREGROUND")));
     171        paramList.insert(std::make_pair("w32_keyboard", "DISCL_NONEXCLUSIVE"));
     172        paramList.insert(std::make_pair("w32_keyboard", "DISCL_FOREGROUND"));
     173        paramList.insert(std::make_pair("w32_mouse", "DISCL_FOREGROUND"));
     174        if (bExclusiveMouse_ || GraphicsManager::getInstance().isFullScreen())
     175        {
     176            // Disable Windows key plus special keys (like play, stop, next, etc.)
     177            paramList.insert(std::make_pair("w32_keyboard", "DISCL_NOWINKEY"));
     178            paramList.insert(std::make_pair("w32_mouse", "DISCL_EXCLUSIVE"));
     179        }
     180        else
     181            paramList.insert(std::make_pair("w32_mouse", "DISCL_NONEXCLUSIVE"));
    180182#elif defined(ORXONOX_PLATFORM_LINUX)
    181         paramList.insert(std::make_pair(std::string("XAutoRepeatOn"), std::string("true")));
    182         paramList.insert(std::make_pair(std::string("x11_mouse_grab"), "true"));
    183         paramList.insert(std::make_pair(std::string("x11_mouse_hide"), "true"));
    184         bool kbNoGrab;
    185         CommandLine::getValue("keyboard_no_grab", &kbNoGrab);
    186         if (kbNoGrab)
    187             paramList.insert(std::make_pair(std::string("x11_keyboard_grab"), std::string("false")));
     183        // Enabling this is probably a bad idea, but whenever orxonox crashes, the setting stays on
     184        // Trouble might be that the Pressed event occurs a bit too often...
     185        paramList.insert(std::make_pair("XAutoRepeatOn", "true"));
     186
     187        if (bExclusiveMouse_ || GraphicsManager::getInstance().isFullScreen())
     188        {
     189            if (CommandLine::getValue("keyboard_no_grab").getBool())
     190                paramList.insert(std::make_pair("x11_keyboard_grab", "false"));
     191            else
     192                paramList.insert(std::make_pair("x11_keyboard_grab", "true"));
     193            paramList.insert(std::make_pair("x11_mouse_grab",  "true"));
     194            paramList.insert(std::make_pair("x11_mouse_hide", "true"));
     195        }
    188196        else
    189             paramList.insert(std::make_pair(std::string("x11_keyboard_grab"), std::string("true")));
     197        {
     198            paramList.insert(std::make_pair("x11_keyboard_grab", "false"));
     199            paramList.insert(std::make_pair("x11_mouse_grab",  "false"));
     200            paramList.insert(std::make_pair("x11_mouse_hide", "false"));
     201        }
    190202#endif
    191203
     
    212224        }
    213225
    214         // TODO: Remove the two parameters
    215226        this->loadMouse();
    216227        this->loadJoySticks();
     
    219230        this->updateActiveStates();
    220231
    221         CCOUT(3) << "Input devices loaded." << std::endl;
     232        CCOUT(4) << "Input devices loaded." << std::endl;
    222233    }
    223234
     
    275286    InputManager::~InputManager()
    276287    {
    277         CCOUT(4) << "Destroying..." << std::endl;
     288        CCOUT(3) << "Destroying..." << std::endl;
    278289
    279290        // Destroy calibrator helper handler and state
     
    293304            this->destroyDevices();
    294305
    295         CCOUT(4) << "Destruction complete." << std::endl;
     306        CCOUT(3) << "Destruction complete." << std::endl;
    296307    }
    297308
     
    304315    void InputManager::destroyDevices()
    305316    {
    306         CCOUT(3) << "Destroying devices..." << std::endl;
     317        CCOUT(4) << "Destroying devices..." << std::endl;
    307318
    308319        BOOST_FOREACH(InputDevice*& device, devices_)
     
    336347
    337348        internalState_ |= Bad;
    338         CCOUT(3) << "Destroyed devices." << std::endl;
     349        CCOUT(4) << "Destroyed devices." << std::endl;
    339350    }
    340351
     
    365376
    366377        this->destroyDevices();
    367         this->loadDevices(windowHnd_);
     378        this->loadDevices();
    368379
    369380        internalState_ &= ~Bad;
    370381        internalState_ &= ~ReloadRequest;
    371         CCOUT(3) << "Reloading complete." << std::endl;
     382        CCOUT(4) << "Reloading complete." << std::endl;
    372383    }
    373384
     
    481492    void InputManager::updateActiveStates()
    482493    {
     494        assert((internalState_ & InputManager::Ticking) == 0);
    483495        // temporary resize
    484496        for (unsigned int i = 0; i < devices_.size(); ++i)
     
    512524        for (std::set<InputState*>::const_iterator it = tempSet.begin();it != tempSet.end(); ++it)
    513525            activeStatesTicked_.push_back(*it);
     526
     527        // Check whether we have to change the mouse mode
     528        std::vector<InputState*>& mouseStates = devices_[InputDeviceEnumerator::Mouse]->getStateListRef();
     529        if (mouseStates.empty() && bExclusiveMouse_ ||
     530            !mouseStates.empty() && mouseStates.front()->getIsExclusiveMouse() != bExclusiveMouse_)
     531        {
     532            bExclusiveMouse_ = !bExclusiveMouse_;
     533            if (!GraphicsManager::getInstance().isFullScreen())
     534                this->reloadInternal();
     535        }
    514536    }
    515537
     
    556578    }
    557579
    558     // ############################################################
    559     // #####                    Iput States                   #####
     580    std::pair<int, int> InputManager::getMousePosition() const
     581    {
     582        Mouse* mouse = static_cast<Mouse*>(devices_[InputDeviceEnumerator::Mouse]);
     583        if (mouse != NULL)
     584        {
     585            const OIS::MouseState state = mouse->getOISDevice()->getMouseState();
     586            return std::make_pair(state.X.abs, state.Y.abs);
     587        }
     588        else
     589            return std::make_pair(0, 0);
     590    }
     591
     592    // ############################################################
     593    // #####                    Input States                  #####
    560594    // ##########                                        ##########
    561595    // ############################################################
  • code/trunk/src/core/input/InputManager.h

    r3370 r5695  
    8484            the constructor fails with an std::exception.
    8585        */
    86         InputManager(size_t windowHnd);
     86        InputManager();
    8787        //! Destroys all devices AND all input states!
    8888        ~InputManager();
     
    167167            { return devices_.size() - InputDeviceEnumerator::FirstJoyStick; }
    168168        //! Returns a pointer to the OIS InputManager. Only you if you know what you're doing!
    169         OIS::InputManager* getOISInputManager()
    170             { return this->oisInputManager_; }
     169        OIS::InputManager* getOISInputManager() { return this->oisInputManager_; }
     170        std::pair<int, int> getMousePosition() const;
    171171
    172172    private: // functions
     
    175175
    176176        // Intenal methods
    177         void loadDevices(size_t windowHnd);
     177        void loadDevices();
    178178        void loadMouse();
    179179        void loadJoySticks();
     
    193193        OIS::InputManager*                  oisInputManager_;      //!< OIS input manager
    194194        std::vector<InputDevice*>           devices_;              //!< List of all input devices (keyboard, mouse, joy sticks)
    195         // TODO: Get this from the GraphicsManager during reload
    196         size_t                              windowHnd_;            //!< Render window handle (used to reload the InputManager)
     195        bool                                bExclusiveMouse_;      //!< Currently applied mouse mode
    197196
    198197        // some internally handled states and handlers
  • code/trunk/src/core/input/InputState.cc

    r3327 r5695  
    3737        , bAlwaysGetsInput_(bAlwaysGetsInput)
    3838        , bTransparent_(bTransparent)
     39        , bExclusiveMouse_(true)
    3940        , bExpired_(true)
    4041        , handlers_(2)
  • code/trunk/src/core/input/InputState.h

    r3327 r5695  
    7575          not influence ony other InputState at all.
    7676
    77         Priorities
    78         **********
     77    @par Priorities
    7978        Every InputState has a priority when on the stack, but mostly this
    8079        priority is dynamic (InputStatePriority::Dynamic) which means that a state
     
    8382        a high priority (InputStatePriority::HighPriority). These 'special' ones
    8483        are used for features like the KeyDetector or the console. Use with care!
     84
     85    @par Exclusive/Non-Exclusive mouse Mode
     86        You can select a specific mouse mode that tells whether the application
     87        should have exclusive accessto it or not.
     88        When in non-exclusive mode, you can move the mouse out of the window
     89        like with any other normal window (only for windowed mode!).
     90        The setting is dictated by the topmost InputState that gets mouse events.
    8591    */
    8692    class _CoreExport InputState : public JoyStickQuantityListener
     
    114120        void setHandler        (InputHandler* handler);
    115121
     122        void setIsExclusiveMouse(bool value) { bExclusiveMouse_ = value; this->bExpired_ = true; }
     123        bool getIsExclusiveMouse() const { return bExclusiveMouse_; }
     124
    116125        //! Returns the name of the state (which is unique!)
    117126        const std::string& getName() const { return name_; }
     
    165174        const bool                  bAlwaysGetsInput_;      //!< See class declaration for explanation
    166175        const bool                  bTransparent_;          //!< See class declaration for explanation
     176        bool                        bExclusiveMouse_;       //!< See class declaration for explanation
    167177        int                         priority_;              //!< Current priority (might change)
    168178        bool                        bExpired_;              //!< See hasExpired()
  • code/trunk/src/core/input/KeyBinder.cc

    r3327 r5695  
    5555        mousePosition_[0] = 0;
    5656        mousePosition_[1] = 0;
    57 
    58         joyStickButtons_.reserve(1000);
    59         joyStickAxes_.reserve(1000);
    6057
    6158        RegisterRootObject(KeyBinder);
     
    167164            {
    168165                for (unsigned int i = 0; i < JoyStickButtonCode::numberOfButtons; ++i)
    169                     joyStickButtons_[iDev][i].readConfigValue(this->configFile_);
     166                    (*joyStickButtons_[iDev])[i].readConfigValue(this->configFile_);
    170167                for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; ++i)
    171                     joyStickAxes_[iDev][i].readConfigValue(this->configFile_);
     168                    (*joyStickAxes_[iDev])[i].readConfigValue(this->configFile_);
    172169            }
    173170        }
     
    179176    void KeyBinder::initialiseJoyStickBindings()
    180177    {
     178        while (joyStickAxes_.size() < joySticks_.size())
     179            joyStickAxes_.push_back(shared_ptr<JoyStickAxisVector>(new JoyStickAxisVector()));
     180        while (joyStickButtons_.size() < joySticks_.size())
     181            joyStickButtons_.push_back(shared_ptr<JoyStickButtonVector>(new JoyStickButtonVector()));
     182        // For the case the new size is smaller
    181183        this->joyStickAxes_.resize(joySticks_.size());
    182184        this->joyStickButtons_.resize(joySticks_.size());
     
    189191            for (unsigned int i = 0; i < JoyStickButtonCode::numberOfButtons; i++)
    190192            {
    191                 joyStickButtons_[iDev][i].name_ = JoyStickButtonCode::ByString[i];
    192                 joyStickButtons_[iDev][i].paramCommandBuffer_ = &paramCommandBuffer_;
    193                 joyStickButtons_[iDev][i].groupName_ = "JoyStickButtons_" + deviceName;
     193                (*joyStickButtons_[iDev])[i].name_ = JoyStickButtonCode::ByString[i];
     194                (*joyStickButtons_[iDev])[i].paramCommandBuffer_ = &paramCommandBuffer_;
     195                (*joyStickButtons_[iDev])[i].groupName_ = "JoyStickButtons_" + deviceName;
    194196            }
    195197            // joy stick axes
    196198            for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; i++)
    197199            {
    198                 joyStickAxes_[iDev][i].name_ = JoyStickAxisCode::ByString[i / 2];
     200                (*joyStickAxes_[iDev])[i].name_ = JoyStickAxisCode::ByString[i / 2];
    199201                if (i & 1)
    200                     joyStickAxes_[iDev][i].name_ += "Pos";
     202                    (*joyStickAxes_[iDev])[i].name_ += "Pos";
    201203                else
    202                     joyStickAxes_[iDev][i].name_ += "Neg";
    203                 joyStickAxes_[iDev][i].paramCommandBuffer_ = &paramCommandBuffer_;
    204                 joyStickAxes_[iDev][i].groupName_ = "JoyStickAxes_" + deviceName;
     204                    (*joyStickAxes_[iDev])[i].name_ += "Neg";
     205                (*joyStickAxes_[iDev])[i].paramCommandBuffer_ = &paramCommandBuffer_;
     206                (*joyStickAxes_[iDev])[i].groupName_ = "JoyStickAxes_" + deviceName;
    205207            }
    206208        }
     
    226228        {
    227229            for (unsigned int i = 0; i < JoyStickButtonCode::numberOfButtons; i++)
    228                 allButtons_[joyStickButtons_[iDev][i].groupName_ + "." + joyStickButtons_[iDev][i].name_] = &(joyStickButtons_[iDev][i]);
     230                allButtons_[(*joyStickButtons_[iDev])[i].groupName_ + "." + (*joyStickButtons_[iDev])[i].name_] = &((*joyStickButtons_[iDev])[i]);
    229231            for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; i++)
    230232            {
    231                 allButtons_[joyStickAxes_[iDev][i].groupName_ + "." + joyStickAxes_[iDev][i].name_] = &(joyStickAxes_[iDev][i]);
    232                 allHalfAxes_.push_back(&(joyStickAxes_[iDev][i]));
     233                allButtons_[(*joyStickAxes_[iDev])[i].groupName_ + "." + (*joyStickAxes_[iDev])[i].name_] = &((*joyStickAxes_[iDev])[i]);
     234                allHalfAxes_.push_back(&((*joyStickAxes_[iDev])[i]));
    233235            }
    234236        }
     
    303305            for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; i++)
    304306            {
    305                 joyStickAxes_[iDev][i].absVal_ = 0.0f;
    306                 joyStickAxes_[iDev][i].relVal_ = 0.0f;
     307                (*joyStickAxes_[iDev])[i].absVal_ = 0.0f;
     308                (*joyStickAxes_[iDev])[i].relVal_ = 0.0f;
    307309            }
    308310        }
     
    366368        for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; i++)
    367369        {
    368             tickHalfAxis(joyStickAxes_[joyStick][i]);
     370            tickHalfAxis((*joyStickAxes_[joyStick])[i]);
    369371        }
    370372    }
     
    481483    {
    482484        int i = axisID * 2;
    483         JoyStickAxisVector& axis = joyStickAxes_[device];
     485        JoyStickAxisVector& axis = *joyStickAxes_[device];
    484486        if (value < 0)
    485487        {
  • code/trunk/src/core/input/KeyBinder.h

    r3327 r5695  
    4141#include <string>
    4242#include <vector>
     43#include <boost/shared_ptr.hpp>
    4344
    4445#include "InputHandler.h"
     
    115116        };
    116117        //! Actual key bindings for joy stick buttons
    117         std::vector<JoyStickButtonVector> joyStickButtons_;
     118        std::vector<shared_ptr<JoyStickButtonVector> > joyStickButtons_;
    118119        //! Helper class to use something like std:vector<HalfAxis[48]>
    119120        struct JoyStickAxisVector
     
    123124        };
    124125        //! Actual key bindings for joy stick axes (and sliders)
    125         std::vector<JoyStickAxisVector> joyStickAxes_;
     126        std::vector<shared_ptr<JoyStickAxisVector> > joyStickAxes_;
    126127
    127128        //! Pointer map with all Buttons, including half axes
     
    191192
    192193    inline void KeyBinder::buttonPressed (unsigned int device, JoyStickButtonCode::ByEnum button)
    193     { joyStickButtons_[device][button].execute(KeybindMode::OnPress); }
     194    { (*joyStickButtons_[device])[button].execute(KeybindMode::OnPress); }
    194195
    195196    inline void KeyBinder::buttonReleased(unsigned int device, JoyStickButtonCode::ByEnum button)
    196     { joyStickButtons_[device][button].execute(KeybindMode::OnRelease); }
     197    { (*joyStickButtons_[device])[button].execute(KeybindMode::OnRelease); }
    197198
    198199    inline void KeyBinder::buttonHeld    (unsigned int device, JoyStickButtonCode::ByEnum button)
    199     { joyStickButtons_[device][button].execute(KeybindMode::OnHold); }
     200    { (*joyStickButtons_[device])[button].execute(KeybindMode::OnHold); }
    200201
    201202    inline void KeyBinder::allDevicesUpdated(float dt)
  • code/trunk/src/core/input/KeyDetector.cc

    r3327 r5695  
    7070    {
    7171        KeyBinder::JoyStickQuantityChanged(joyStickList);
    72         setCallbackCommand(callbackCommand_);
     72        if (!callbackCommand_.empty())
     73            setCallbackCommand(callbackCommand_);
    7374    }
    7475}
Note: See TracChangeset for help on using the changeset viewer.