Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/output/src/libraries/core/GraphicsManager.cc @ 8806

Last change on this file since 8806 was 8806, checked in by landauf, 13 years ago

Replaced COUT with orxout in core. Tried to set levels and contexts in a more or less useful way, but not really optimized.

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