Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/buildsystem3/src/orxonox/gamestates/GSGraphics.cc @ 2693

Last change on this file since 2693 was 2690, checked in by rgrieder, 16 years ago
  • Moved def_keybindings to media repository in folder defaultConfig
  • If you have a better name for that folder, you're welcome
  • the "def_" prefix has been removed
  • ConfigFileManager now looks for a file in media/defaultConfig with the same name if the config file does not exist yet
  • No file gets written while only loading
  • Removed hacky GCC 3 warning code for each library and instead just put "Wno-sign-compare" to the GCC 3 flags (that will remove all boost::filesystem warnings)
  • ogre.cfg still remains on tardis for the development build (not install though)
  • Property svn:eol-style set to native
File size: 19.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 *   Co-authors:
25 *      ...
26 *
27 */
28
29#include "OrxonoxStableHeaders.h"
30#include "GSGraphics.h"
31
32#include <fstream>
33#include <boost/filesystem.hpp>
34
35#include <OgreCompositorManager.h>
36#include <OgreConfigFile.h>
37#include <OgreFrameListener.h>
38#include <OgreRoot.h>
39#include <OgreLogManager.h>
40#include <OgreException.h>
41#include <OgreRenderWindow.h>
42#include <OgreRenderSystem.h>
43#include <OgreTextureManager.h>
44#include <OgreViewport.h>
45#include <OgreWindowEventUtilities.h>
46
47#include "util/Debug.h"
48#include "util/Exception.h"
49#include "util/String.h"
50#include "util/SubString.h"
51#include "core/ConsoleCommand.h"
52#include "core/ConfigValueIncludes.h"
53#include "core/CoreIncludes.h"
54#include "core/Core.h"
55#include "core/input/InputManager.h"
56#include "core/input/KeyBinder.h"
57#include "core/input/ExtendedInputState.h"
58#include "core/Loader.h"
59#include "core/XMLFile.h"
60#include "overlays/console/InGameConsole.h"
61#include "gui/GUIManager.h"
62#include "tools/WindowEventListener.h"
63
64// for compatibility
65#include "GraphicsEngine.h"
66
67namespace orxonox
68{
69    GSGraphics::GSGraphics()
70        : GameState<GSRoot>("graphics")
71        , renderWindow_(0)
72        , viewport_(0)
73        , bWindowEventListenerUpdateRequired_(false)
74        , inputManager_(0)
75        , console_(0)
76        , guiManager_(0)
77        , ogreRoot_(0)
78        , ogreLogger_(0)
79        , graphicsEngine_(0)
80        , masterKeyBinder_(0)
81        , debugOverlay_(0)
82    {
83        RegisterRootObject(GSGraphics);
84        setConfigValues();
85    }
86
87    GSGraphics::~GSGraphics()
88    {
89    }
90
91    void GSGraphics::setConfigValues()
92    {
93        SetConfigValue(resourceFile_,    "resources.cfg")
94            .description("Location of the resources file in the data path.");
95        SetConfigValue(ogreConfigFile_,  "ogre.cfg")
96            .description("Location of the Ogre config file");
97        SetConfigValue(ogrePluginsFolder_, ORXONOX_OGRE_PLUGINS_FOLDER)
98            .description("Folder where the Ogre plugins are located.");
99        SetConfigValue(ogrePlugins_, ORXONOX_OGRE_PLUGINS)
100            .description("Comma separated list of all plugins to load.");
101        SetConfigValue(ogreLogFile_,     "ogre.log")
102            .description("Logfile for messages from Ogre. Use \"\" to suppress log file creation.");
103        SetConfigValue(ogreLogLevelTrivial_ , 5)
104            .description("Corresponding orxonox debug level for ogre Trivial");
105        SetConfigValue(ogreLogLevelNormal_  , 4)
106            .description("Corresponding orxonox debug level for ogre Normal");
107        SetConfigValue(ogreLogLevelCritical_, 2)
108            .description("Corresponding orxonox debug level for ogre Critical");
109    }
110
111    void GSGraphics::enter()
112    {
113        Core::setShowsGraphics(true);
114
115        // initialise graphics engine. Doesn't load the render window yet!
116        graphicsEngine_ = new GraphicsEngine();
117
118        // Ogre setup procedure
119        setupOgre();
120        // load all the required plugins for Ogre
121        loadOgrePlugins();
122        // read resource declaration file
123        this->declareResources();
124        // Reads ogre config and creates the render window
125        this->loadRenderer();
126
127        // TODO: Spread this so that this call only initialises things needed for the Console and GUI
128        this->initialiseResources();
129
130        // We want to get informed whenever an object of type WindowEventListener is created
131        // in order to later update the window size.
132        bWindowEventListenerUpdateRequired_ = false;
133        RegisterConstructionCallback(GSGraphics, orxonox::WindowEventListener, requestWindowEventListenerUpdate);
134
135        // load debug overlay
136        COUT(3) << "Loading Debug Overlay..." << std::endl;
137        this->debugOverlay_ = new XMLFile(Core::getMediaPath() + "overlay/debug.oxo");
138        Loader::open(debugOverlay_);
139
140        // Calls the InputManager which sets up the input devices.
141        // The render window width and height are used to set up the mouse movement.
142        inputManager_ = new InputManager();
143        size_t windowHnd = 0;
144        this->renderWindow_->getCustomAttribute("WINDOW", &windowHnd);
145        inputManager_->initialise(windowHnd, renderWindow_->getWidth(), renderWindow_->getHeight(), true);
146        // Configure master input state with a KeyBinder
147        masterKeyBinder_ = new KeyBinder();
148        masterKeyBinder_->loadBindings("masterKeybindings.ini");
149        inputManager_->getMasterInputState()->addKeyHandler(masterKeyBinder_);
150
151        // Load the InGameConsole
152        console_ = new InGameConsole();
153        console_->initialise(this->renderWindow_->getWidth(), this->renderWindow_->getHeight());
154
155        // load the CEGUI interface
156        guiManager_ = new GUIManager();
157        guiManager_->initialise(this->renderWindow_);
158
159        // add console commands
160        FunctorMember<GSGraphics>* functor1 = createFunctor(&GSGraphics::printScreen);
161        functor1->setObject(this);
162        ccPrintScreen_ = createConsoleCommand(functor1, "printScreen");
163        CommandExecutor::addConsoleCommandShortcut(ccPrintScreen_);
164    }
165
166    void GSGraphics::leave()
167    {
168        using namespace Ogre;
169
170        delete this->ccPrintScreen_;
171
172        // remove our WindowEventListener first to avoid bad calls after the window has been destroyed
173        Ogre::WindowEventUtilities::removeWindowEventListener(this->renderWindow_, this);
174
175        delete this->guiManager_;
176
177        delete this->console_;
178
179        //inputManager_->getMasterInputState()->removeKeyHandler(this->masterKeyBinder_);
180        delete this->masterKeyBinder_;
181        delete this->inputManager_;
182
183        Loader::unload(this->debugOverlay_);
184        delete this->debugOverlay_;
185
186        // unload all compositors
187        Ogre::CompositorManager::getSingleton().removeAll();
188
189        // destroy render window
190        RenderSystem* renderer = this->ogreRoot_->getRenderSystem();
191        renderer->destroyRenderWindow("Orxonox");
192
193        /*** CODE SNIPPET, UNUSED ***/
194        // Does the opposite of initialise()
195        //ogreRoot_->shutdown();
196        // Remove all resources and resource groups
197        //StringVector groups = ResourceGroupManager::getSingleton().getResourceGroups();
198        //for (StringVector::iterator it = groups.begin(); it != groups.end(); ++it)
199        //{
200        //    ResourceGroupManager::getSingleton().destroyResourceGroup(*it);
201        //}
202
203        //ParticleSystemManager::getSingleton().removeAllTemplates();
204
205        // Shutdown the render system
206        //this->ogreRoot_->setRenderSystem(0);
207
208        delete this->ogreRoot_;
209
210        // delete the ogre log and the logManager (since we have created it).
211        this->ogreLogger_->getDefaultLog()->removeListener(this);
212        this->ogreLogger_->destroyLog(Ogre::LogManager::getSingleton().getDefaultLog());
213        delete this->ogreLogger_;
214
215        delete graphicsEngine_;
216
217        Core::setShowsGraphics(false);
218    }
219
220    /**
221    @note
222        A note about the Ogre::FrameListener: Even though we don't use them,
223        they still get called. However, the delta times are not correct (except
224        for timeSinceLastFrame, which is the most important). A little research
225        as shown that there is probably only one FrameListener that doesn't even
226        need the time. So we shouldn't run into problems.
227    */
228    void GSGraphics::ticked(const Clock& time)
229    {
230        uint64_t timeBeforeTick = time.getRealMicroseconds();
231
232        float dt = time.getDeltaTime();
233
234        this->inputManager_->tick(dt);
235        // tick console
236        this->console_->tick(dt);
237        this->tickChild(time);
238
239        if (this->bWindowEventListenerUpdateRequired_)
240        {
241            // Update all WindowEventListeners for the case a new one was created.
242            this->windowResized(this->renderWindow_);
243            this->bWindowEventListenerUpdateRequired_ = false;
244        }
245
246        uint64_t timeAfterTick = time.getRealMicroseconds();
247
248        // Also add our tick time to the list in GSRoot
249        this->getParent()->addTickTime(timeAfterTick - timeBeforeTick);
250
251        // Update statistics overlay. Note that the values only change periodically in GSRoot.
252        GraphicsEngine::getInstance().setAverageFramesPerSecond(this->getParent()->getAvgFPS());
253        GraphicsEngine::getInstance().setAverageTickTime(this->getParent()->getAvgTickTime());
254
255        // don't forget to call _fireFrameStarted in ogre to make sure
256        // everything goes smoothly
257        Ogre::FrameEvent evt;
258        evt.timeSinceLastFrame = dt;
259        evt.timeSinceLastEvent = dt; // note: same time, but shouldn't matter anyway
260        ogreRoot_->_fireFrameStarted(evt);
261
262        // Pump messages in all registered RenderWindows
263        // This calls the WindowEventListener objects.
264        Ogre::WindowEventUtilities::messagePump();
265        // make sure the window stays active even when not focused
266        // (probably only necessary on windows)
267        this->renderWindow_->setActive(true);
268
269        // render
270        ogreRoot_->_updateAllRenderTargets();
271
272        // again, just to be sure ogre works fine
273        ogreRoot_->_fireFrameEnded(evt); // note: uses the same time as _fireFrameStarted
274    }
275
276    /**
277    @brief
278        Creates the Ogre Root object and sets up the ogre log.
279    */
280    void GSGraphics::setupOgre()
281    {
282        COUT(3) << "Setting up Ogre..." << std::endl;
283
284        if (ogreConfigFile_ == "")
285        {
286            COUT(2) << "Warning: Ogre config file set to \"\". Defaulting to config.cfg" << std::endl;
287            ModifyConfigValue(ogreConfigFile_, tset, "config.cfg");
288        }
289        if (ogreLogFile_ == "")
290        {
291            COUT(2) << "Warning: Ogre log file set to \"\". Defaulting to ogre.log" << std::endl;
292            ModifyConfigValue(ogreLogFile_, tset, "ogre.log");
293        }
294
295        boost::filesystem::path ogreConfigFilepath(Core::getConfigPath() + ogreConfigFile_);
296        boost::filesystem::path ogreLogFilepath(Core::getLogPath() + ogreLogFile_);
297
298        // create a new logManager
299        // Ogre::Root will detect that we've already created a Log
300        ogreLogger_ = new Ogre::LogManager();
301        COUT(4) << "Ogre LogManager created" << std::endl;
302
303        // create our own log that we can listen to
304        Ogre::Log *myLog;
305        myLog = ogreLogger_->createLog(ogreLogFilepath.file_string(), true, false, false);
306        COUT(4) << "Ogre Log created" << std::endl;
307
308        myLog->setLogDetail(Ogre::LL_BOREME);
309        myLog->addListener(this);
310
311        COUT(4) << "Creating Ogre Root..." << std::endl;
312
313        // check for config file existence because Ogre displays (caught) exceptions if not
314        std::ifstream probe;
315        probe.open(ogreConfigFilepath.file_string().c_str());
316        if (!probe)
317        {
318            // create a zero sized file
319            std::ofstream creator;
320            creator.open(ogreConfigFilepath.file_string().c_str());
321            creator.close();
322        }
323        else
324            probe.close();
325
326        // Leave plugins file empty. We're going to do that part manually later
327        ogreRoot_ = new Ogre::Root("", ogreConfigFilepath.file_string(), ogreLogFilepath.file_string());
328
329        COUT(3) << "Ogre set up done." << std::endl;
330    }
331
332    void GSGraphics::loadOgrePlugins()
333    {
334        // just to make sure the next statement doesn't segfault
335        if (ogrePluginsFolder_ == "")
336            ogrePluginsFolder_ = ".";
337
338        boost::filesystem::path folder(ogrePluginsFolder_);
339        // Do some SubString magic to get the comma separated list of plugins
340        SubString plugins(ogrePlugins_, ",", " ", false, 92, false, 34, false, 40, 41, false, '\0');
341        for (unsigned int i = 0; i < plugins.size(); ++i)
342            ogreRoot_->loadPlugin((folder / plugins[i]).file_string());
343    }
344
345    void GSGraphics::declareResources()
346    {
347        CCOUT(4) << "Declaring Resources" << std::endl;
348        //TODO: Specify layout of data file and maybe use xml-loader
349        //TODO: Work with ressource groups (should be generated by a special loader)
350
351        if (resourceFile_ == "")
352        {
353            COUT(2) << "Warning: Ogre resource file set to \"\". Defaulting to resources.cfg" << std::endl;
354            ModifyConfigValue(resourceFile_, tset, "resources.cfg");
355        }
356
357        // Load resource paths from data file using configfile ressource type
358        Ogre::ConfigFile cf;
359        try
360        {
361            cf.load(Core::getMediaPath() + resourceFile_);
362        }
363        catch (...)
364        {
365            //COUT(1) << ex.getFullDescription() << std::endl;
366            COUT(0) << "Have you forgotten to set the data path in orxnox.ini?" << std::endl;
367            throw;
368        }
369
370        // Go through all sections & settings in the file
371        Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
372
373        std::string secName, typeName, archName;
374        while (seci.hasMoreElements())
375        {
376            try
377            {
378                secName = seci.peekNextKey();
379                Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
380                Ogre::ConfigFile::SettingsMultiMap::iterator i;
381                for (i = settings->begin(); i != settings->end(); ++i)
382                {
383                    typeName = i->first; // for instance "FileSystem" or "Zip"
384                    archName = i->second; // name (and location) of archive
385
386                    Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
387                        std::string(Core::getMediaPath() + archName), typeName, secName);
388                }
389            }
390            catch (Ogre::Exception& ex)
391            {
392                COUT(1) << ex.getFullDescription() << std::endl;
393            }
394        }
395    }
396
397    void GSGraphics::loadRenderer()
398    {
399        CCOUT(4) << "Configuring Renderer" << std::endl;
400
401        if (!ogreRoot_->restoreConfig())
402            if (!ogreRoot_->showConfigDialog())
403                ThrowException(InitialisationFailed, "Could not show Ogre configuration dialogue.");
404
405        CCOUT(4) << "Creating render window" << std::endl;
406
407        this->renderWindow_ = ogreRoot_->initialise(true, "Orxonox");
408
409        Ogre::WindowEventUtilities::addWindowEventListener(this->renderWindow_, this);
410
411        Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(0);
412
413        // create a full screen default viewport
414        this->viewport_ = this->renderWindow_->addViewport(0, 0);
415
416        if (this->graphicsEngine_)
417            this->graphicsEngine_->setViewport(this->viewport_);
418    }
419
420    void GSGraphics::initialiseResources()
421    {
422        CCOUT(4) << "Initialising resources" << std::endl;
423        //TODO: Do NOT load all the groups, why are we doing that? And do we really do that? initialise != load...
424        //try
425        //{
426            Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
427            /*Ogre::StringVector str = Ogre::ResourceGroupManager::getSingleton().getResourceGroups();
428            for (unsigned int i = 0; i < str.size(); i++)
429            {
430            Ogre::ResourceGroupManager::getSingleton().loadResourceGroup(str[i]);
431            }*/
432        //}
433        //catch (...)
434        //{
435        //    CCOUT(2) << "Error: There was a serious error when initialising the resources." << std::endl;
436        //    throw;
437        //}
438    }
439
440    /**
441    @brief
442        Method called by the LogListener interface from Ogre.
443        We use it to capture Ogre log messages and handle it ourselves.
444    @param message
445        The message to be logged
446    @param lml
447        The message level the log is using
448    @param maskDebug
449        If we are printing to the console or not
450    @param logName
451        The name of this log (so you can have several listeners
452        for different logs, and identify them)
453    */
454    void GSGraphics::messageLogged(const std::string& message,
455        Ogre::LogMessageLevel lml, bool maskDebug, const std::string& logName)
456    {
457        int orxonoxLevel;
458        switch (lml)
459        {
460        case Ogre::LML_TRIVIAL:
461            orxonoxLevel = this->ogreLogLevelTrivial_;
462            break;
463        case Ogre::LML_NORMAL:
464            orxonoxLevel = this->ogreLogLevelNormal_;
465            break;
466        case Ogre::LML_CRITICAL:
467            orxonoxLevel = this->ogreLogLevelCritical_;
468            break;
469        default:
470            orxonoxLevel = 0;
471        }
472        OutputHandler::getOutStream().setOutputLevel(orxonoxLevel)
473            << "Ogre: " << message << std::endl;
474    }
475
476    /**
477    @brief
478        Window has moved.
479    @param rw
480        The render window it occured in
481    */
482    void GSGraphics::windowMoved(Ogre::RenderWindow *rw)
483    {
484        for (ObjectList<orxonox::WindowEventListener>::iterator it = ObjectList<orxonox::WindowEventListener>::begin(); it; ++it)
485            it->windowMoved();
486    }
487
488    /**
489    @brief
490        Window has resized.
491    @param rw
492        The render window it occured in
493    @note
494        GraphicsEngine has a render window stored itself. This is the same
495        as rw. But we have to be careful when using multiple render windows!
496    */
497    void GSGraphics::windowResized(Ogre::RenderWindow *rw)
498    {
499        for (ObjectList<orxonox::WindowEventListener>::iterator it = ObjectList<orxonox::WindowEventListener>::begin(); it; ++it)
500            it->windowResized(this->renderWindow_->getWidth(), this->renderWindow_->getHeight());
501
502        // OIS needs this under linux even if we only use relative input measurement.
503        if (this->inputManager_)
504            this->inputManager_->setWindowExtents(renderWindow_->getWidth(), renderWindow_->getHeight());
505    }
506
507    /**
508    @brief
509        Window focus has changed.
510    @param rw
511        The render window it occured in
512    */
513    void GSGraphics::windowFocusChange(Ogre::RenderWindow *rw)
514    {
515        for (ObjectList<orxonox::WindowEventListener>::iterator it = ObjectList<orxonox::WindowEventListener>::begin(); it; ++it)
516            it->windowFocusChanged();
517
518        // instruct InputManager to clear the buffers (core library so we cannot use the interface)
519        if (this->inputManager_)
520            this->inputManager_->clearBuffers();
521    }
522
523    /**
524    @brief
525        Window was closed.
526    @param rw
527        The render window it occured in
528    */
529    void GSGraphics::windowClosed(Ogre::RenderWindow *rw)
530    {
531        this->requestState("root");
532    }
533
534    void GSGraphics::printScreen()
535    {
536        if (this->renderWindow_)
537        {
538            this->renderWindow_->writeContentsToTimestampedFile("shot_", ".jpg");
539        }
540    }
541}
Note: See TracBrowser for help on using the repository browser.