Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/libraries/core/GraphicsManager.cc @ 8703

Last change on this file since 8703 was 8423, checked in by rgrieder, 14 years ago

Added and incorporated new class DestructionHelper: instead of doing the destruction of certain singletons implicitly via scoped_ptrs and ScopeGuards, use a method named destroy() that essentially achieves the same, but makes the destruction sequence obvious.

  • Property svn:eol-style set to native
File size: 20.7 KB
RevLine 
[612]1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
[1293]3 *                    > www.orxonox.net <
[612]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
[1349]11 *   of the License, or (at your option) any later version.
12 *
[612]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:
[1535]23 *      Reto Grieder
[1755]24 *      Benjamin Knecht <beni_at_orxonox.net>, (C) 2007
[612]25 *   Co-authors:
[1755]26 *      Felix Schulthess
[612]27 *
28 */
[1035]29
[2801]30#include "GraphicsManager.h"
[612]31
[8351]32#include <cstdlib>
[2801]33#include <fstream>
[5695]34#include <sstream>
[2801]35#include <boost/filesystem.hpp>
[5695]36#include <boost/shared_array.hpp>
[2801]37
38#include <OgreFrameListener.h>
39#include <OgreRoot.h>
40#include <OgreLogManager.h>
[1755]41#include <OgreRenderWindow.h>
[2801]42#include <OgreRenderSystem.h>
[5695]43#include <OgreResourceGroupManager.h>
[2801]44#include <OgreTextureManager.h>
45#include <OgreViewport.h>
46#include <OgreWindowEventUtilities.h>
[1538]47
[2801]48#include "SpecialConfig.h"
[5929]49#include "util/Clock.h"
[8079]50#include "util/Convert.h"
[2801]51#include "util/Exception.h"
[3280]52#include "util/StringUtils.h"
[2801]53#include "util/SubString.h"
[3346]54#include "ConfigValueIncludes.h"
55#include "CoreIncludes.h"
[7870]56#include "Core.h"
[3346]57#include "Game.h"
58#include "GameMode.h"
[8079]59#include "GUIManager.h"
[5695]60#include "Loader.h"
[5929]61#include "PathConfig.h"
[8079]62#include "ViewportEventListener.h"
[3346]63#include "WindowEventListener.h"
[5695]64#include "XMLFile.h"
[7284]65#include "command/ConsoleCommand.h"
[8079]66#include "input/InputManager.h"
[1032]67
[1625]68namespace orxonox
69{
[8079]70    static const std::string __CC_GraphicsManager_group = "GraphicsManager";
71    static const std::string __CC_setScreenResolution_name = "setScreenResolution";
72    static const std::string __CC_setFSAA_name = "setFSAA";
73    static const std::string __CC_setVSync_name = "setVSync";
74    DeclareConsoleCommand(__CC_GraphicsManager_group, __CC_setScreenResolution_name, &prototype::string__uint_uint_bool);
75    DeclareConsoleCommand(__CC_GraphicsManager_group, __CC_setFSAA_name, &prototype::string__string);
76    DeclareConsoleCommand(__CC_GraphicsManager_group, __CC_setVSync_name, &prototype::string__bool);
77
[7284]78    static const std::string __CC_printScreen_name = "printScreen";
79    DeclareConsoleCommand(__CC_printScreen_name, &prototype::void__void);
80
[3327]81    class OgreWindowEventListener : public Ogre::WindowEventListener
[2801]82    {
[3327]83    public:
84        void windowResized     (Ogre::RenderWindow* rw)
85            { orxonox::WindowEventListener::resizeWindow(rw->getWidth(), rw->getHeight()); }
86        void windowFocusChange (Ogre::RenderWindow* rw)
[7874]87            { orxonox::WindowEventListener::changeWindowFocus(rw->isActive()); }
[3327]88        void windowClosed      (Ogre::RenderWindow* rw)
89            { orxonox::Game::getInstance().stop(); }
90        void windowMoved       (Ogre::RenderWindow* rw)
91            { orxonox::WindowEventListener::moveWindow(); }
[2801]92    };
[1032]93
[3366]94    GraphicsManager* GraphicsManager::singletonPtr_s = 0;
[1293]95
[5695]96    GraphicsManager::GraphicsManager(bool bLoadRenderer)
97        : ogreWindowEventListener_(new OgreWindowEventListener())
[2801]98        , renderWindow_(0)
99        , viewport_(0)
[8079]100        , lastFrameStartTime_(0.0f)
101        , lastFrameEndTime_(0.0f)
[8423]102        , destructionHelper_(this)
[1024]103    {
[2801]104        RegisterObject(GraphicsManager);
105
106        this->setConfigValues();
[612]107
[5695]108        // Ogre setup procedure (creating Ogre::Root)
109        this->loadOgreRoot();
[2801]110
[5695]111        // At first, add the root paths of the data directories as resource locations
[6417]112        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getDataPathString(), "FileSystem");
[5695]113        // Load resources
[6417]114        resources_.reset(new XMLFile("DefaultResources.oxr"));
[5695]115        resources_->setLuaSupport(false);
116        Loader::open(resources_.get());
117
[8366]118        // Only for runs in the build directory (not installed)
119        if (PathConfig::buildDirectoryRun())
[6417]120            Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getExternalDataPathString(), "FileSystem");
[2801]121
[8351]122        extResources_.reset(new XMLFile("resources.oxr"));
123        extResources_->setLuaSupport(false);
124        Loader::open(extResources_.get());
125
[5695]126        if (bLoadRenderer)
[3280]127        {
[5695]128            // Reads the ogre config and creates the render window
129            this->upgradeToGraphics();
[3280]130        }
[2801]131    }
132
[8423]133    void GraphicsManager::destroy()
[1535]134    {
[5929]135        Loader::unload(debugOverlay_.get());
136
[8423]137        Ogre::WindowEventUtilities::removeWindowEventListener(renderWindow_, ogreWindowEventListener_);
[7284]138        ModifyConsoleCommand(__CC_printScreen_name).resetFunction();
[8079]139        ModifyConsoleCommand(__CC_GraphicsManager_group, __CC_setScreenResolution_name).resetFunction();
140        ModifyConsoleCommand(__CC_GraphicsManager_group, __CC_setFSAA_name).resetFunction();
141        ModifyConsoleCommand(__CC_GraphicsManager_group, __CC_setVSync_name).resetFunction();
[5929]142
143        // Undeclare the resources
144        Loader::unload(resources_.get());
[8351]145        Loader::unload(extResources_.get());
[8423]146
147        safeObjectDelete(&ogreRoot_);
148        safeObjectDelete(&ogreLogger_);
149        safeObjectDelete(&ogreWindowEventListener_);
[1535]150    }
151
[2801]152    void GraphicsManager::setConfigValues()
[1535]153    {
[2801]154        SetConfigValue(ogreConfigFile_,  "ogre.cfg")
155            .description("Location of the Ogre config file");
[5695]156        SetConfigValue(ogrePlugins_, specialConfig::ogrePlugins)
[2801]157            .description("Comma separated list of all plugins to load.");
158        SetConfigValue(ogreLogFile_,     "ogre.log")
159            .description("Logfile for messages from Ogre. Use \"\" to suppress log file creation.");
160        SetConfigValue(ogreLogLevelTrivial_ , 5)
161            .description("Corresponding orxonox debug level for ogre Trivial");
162        SetConfigValue(ogreLogLevelNormal_  , 4)
163            .description("Corresponding orxonox debug level for ogre Normal");
164        SetConfigValue(ogreLogLevelCritical_, 2)
165            .description("Corresponding orxonox debug level for ogre Critical");
[1535]166    }
[612]167
[5695]168    /**
169    @brief
170        Loads the renderer and creates the render window if not yet done so.
171    @remarks
172        This operation is irreversible without recreating the GraphicsManager!
173        So if it throws you HAVE to recreate the GraphicsManager!!!
174        It therefore offers almost no exception safety.
175    */
176    void GraphicsManager::upgradeToGraphics()
[2801]177    {
[5695]178        if (renderWindow_ != NULL)
179            return;
[2801]180
[6075]181        // load all the required plugins for Ogre
182        this->loadOgrePlugins();
183
[5695]184        this->loadRenderer();
[2801]185
[5695]186        // Initialise all resources (do this AFTER the renderer has been loaded!)
187        // Note: You can only do this once! Ogre will check whether a resource group has
188        // already been initialised. If you need to load resources later, you will have to
189        // choose another resource group.
190        Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
[2801]191    }
192
[1755]193    /**
194    @brief
[2801]195        Creates the Ogre Root object and sets up the ogre log.
[1755]196    */
[5695]197    void GraphicsManager::loadOgreRoot()
[1538]198    {
[2801]199        COUT(3) << "Setting up Ogre..." << std::endl;
200
[6417]201        if (ogreConfigFile_.empty())
[2801]202        {
203            COUT(2) << "Warning: Ogre config file set to \"\". Defaulting to config.cfg" << std::endl;
204            ModifyConfigValue(ogreConfigFile_, tset, "config.cfg");
205        }
[6417]206        if (ogreLogFile_.empty())
[2801]207        {
208            COUT(2) << "Warning: Ogre log file set to \"\". Defaulting to ogre.log" << std::endl;
209            ModifyConfigValue(ogreLogFile_, tset, "ogre.log");
210        }
211
[5929]212        boost::filesystem::path ogreConfigFilepath(PathConfig::getConfigPath() / this->ogreConfigFile_);
213        boost::filesystem::path ogreLogFilepath(PathConfig::getLogPath() / this->ogreLogFile_);
[2801]214
215        // create a new logManager
216        // Ogre::Root will detect that we've already created a Log
[8423]217        ogreLogger_ = new Ogre::LogManager();
[2801]218        COUT(4) << "Ogre LogManager created" << std::endl;
219
220        // create our own log that we can listen to
221        Ogre::Log *myLog;
[5695]222        myLog = ogreLogger_->createLog(ogreLogFilepath.string(), true, false, false);
[2801]223        COUT(4) << "Ogre Log created" << std::endl;
224
225        myLog->setLogDetail(Ogre::LL_BOREME);
226        myLog->addListener(this);
227
228        COUT(4) << "Creating Ogre Root..." << std::endl;
229
230        // check for config file existence because Ogre displays (caught) exceptions if not
231        if (!boost::filesystem::exists(ogreConfigFilepath))
232        {
233            // create a zero sized file
234            std::ofstream creator;
235            creator.open(ogreConfigFilepath.string().c_str());
236            creator.close();
237        }
238
239        // Leave plugins file empty. We're going to do that part manually later
[8423]240        ogreRoot_ = new Ogre::Root("", ogreConfigFilepath.string(), ogreLogFilepath.string());
[2801]241
242        COUT(3) << "Ogre set up done." << std::endl;
[1538]243    }
[2801]244
245    void GraphicsManager::loadOgrePlugins()
246    {
[8351]247        // Plugin path can have many different locations...
248        std::string pluginPath = specialConfig::ogrePluginsDirectory;
249#ifdef DEPENDENCY_PACKAGE_ENABLE
[8366]250        if (!PathConfig::buildDirectoryRun())
[8351]251        {
252#  if defined(ORXONOX_PLATFORM_WINDOWS)
253            pluginPath = PathConfig::getExecutablePathString();
254#  elif defined(ORXONOX_PLATFORM_APPLE)
255            // TODO: Where are the plugins being installed to?
256            pluginPath = PathConfig::getExecutablePathString();
257#  endif
258        }
259#endif
[2801]260
[8351]261#ifdef ORXONOX_PLATFORM_WINDOWS
262        // Add OGRE plugin path to the environment. That way one plugin could
263        // also depend on another without problems on Windows
264        const char* currentPATH = getenv("PATH");
265        std::string newPATH = pluginPath;
266        if (currentPATH != NULL)
267            newPATH = std::string(currentPATH) + ';' + newPATH;
268        putenv(const_cast<char*>(("PATH=" + newPATH).c_str()));
269#endif
270
[2801]271        // Do some SubString magic to get the comma separated list of plugins
[7284]272        SubString plugins(ogrePlugins_, ",", " ", false, '\\', false, '"', false, '{', '}', false, '\0');
[2801]273        for (unsigned int i = 0; i < plugins.size(); ++i)
[8351]274            ogreRoot_->loadPlugin(pluginPath + '/' + plugins[i]);
[2801]275    }
276
277    void GraphicsManager::loadRenderer()
278    {
279        CCOUT(4) << "Configuring Renderer" << std::endl;
280
[8079]281        bool updatedConfig = Core::getInstance().getOgreConfigTimestamp() > Core::getInstance().getLastLevelTimestamp();
282        if (updatedConfig)
283            COUT(2) << "Ogre config file has changed, but no level was started since then. Displaying config dialogue again to verify the changes." << std::endl;
284
285        if (!ogreRoot_->restoreConfig() || updatedConfig)
[7870]286        {
[2801]287            if (!ogreRoot_->showConfigDialog())
[7868]288                ThrowException(InitialisationFailed, "OGRE graphics configuration dialogue canceled.");
[7870]289            else
290                Core::getInstance().updateOgreConfigTimestamp();
291        }
[2801]292
293        CCOUT(4) << "Creating render window" << std::endl;
294
295        this->renderWindow_ = ogreRoot_->initialise(true, "Orxonox");
[5695]296        // Propagate the size of the new winodw
[3327]297        this->ogreWindowEventListener_->windowResized(renderWindow_);
[2801]298
[8423]299        Ogre::WindowEventUtilities::addWindowEventListener(this->renderWindow_, ogreWindowEventListener_);
[2801]300
[5695]301        // create a full screen default viewport
302        // Note: This may throw when adding a viewport with an existing z-order!
303        //       But in our case we only have one viewport for now anyway, therefore
304        //       no ScopeGuards or anything to handle exceptions.
305        this->viewport_ = this->renderWindow_->addViewport(0, 0);
306
[6524]307        Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(Ogre::MIP_UNLIMITED);
[2801]308
[5695]309        // add console commands
[7284]310        ModifyConsoleCommand(__CC_printScreen_name).setFunction(&GraphicsManager::printScreen, this);
[8079]311        ModifyConsoleCommand(__CC_GraphicsManager_group, __CC_setScreenResolution_name).setFunction(&GraphicsManager::setScreenResolution, this);
312        ModifyConsoleCommand(__CC_GraphicsManager_group, __CC_setFSAA_name).setFunction(&GraphicsManager::setFSAA, this);
313        ModifyConsoleCommand(__CC_GraphicsManager_group, __CC_setVSync_name).setFunction(&GraphicsManager::setVSync, this);
[2801]314    }
315
[5929]316    void GraphicsManager::loadDebugOverlay()
317    {
318        // Load debug overlay to show info about fps and tick time
319        COUT(4) << "Loading Debug Overlay..." << std::endl;
320        debugOverlay_.reset(new XMLFile("debug.oxo"));
321        Loader::open(debugOverlay_.get());
322    }
323
324    /**
325    @note
326        A note about the Ogre::FrameListener: Even though we don't use them,
[8079]327        they still get called.
[5929]328    */
[6417]329    void GraphicsManager::postUpdate(const Clock& time)
[2801]330    {
[8079]331        // Time before rendering
332        uint64_t timeBeforeTick = time.getRealMicroseconds();
333
334        // Ogre's time keeping object
[5695]335        Ogre::FrameEvent evt;
336
[8079]337        // Translate to Ogre float times before the update
338        float temp = lastFrameStartTime_;
339        lastFrameStartTime_ = (float)timeBeforeTick * 0.000001f;
340        evt.timeSinceLastFrame = lastFrameStartTime_ - temp;
341        evt.timeSinceLastEvent = lastFrameStartTime_ - lastFrameEndTime_;
342
343        // Ogre requires the time too
[5695]344        ogreRoot_->_fireFrameStarted(evt);
345
346        // Pump messages in all registered RenderWindows
347        // This calls the WindowEventListener objects.
348        Ogre::WindowEventUtilities::messagePump();
[8079]349        // Make sure the window stays active even when not focused
[5695]350        // (probably only necessary on windows)
351        this->renderWindow_->setActive(true);
352
353        // Render frame
354        ogreRoot_->_updateAllRenderTargets();
355
356        uint64_t timeAfterTick = time.getRealMicroseconds();
357        // Subtract the time used for rendering from the tick time counter
[6502]358        Game::getInstance().subtractTickTime((int32_t)(timeAfterTick - timeBeforeTick));
[5695]359
[8079]360        // Translate to Ogre float times after the update
361        temp = lastFrameEndTime_;
362        lastFrameEndTime_ = (float)timeBeforeTick * 0.000001f;
363        evt.timeSinceLastFrame = lastFrameEndTime_ - temp;
364        evt.timeSinceLastEvent = lastFrameEndTime_ - lastFrameStartTime_;
365
366        // Ogre also needs the time after the frame finished
367        ogreRoot_->_fireFrameEnded(evt);
[2801]368    }
369
[5695]370    void GraphicsManager::setCamera(Ogre::Camera* camera)
371    {
[8079]372        Ogre::Camera* oldCamera = this->viewport_->getCamera();
373
[5695]374        this->viewport_->setCamera(camera);
[8079]375        GUIManager::getInstance().setCamera(camera);
376
377        for (ObjectList<ViewportEventListener>::iterator it = ObjectList<ViewportEventListener>::begin(); it != ObjectList<ViewportEventListener>::end(); ++it)
378            it->cameraChanged(this->viewport_, oldCamera);
[5695]379    }
380
[2801]381    /**
382    @brief
383        Method called by the LogListener interface from Ogre.
384        We use it to capture Ogre log messages and handle it ourselves.
385    @param message
386        The message to be logged
387    @param lml
388        The message level the log is using
389    @param maskDebug
390        If we are printing to the console or not
391    @param logName
392        The name of this log (so you can have several listeners
393        for different logs, and identify them)
394    */
395    void GraphicsManager::messageLogged(const std::string& message,
396        Ogre::LogMessageLevel lml, bool maskDebug, const std::string& logName)
397    {
398        int orxonoxLevel;
[6417]399        std::string introduction;
400        // Do not show caught OGRE exceptions in front
401        if (message.find("EXCEPTION") != std::string::npos)
[2801]402        {
[6417]403            orxonoxLevel = OutputLevel::Debug;
404            introduction = "Ogre, caught exception: ";
[2801]405        }
[6417]406        else
407        {
408            switch (lml)
409            {
410            case Ogre::LML_TRIVIAL:
411                orxonoxLevel = this->ogreLogLevelTrivial_;
412                break;
413            case Ogre::LML_NORMAL:
414                orxonoxLevel = this->ogreLogLevelNormal_;
415                break;
416            case Ogre::LML_CRITICAL:
417                orxonoxLevel = this->ogreLogLevelCritical_;
418                break;
419            default:
420                orxonoxLevel = 0;
421            }
422            introduction = "Ogre: ";
423        }
[6105]424        OutputHandler::getOutStream(orxonoxLevel)
[6417]425            << introduction << message << std::endl;
[2801]426    }
427
[5695]428    size_t GraphicsManager::getRenderWindowHandle()
429    {
430        size_t windowHnd = 0;
431        renderWindow_->getCustomAttribute("WINDOW", &windowHnd);
432        return windowHnd;
433    }
434
435    bool GraphicsManager::isFullScreen() const
436    {
[8079]437        return this->renderWindow_->isFullScreen();
438    }
439
440    unsigned int GraphicsManager::getWindowWidth() const
441    {
442        return this->renderWindow_->getWidth();
443    }
444
445    unsigned int GraphicsManager::getWindowHeight() const
446    {
447        return this->renderWindow_->getHeight();
448    }
449
450    bool GraphicsManager::hasVSyncEnabled() const
451    {
[5695]452        Ogre::ConfigOptionMap& options = ogreRoot_->getRenderSystem()->getConfigOptions();
[8079]453        Ogre::ConfigOptionMap::iterator it = options.find("VSync");
454        if (it != options.end())
455            return (it->second.currentValue == "Yes");
456        else
457            return false;
458    }
459
460    std::string GraphicsManager::getFSAAMode() const
461    {
462        Ogre::ConfigOptionMap& options = ogreRoot_->getRenderSystem()->getConfigOptions();
463        Ogre::ConfigOptionMap::iterator it = options.find("FSAA");
464        if (it != options.end())
465            return it->second.currentValue;
466        else
467            return "";
468    }
469
470    std::string GraphicsManager::setScreenResolution(unsigned int width, unsigned int height, bool fullscreen)
471    {
472        // workaround to detect if the colour depth should be written to the config file
473        bool bWriteColourDepth = false;
474        Ogre::ConfigOptionMap& options = ogreRoot_->getRenderSystem()->getConfigOptions();
475        Ogre::ConfigOptionMap::iterator it = options.find("Video Mode");
476        if (it != options.end())
477            bWriteColourDepth = (it->second.currentValue.find('@') != std::string::npos);
478
479        if (bWriteColourDepth)
[5695]480        {
[8079]481            this->ogreRoot_->getRenderSystem()->setConfigOption("Video Mode", multi_cast<std::string>(width)
482                                                                    + " x " + multi_cast<std::string>(height)
483                                                                    + " @ " + multi_cast<std::string>(this->getRenderWindow()->getColourDepth()) + "-bit colour");
[5695]484        }
485        else
486        {
[8079]487            this->ogreRoot_->getRenderSystem()->setConfigOption("Video Mode", multi_cast<std::string>(width)
488                                                                    + " x " + multi_cast<std::string>(height));
[5695]489        }
[8079]490
491        this->ogreRoot_->getRenderSystem()->setConfigOption("Full Screen", fullscreen ? "Yes" : "No");
492
493        std::string validate = this->ogreRoot_->getRenderSystem()->validateConfigOptions();
494
495        if (validate == "")
496        {
497            GraphicsManager::getInstance().getRenderWindow()->setFullscreen(fullscreen, width, height);
498            this->ogreRoot_->saveConfig();
499            Core::getInstance().updateOgreConfigTimestamp();
500            // Also reload the input devices
501            InputManager::getInstance().reload();
502        }
503
504        return validate;
[5695]505    }
506
[8079]507    std::string GraphicsManager::setFSAA(const std::string& mode)
508    {
509        this->ogreRoot_->getRenderSystem()->setConfigOption("FSAA", mode);
510
511        std::string validate = this->ogreRoot_->getRenderSystem()->validateConfigOptions();
512
513        if (validate == "")
514        {
515            //this->ogreRoot_->getRenderSystem()->reinitialise(); // can't use this that easily, because it recreates the render window, invalidating renderWindow_
516            this->ogreRoot_->saveConfig();
517            Core::getInstance().updateOgreConfigTimestamp();
518        }
519
520        return validate;
521    }
522
523    std::string GraphicsManager::setVSync(bool vsync)
524    {
525        this->ogreRoot_->getRenderSystem()->setConfigOption("VSync", vsync ? "Yes" : "No");
526
527        std::string validate = this->ogreRoot_->getRenderSystem()->validateConfigOptions();
528
529        if (validate == "")
530        {
531            //this->ogreRoot_->getRenderSystem()->reinitialise(); // can't use this that easily, because it recreates the render window, invalidating renderWindow_
532            this->ogreRoot_->saveConfig();
533            Core::getInstance().updateOgreConfigTimestamp();
534        }
535
536        return validate;
537    }
538
[2801]539    void GraphicsManager::printScreen()
540    {
541        assert(this->renderWindow_);
[6417]542        this->renderWindow_->writeContentsToTimestampedFile(PathConfig::getLogPathString() + "screenShot_", ".png");
[2801]543    }
[612]544}
Note: See TracBrowser for help on using the repository browser.