Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/orxonox/gui/GUIManager.cc @ 3320

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

Console should now be visible again in the main menu (and FPS text as well).

  • Property svn:eol-style set to native
File size: 14.3 KB
RevLine 
[1638]1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      Reto Grieder
[2896]24 *      Benjamin Knecht
[1638]25 *   Co-authors:
[3196]26 *      ...
[1638]27 *
28 */
29
30/**
[3196]31@file
32@brief
33    Implementation of the GUIManager class.
[1638]34*/
35
36#include "GUIManager.h"
37
[3196]38extern "C" {
39#include <lua.h>
40}
[2710]41#include <CEGUIDefaultLogger.h>
[3196]42#include <CEGUIExceptions.h>
43#include <CEGUIInputEvent.h>
44#include <CEGUIResourceProvider.h>
45#include <CEGUISystem.h>
[2710]46#include <ogreceguirenderer/OgreCEGUIRenderer.h>
[3196]47
[2710]48#include "SpecialConfig.h" // Configures the macro below
49#ifdef CEGUILUA_USE_INTERNAL_LIBRARY
50#   include <ceguilua/CEGUILua.h>
51#else
52#   include <CEGUILua.h>
53#endif
54
[3280]55#include "util/Debug.h"
[1764]56#include "util/Exception.h"
[3280]57#include "util/OrxAssert.h"
[1638]58#include "core/Core.h"
[2896]59#include "core/Clock.h"
[2710]60#include "ToluaBindCore.h"
61#include "ToluaBindOrxonox.h"
[3008]62#include "core/Loader.h"
[1638]63
64namespace orxonox
65{
[3280]66    class CEGUILogger : public CEGUI::DefaultLogger
67    {
68    public:
69            void logEvent(const CEGUI::String& message, CEGUI::LoggingLevel level = CEGUI::Standard)
70        {
71            int orxonoxLevel;
72            switch (level)
73            {
74                case CEGUI::Errors:      orxonoxLevel = 1; break;
75                case CEGUI::Warnings:    orxonoxLevel = 2; break;
76                case CEGUI::Standard:    orxonoxLevel = 4; break;
77                case CEGUI::Informative: orxonoxLevel = 5; break;
78                case CEGUI::Insane:      orxonoxLevel = 6; break;
79                default: OrxAssert(false, "CEGUI log level out of range, inpect immediately!");
80            }
81            OutputHandler::getOutStream().setOutputLevel(orxonoxLevel)
82                << "CEGUI: " << message << std::endl;
83
84            CEGUI::DefaultLogger::logEvent(message, level);
85        }
86    };
87
[3196]88    static CEGUI::MouseButton convertButton(MouseButtonCode::ByEnum button);
[1646]89    GUIManager* GUIManager::singletonRef_s = 0;
90
[1638]91    GUIManager::GUIManager()
[2896]92        : renderWindow_(0)
[1638]93        , guiRenderer_(0)
94        , resourceProvider_(0)
95        , scriptModule_(0)
96        , guiSystem_(0)
97        , state_(Uninitialised)
98    {
[1646]99        assert(singletonRef_s == 0);
100        singletonRef_s = this;
[1638]101    }
102
[2896]103    /**
104    @brief
105        Deconstructor of the GUIManager
106
107        Basically shuts down CEGUI and destroys the Lua engine and afterwards the interface to the Ogre engine.
108    */
[1638]109    GUIManager::~GUIManager()
110    {
[1646]111        if (guiSystem_)
112            delete guiSystem_;
113
114        if (scriptModule_)
115        {
116            // destroy our own tolua interfaces
[3034]117            lua_pushnil(luaState_);
118            lua_setglobal(luaState_, "Orxonox");
119            lua_pushnil(luaState_);
120            lua_setglobal(luaState_, "Core");
[2662]121            delete scriptModule_;
[1646]122        }
123
124        if (guiRenderer_)
125            delete guiRenderer_;
126
127        singletonRef_s = 0;
[1638]128    }
129
[2896]130    /**
131    @brief
132        Initialises the GUIManager by starting up CEGUI
133    @param renderWindow
134        Ogre's render window. Without this, the GUI cannot be displayed.
135    @return true if success, otherwise false
136
137        Before this call the GUIManager won't do anything, but can be accessed.
138
139        Creates the interface to Ogre, sets up the CEGUI renderer and the Lua script module together with the Lua engine.
140        The log is set up and connected to the CEGUILogger.
141        After Lua setup tolua++-elements are linked to Lua-state to give Lua access to C++-code.
142        Finally initial Lua code is executed (maybe we can do this with the CEGUI startup script automatically).
143    */
[1686]144    bool GUIManager::initialise(Ogre::RenderWindow* renderWindow)
[1638]145    {
146        using namespace CEGUI;
147        if (state_ == Uninitialised)
148        {
[1776]149            COUT(3) << "Initialising CEGUI." << std::endl;
[1638]150
151            try
152            {
[1686]153                // save the render window
154                renderWindow_ = renderWindow;
[1638]155
156                // Note: No SceneManager specified yet
[3287]157                this->guiRenderer_ = new OgreCEGUIRenderer(renderWindow_, Ogre::RENDER_QUEUE_OVERLAY, false, 3000);
[1638]158                this->resourceProvider_ = guiRenderer_->createResourceProvider();
159                this->resourceProvider_->setDefaultResourceGroup("GUI");
[1776]160
[1638]161                // setup scripting
162                this->scriptModule_ = new LuaScriptModule();
[1646]163                this->luaState_ = this->scriptModule_->getLuaState();
[1638]164
[2710]165                // Create our own logger to specify the filepath
[3280]166                this->ceguiLogger_ = new CEGUILogger();
[3196]167                this->ceguiLogger_->setLogFilename(Core::getLogPathString() + "cegui.log");
[2710]168                // set the log level according to ours (translate by subtracting 1)
169                this->ceguiLogger_->setLoggingLevel(
170                    (LoggingLevel)(Core::getSoftDebugLevel(OutputHandler::LD_Logfile) - 1));
171
[1638]172                // create the CEGUI system singleton
173                this->guiSystem_ = new System(this->guiRenderer_, this->resourceProvider_, 0, this->scriptModule_);
[1776]174
[1638]175                // do this after 'new CEGUI::Sytem' because that creates the lua state in the first place
176                tolua_Core_open(this->scriptModule_->getLuaState());
177                tolua_Orxonox_open(this->scriptModule_->getLuaState());
178
[2896]179                // initialise the basic lua code
180                loadLuaCode();
[1638]181            }
182            catch (CEGUI::Exception& ex)
183            {
[1653]184#if CEGUI_VERSION_MAJOR == 0 && CEGUI_VERSION_MINOR < 6
[1645]185                throw GeneralException(ex.getMessage().c_str());
186#else
[1638]187                throw GeneralException(ex.getMessage().c_str(), ex.getLine(),
188                    ex.getFileName().c_str(), ex.getName().c_str());
[1645]189#endif
[1638]190            }
191
192            state_ = Ready;
193        }
[1776]194
[1638]195        return true;
196    }
197
[2896]198    /**
199    @brief
200        Calls main Lua script
201    @todo
202        Replace loadGUI.lua with loadGUI_2.lua after merging this back to trunk.
203        However CEGUI is able to execute a startup script. We could maybe put this call in this startup code.
204
205        This function calls the main Lua script for our GUI.
206
207        Additionally we set the datapath variable in Lua. This is needed so Lua can access the data used for the GUI.
208    */
209    void GUIManager::loadLuaCode()
[2790]210    {
[2896]211        try
[2790]212        {
[2896]213            // set datapath for GUI data
214            lua_pushfstring(this->scriptModule_->getLuaState(), Core::getMediaPathString().c_str());
215            lua_setglobal(this->scriptModule_->getLuaState(), "datapath");
[2957]216            // call main Lua script
217            this->scriptModule_->executeScriptFile("loadGUI_3.lua", "GUI");
[2896]218        }
219        catch (CEGUI::Exception& ex)
220        {
[2790]221#if CEGUI_VERSION_MINOR < 6
[2896]222            throw GeneralException(ex.getMessage().c_str());
[2790]223#else
[2896]224            throw GeneralException(ex.getMessage().c_str(), ex.getLine(),
225                ex.getFileName().c_str(), ex.getName().c_str());
[2790]226#endif
227        }
228    }
229
[2896]230    /**
231    @brief
232        used to tick the GUI
233    @param time
234        clock which provides time value for the GUI System
235
236        Ticking the GUI means updating it with a certain regularity.
237        The elapsed time since the last call is given in the time value provided by the clock.
238        This time value is then used to provide a fluent animation of the GUI.
239    */
240    void GUIManager::update(const Clock& time)
[1638]241    {
[2896]242        assert(guiSystem_);
243        guiSystem_->injectTimePulse(time.getDeltaTime());
244    }
[1638]245
[2896]246    /**
247    @brief
248        Executes Lua code
249    @param str
250        reference to string object holding the Lua code which is to be executed
[1638]251
[2896]252        This function gives total access to the GUI. You can execute ANY Lua code here.
253    */
254    void GUIManager::executeCode(const std::string& str)
255    {
[1638]256        try
257        {
[2896]258            this->scriptModule_->executeString(str);
[1638]259        }
260        catch (CEGUI::Exception& ex)
261        {
[2896]262            COUT(2) << "CEGUI Error: \"" << ex.getMessage() << "\" while executing code \"" << str << "\"" << std::endl;
[1638]263        }
264    }
265
[2896]266    /**
[3008]267
268    */
269    void GUIManager::getLevelList()
270    {
271        lua_State* L = this->scriptModule_->getLuaState();
272        lua_newtable(L);
273
274        std::vector<std::string> list = Loader::getLevelList();
275
276        int j = 1;
277        for (std::vector<std::string>::iterator i = list.begin(); i != list.end(); i++)
278        {
279            lua_pushnumber(L,j);
280            lua_pushstring(L,i->c_str());
281            lua_settable(L,-3);
282            j++;
283        }
284        lua_setglobal(L, "levellist");
285    }
286
287    /**
[2896]288    @brief
[2963]289        Registers a GUIOverlay with the GUIManager so that the GUIOverlay can be accessed by it's name through the GUIManager.
290    @param name
291        The name of the GUI.
292    @param overlay
293        A pointer to the GUIOverlay of the GUI.
294    @return
295        Returns false if the Overlay was already present.
296    */
[3196]297    bool GUIManager::registerOverlay(const std::string& name, GUIOverlay* overlay)
[2963]298    {
299        return (this->guiOverlays_.insert(std::pair<std::string, GUIOverlay*>(name, overlay))).second;
300    }
301
302    /**
303    @brief
304        Get the GUIOverlay of the GUI with the given name.
305    @param name
306        The name of the GUI.
307    @return
308        Returns a pointer to the GUIOverlay.
309    */
[3196]310    GUIOverlay* GUIManager::getOverlay(const std::string& name)
[2963]311    {
312        return (this->guiOverlays_.find(name))->second;
313    }
314
315    /**
316    @brief
[2896]317        Tells the GUIManager which SceneManager to use
318    @param camera
319        The current camera on which the GUI should be displayed on.
320
321        In fact the GUIManager needs the SceneManager and not the Camera to display the GUI.
322        This means the GUI is not bound to a camera but rather to the SceneManager.
323        Hidding the GUI when needed can therefore not be solved by just NOT setting the current camera.
324    */
325    void GUIManager::setCamera(Ogre::Camera* camera)
[1638]326    {
[2927]327        if (camera == NULL)
328            this->guiRenderer_->setTargetSceneManager(0);
329        else
330            this->guiRenderer_->setTargetSceneManager(camera->getSceneManager());
[2896]331    }
332
333    /**
334    @brief
335        Displays specified GUI on screen
336    @param name
337        The name of the GUI
338
339        The function executes the Lua function with the same name in case the GUIManager is ready.
340        For more details check out loadGUI_2.lua where the function presides.
341    */
342    void GUIManager::showGUI(const std::string& name)
343    {
[1638]344        if (state_ != Uninitialised)
345        {
[2896]346            //COUT(3) << "Loading GUI " << name << std::endl;
[1638]347            try
348            {
[2896]349                this->scriptModule_->executeString(std::string("showGUI(\"") + name + "\")");
[1638]350            }
351            catch (CEGUI::Exception& ex)
352            {
353                COUT(2) << "Error while executing lua script. Message:\n" << ex.getMessage() << std::endl;
354            }
355            catch (...)
356            {
357                COUT(2) << "Could show a menu due to unknown reasons." << std::endl;
358            }
359        }
360        else
361        {
362            COUT(2) << "Warning: GUI Manager not yet initialised, cannot load a GUI" << std::endl;
363        }
364    }
365
[3196]366    void GUIManager::keyPressed(const KeyEvent& evt)
367    {
368        guiSystem_->injectKeyDown(evt.key); guiSystem_->injectChar(evt.text);
369    }
370    void GUIManager::keyReleased(const KeyEvent& evt)
371    {
372        guiSystem_->injectKeyUp(evt.key);
373    }
374
[2896]375    /**
376    @brief
377        Function receiving a mouse button pressed event.
378    @param id
379        ID of the mouse button which got pressed
[1638]380
[2896]381        This function is inherited by MouseHandler and injects the event into CEGUI.
382        It is for CEGUI to process the event.
383    */
[1887]384    void GUIManager::mouseButtonPressed(MouseButtonCode::ByEnum id)
[1638]385    {
386        try
387        {
388            guiSystem_->injectMouseButtonDown(convertButton(id));
389        }
390        catch (CEGUI::ScriptException& ex)
391        {
392            // We simply ignore the exception and proceed
393            COUT(1) << ex.getMessage() << std::endl;
394        }
395    }
396
[2896]397    /**
398    @brief
399        Function receiving a mouse button released event.
400    @param id
401        ID of the mouse button which got released
402
403        This function is inherited by MouseHandler and injects the event into CEGUI.
404        It is for CEGUI to process the event.
405    */
[1887]406    void GUIManager::mouseButtonReleased(MouseButtonCode::ByEnum id)
[1638]407    {
408        try
409        {
410            guiSystem_->injectMouseButtonUp(convertButton(id));
411        }
412        catch (CEGUI::ScriptException& ex)
413        {
414            // We simply ignore the exception and proceed
415            COUT(1) << ex.getMessage() << std::endl;
416        }
417    }
418
[3196]419    void GUIManager::mouseMoved(IntVector2 abs, IntVector2 rel, IntVector2 clippingSize)
420    {
421        guiSystem_->injectMouseMove(static_cast<float>(rel.x), static_cast<float>(rel.y));
422    }
423    void GUIManager::mouseScrolled(int abs, int rel)
424    {
425        guiSystem_->injectMouseWheelChange(static_cast<float>(rel));
426    }
427
[2896]428    /**
429    @brief
430        converts mouse event code to CEGUI event code
431    @param button
432        code of the mouse button as we use it in Orxonox
433    @return
434        code of the mouse button as it is used by CEGUI
[1638]435
[2896]436        Simple convertion from mouse event code in Orxonox to the one used in CEGUI.
437     */
[3196]438    static inline CEGUI::MouseButton convertButton(MouseButtonCode::ByEnum button)
[1638]439    {
440        switch (button)
441        {
[1887]442        case MouseButtonCode::Left:
[1638]443            return CEGUI::LeftButton;
444
[1887]445        case MouseButtonCode::Right:
[1638]446            return CEGUI::RightButton;
447
[1887]448        case MouseButtonCode::Middle:
[1638]449            return CEGUI::MiddleButton;
450
[1887]451        case MouseButtonCode::Button3:
[1638]452            return CEGUI::X1Button;
453
[1887]454        case MouseButtonCode::Button4:
[1638]455            return CEGUI::X2Button;
456
457        default:
458            return CEGUI::NoButton;
459        }
460    }
461}
Note: See TracBrowser for help on using the repository browser.