Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 8366 was 8366, checked in by rgrieder, 13 years ago

Renamed PathConfig::isDevelopmentRun() to PathConfig::buildDirectoryRun() because that fits better and there is no confusion with Core::inDevMode().
Also used isDevelopmentRun() as default value for Core::inDevMode() instead of ORXONOX_RELEASE.

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