Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/resource/src/orxonox/gui/GUIManager.cc @ 3340

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

Generalised use of tolua interfaces a bit: GSRoot now adds the interface functions to LuaBind which supports two new functions: openToluaInterfaces and closeToluaInterfaces. Both accept a lua state and can therefore be used to inject our own tolua bindings (the GUIManager makes use of that).
There's also something new: When loading a level, you could now use the tolua bindings from Orxonox as well (not just those from Core).

  • Property svn:eol-style set to native
File size: 11.1 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      Reto Grieder
24 *      Benjamin Knecht
25 *   Co-authors:
26 *      ...
27 *
28 */
29
30/**
31@file
32@brief
33    Implementation of the GUIManager class.
34*/
35
36#include "GUIManager.h"
37
38#include <memory>
39extern "C" {
40#include <lua.h>
41}
42#include <CEGUIDefaultLogger.h>
43#include <CEGUIExceptions.h>
44#include <CEGUIInputEvent.h>
45#include <CEGUIResourceProvider.h>
46#include <CEGUISystem.h>
47#include <ogreceguirenderer/OgreCEGUIRenderer.h>
48
49#include "SpecialConfig.h" // Configures the macro below
50#ifdef CEGUILUA_USE_INTERNAL_LIBRARY
51#   include <ceguilua/CEGUILua.h>
52#else
53#   include <CEGUILua.h>
54#endif
55
56#include "util/Debug.h"
57#include "util/Exception.h"
58#include "util/OrxAssert.h"
59#include "core/Core.h"
60#include "core/Clock.h"
61#include "core/LuaBind.h"
62
63namespace orxonox
64{
65    class CEGUILogger : public CEGUI::DefaultLogger
66    {
67    public:
68            void logEvent(const CEGUI::String& message, CEGUI::LoggingLevel level = CEGUI::Standard)
69        {
70            int orxonoxLevel = CEGUI::Standard;
71            switch (level)
72            {
73                case CEGUI::Errors:      orxonoxLevel = 1; break;
74                case CEGUI::Warnings:    orxonoxLevel = 2; break;
75                case CEGUI::Standard:    orxonoxLevel = 4; break;
76                case CEGUI::Informative: orxonoxLevel = 5; break;
77                case CEGUI::Insane:      orxonoxLevel = 6; break;
78                default: OrxAssert(false, "CEGUI log level out of range, inpect immediately!");
79            }
80            OutputHandler::getOutStream().setOutputLevel(orxonoxLevel)
81                << "CEGUI: " << message << std::endl;
82
83            CEGUI::DefaultLogger::logEvent(message, level);
84        }
85    };
86
87    static CEGUI::MouseButton convertButton(MouseButtonCode::ByEnum button);
88
89    GUIManager* GUIManager::singletonRef_s = 0;
90
91    /**
92    @brief
93        Constructs the GUIManager by starting up CEGUI
94
95        Creates the interface to Ogre, sets up the CEGUI renderer and the Lua script module together with the Lua engine.
96        The log is set up and connected to the CEGUILogger.
97        After Lua setup tolua++-elements are linked to Lua-state to give Lua access to C++-code.
98        Finally initial Lua code is executed (maybe we can do this with the CEGUI startup script automatically).
99    @param renderWindow
100        Ogre's render window. Without this, the GUI cannot be displayed.
101    @return true if success, otherwise false
102    */
103    GUIManager::GUIManager(Ogre::RenderWindow* renderWindow)
104        : renderWindow_(renderWindow)
105        , resourceProvider_(0)
106    {
107        assert(singletonRef_s == 0);
108        singletonRef_s = this;
109
110        using namespace CEGUI;
111
112        COUT(3) << "Initialising CEGUI." << std::endl;
113
114        try
115        {
116            // Note: No SceneManager specified yet
117            guiRenderer_.reset(new OgreCEGUIRenderer(renderWindow_, Ogre::RENDER_QUEUE_OVERLAY, false, 3000));
118            resourceProvider_ = guiRenderer_->createResourceProvider();
119            resourceProvider_->setDefaultResourceGroup("GUI");
120
121            // setup scripting
122            scriptModule_.reset(new LuaScriptModule());
123            luaState_ = scriptModule_->getLuaState();
124
125            // Create our own logger to specify the filepath
126            std::auto_ptr<CEGUILogger> ceguiLogger(new CEGUILogger());
127            ceguiLogger->setLogFilename(Core::getLogPathString() + "cegui.log");
128            // set the log level according to ours (translate by subtracting 1)
129            ceguiLogger->setLoggingLevel(
130                static_cast<LoggingLevel>(Core::getSoftDebugLevel(OutputHandler::LD_Logfile) - 1));
131            this->ceguiLogger_ = ceguiLogger.release();
132
133            // create the CEGUI system singleton
134            guiSystem_.reset(new System(guiRenderer_.get(), resourceProvider_, 0, scriptModule_.get()));
135
136            // do this after 'new CEGUI::Sytem' because that creates the lua state in the first place
137            LuaBind::getInstance().openToluaInterfaces(this->luaState_);
138
139            // initialise the basic lua code
140            this->loadLuaCode();
141        }
142        catch (CEGUI::Exception& ex)
143        {
144#if CEGUI_VERSION_MAJOR == 0 && CEGUI_VERSION_MINOR < 6
145            throw GeneralException(ex.getMessage().c_str());
146#else
147            throw GeneralException(ex.getMessage().c_str(), ex.getLine(),
148                ex.getFileName().c_str(), ex.getName().c_str());
149#endif
150        }
151    }
152
153    /**
154    @brief
155        Destructor of the GUIManager
156
157        Basically shuts down CEGUI (member smart pointers) but first unloads our Tolua modules.
158    */
159    GUIManager::~GUIManager()
160    {
161        // destroy our own tolua interfaces
162        LuaBind::getInstance().closeToluaInterfaces(this->luaState_);
163
164        singletonRef_s = 0;
165    }
166
167    /**
168    @brief
169        Calls main Lua script
170    @todo
171        This function calls the main Lua script for our GUI.
172
173        Additionally we set the datapath variable in Lua. This is needed so Lua can access the data used for the GUI.
174    */
175    void GUIManager::loadLuaCode()
176    {
177        // set datapath for GUI data
178        lua_pushfstring(this->scriptModule_->getLuaState(), Core::getMediaPathString().c_str());
179        lua_setglobal(this->scriptModule_->getLuaState(), "datapath");
180        // call main Lua script
181        this->scriptModule_->executeScriptFile("loadGUI_3.lua", "GUI");
182    }
183
184    /**
185    @brief
186        used to tick the GUI
187    @param time
188        clock which provides time value for the GUI System
189
190        Ticking the GUI means updating it with a certain regularity.
191        The elapsed time since the last call is given in the time value provided by the clock.
192        This time value is then used to provide a fluent animation of the GUI.
193    */
194    void GUIManager::update(const Clock& time)
195    {
196        assert(guiSystem_);
197        guiSystem_->injectTimePulse(time.getDeltaTime());
198    }
199
200    /**
201    @brief
202        Tells the GUIManager which SceneManager to use
203    @param camera
204        The current camera on which the GUI should be displayed on.
205
206        In fact the GUIManager needs the SceneManager and not the Camera to display the GUI.
207        This means the GUI is not bound to a camera but rather to the SceneManager.
208        Hiding the GUI when needed can therefore not be resolved by just NOT setting the current camera.
209    */
210    void GUIManager::setCamera(Ogre::Camera* camera)
211    {
212        if (camera == NULL)
213            this->guiRenderer_->setTargetSceneManager(0);
214        else
215            this->guiRenderer_->setTargetSceneManager(camera->getSceneManager());
216    }
217
218    /**
219    @brief
220        Executes Lua code
221    @param str
222        reference to string object holding the Lua code which is to be executed
223
224        This function gives total access to the GUI. You can execute ANY Lua code here.
225    */
226    void GUIManager::executeCode(const std::string& str)
227    {
228        try
229        {
230            this->scriptModule_->executeString(str);
231        }
232        catch (const CEGUI::Exception& ex)
233        {
234            COUT(2) << "CEGUI Error: \"" << ex.getMessage() << "\" while executing code \"" << str << "\"" << std::endl;
235        }
236        catch (...)
237        {
238            COUT(2) << "Couldn't execute GUI related Lua code due to unknown reasons." << std::endl;
239        }
240    }
241
242    /**
243    @brief
244        Displays specified GUI on screen
245    @param name
246        The name of the GUI
247
248        The function executes the Lua function with the same name in case the GUIManager is ready.
249        For more details check out loadGUI_2.lua where the function presides.
250    */
251    void GUIManager::showGUI(const std::string& name)
252    {
253        this->executeCode(std::string("showGUI(\"") + name + "\")");
254    }
255
256    void GUIManager::keyPressed(const KeyEvent& evt)
257    {
258        guiSystem_->injectKeyDown(evt.getKeyCode());
259        guiSystem_->injectChar(evt.getText());
260    }
261    void GUIManager::keyReleased(const KeyEvent& evt)
262    {
263        guiSystem_->injectKeyUp(evt.getKeyCode());
264    }
265
266    /**
267    @brief
268        Function receiving a mouse button pressed event.
269    @param id
270        ID of the mouse button which got pressed
271
272        This function is inherited by MouseHandler and injects the event into CEGUI.
273        It is for CEGUI to process the event.
274    */
275    void GUIManager::buttonPressed(MouseButtonCode::ByEnum id)
276    {
277        try
278        {
279            guiSystem_->injectMouseButtonDown(convertButton(id));
280        }
281        catch (CEGUI::ScriptException& ex)
282        {
283            // We simply ignore the exception and proceed
284            COUT(1) << ex.getMessage() << std::endl;
285        }
286    }
287
288    /**
289    @brief
290        Function receiving a mouse button released event.
291    @param id
292        ID of the mouse button which got released
293
294        This function is inherited by MouseHandler and injects the event into CEGUI.
295        It is for CEGUI to process the event.
296    */
297    void GUIManager::buttonReleased(MouseButtonCode::ByEnum id)
298    {
299        try
300        {
301            guiSystem_->injectMouseButtonUp(convertButton(id));
302        }
303        catch (CEGUI::ScriptException& ex)
304        {
305            // We simply ignore the exception and proceed
306            COUT(1) << ex.getMessage() << std::endl;
307        }
308    }
309
310    void GUIManager::mouseMoved(IntVector2 abs, IntVector2 rel, IntVector2 clippingSize)
311    {
312        guiSystem_->injectMouseMove(static_cast<float>(rel.x), static_cast<float>(rel.y));
313    }
314    void GUIManager::mouseScrolled(int abs, int rel)
315    {
316        guiSystem_->injectMouseWheelChange(static_cast<float>(rel));
317    }
318
319    /**
320    @brief
321        converts mouse event code to CEGUI event code
322    @param button
323        code of the mouse button as we use it in Orxonox
324    @return
325        code of the mouse button as it is used by CEGUI
326
327        Simple convertion from mouse event code in Orxonox to the one used in CEGUI.
328     */
329    static inline CEGUI::MouseButton convertButton(MouseButtonCode::ByEnum button)
330    {
331        switch (button)
332        {
333        case MouseButtonCode::Left:
334            return CEGUI::LeftButton;
335
336        case MouseButtonCode::Right:
337            return CEGUI::RightButton;
338
339        case MouseButtonCode::Middle:
340            return CEGUI::MiddleButton;
341
342        case MouseButtonCode::Button3:
343            return CEGUI::X1Button;
344
345        case MouseButtonCode::Button4:
346            return CEGUI::X2Button;
347
348        default:
349            return CEGUI::NoButton;
350        }
351    }
352}
Note: See TracBrowser for help on using the repository browser.