Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/kicklib/src/libraries/core/GraphicsManager.cc @ 7967

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

Dropped support for OGRE v1.4 and removed the remaining workarounds.

  • Property svn:eol-style set to native
File size: 14.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
[2801]32#include <fstream>
[5695]33#include <sstream>
[2801]34#include <boost/filesystem.hpp>
[5695]35#include <boost/shared_array.hpp>
[2801]36
37#include <OgreFrameListener.h>
38#include <OgreRoot.h>
39#include <OgreLogManager.h>
[1755]40#include <OgreRenderWindow.h>
[2801]41#include <OgreRenderSystem.h>
[5695]42#include <OgreResourceGroupManager.h>
[2801]43#include <OgreTextureManager.h>
44#include <OgreViewport.h>
45#include <OgreWindowEventUtilities.h>
[1538]46
[2801]47#include "SpecialConfig.h"
[5929]48#include "util/Clock.h"
[2801]49#include "util/Exception.h"
[3280]50#include "util/StringUtils.h"
[2801]51#include "util/SubString.h"
[3346]52#include "ConfigValueIncludes.h"
53#include "CoreIncludes.h"
[7870]54#include "Core.h"
[3346]55#include "Game.h"
56#include "GameMode.h"
[5695]57#include "Loader.h"
[5929]58#include "PathConfig.h"
[3346]59#include "WindowEventListener.h"
[5695]60#include "XMLFile.h"
[7284]61#include "command/ConsoleCommand.h"
[1032]62
[1625]63namespace orxonox
64{
[7284]65    static const std::string __CC_printScreen_name = "printScreen";
66    DeclareConsoleCommand(__CC_printScreen_name, &prototype::void__void);
67
[3327]68    class OgreWindowEventListener : public Ogre::WindowEventListener
[2801]69    {
[3327]70    public:
71        void windowResized     (Ogre::RenderWindow* rw)
72            { orxonox::WindowEventListener::resizeWindow(rw->getWidth(), rw->getHeight()); }
73        void windowFocusChange (Ogre::RenderWindow* rw)
[7874]74            { orxonox::WindowEventListener::changeWindowFocus(rw->isActive()); }
[3327]75        void windowClosed      (Ogre::RenderWindow* rw)
76            { orxonox::Game::getInstance().stop(); }
77        void windowMoved       (Ogre::RenderWindow* rw)
78            { orxonox::WindowEventListener::moveWindow(); }
[2801]79    };
[1032]80
[3366]81    GraphicsManager* GraphicsManager::singletonPtr_s = 0;
[1293]82
[1755]83    /**
84    @brief
[2801]85        Non-initialising constructor.
[1755]86    */
[5695]87    GraphicsManager::GraphicsManager(bool bLoadRenderer)
88        : ogreWindowEventListener_(new OgreWindowEventListener())
[2801]89        , renderWindow_(0)
90        , viewport_(0)
[1024]91    {
[2801]92        RegisterObject(GraphicsManager);
93
94        this->setConfigValues();
[612]95
[5695]96        // Ogre setup procedure (creating Ogre::Root)
97        this->loadOgreRoot();
[2801]98
[5695]99        // At first, add the root paths of the data directories as resource locations
[6417]100        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getDataPathString(), "FileSystem");
[5695]101        // Load resources
[6417]102        resources_.reset(new XMLFile("DefaultResources.oxr"));
[5695]103        resources_->setLuaSupport(false);
104        Loader::open(resources_.get());
105
106        // Only for development runs
[5929]107        if (PathConfig::isDevelopmentRun())
[3280]108        {
[6417]109            Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getExternalDataPathString(), "FileSystem");
110            extResources_.reset(new XMLFile("resources.oxr"));
[5695]111            extResources_->setLuaSupport(false);
112            Loader::open(extResources_.get());
113        }
[2801]114
[5695]115        if (bLoadRenderer)
[3280]116        {
[5695]117            // Reads the ogre config and creates the render window
118            this->upgradeToGraphics();
[3280]119        }
[2801]120    }
121
[1755]122    /**
123    @brief
[5695]124        Destruction is done by the member scoped_ptrs.
[1755]125    */
[2801]126    GraphicsManager::~GraphicsManager()
[1535]127    {
[5929]128        Loader::unload(debugOverlay_.get());
129
[5695]130        Ogre::WindowEventUtilities::removeWindowEventListener(renderWindow_, ogreWindowEventListener_.get());
[7284]131        ModifyConsoleCommand(__CC_printScreen_name).resetFunction();
[5929]132
133        // Undeclare the resources
134        Loader::unload(resources_.get());
135        if (PathConfig::isDevelopmentRun())
136            Loader::unload(extResources_.get());
[1535]137    }
138
[2801]139    void GraphicsManager::setConfigValues()
[1535]140    {
[2801]141        SetConfigValue(ogreConfigFile_,  "ogre.cfg")
142            .description("Location of the Ogre config file");
[5695]143        SetConfigValue(ogrePluginsDirectory_, specialConfig::ogrePluginsDirectory)
[2801]144            .description("Folder where the Ogre plugins are located.");
[5695]145        SetConfigValue(ogrePlugins_, specialConfig::ogrePlugins)
[2801]146            .description("Comma separated list of all plugins to load.");
147        SetConfigValue(ogreLogFile_,     "ogre.log")
148            .description("Logfile for messages from Ogre. Use \"\" to suppress log file creation.");
149        SetConfigValue(ogreLogLevelTrivial_ , 5)
150            .description("Corresponding orxonox debug level for ogre Trivial");
151        SetConfigValue(ogreLogLevelNormal_  , 4)
152            .description("Corresponding orxonox debug level for ogre Normal");
153        SetConfigValue(ogreLogLevelCritical_, 2)
154            .description("Corresponding orxonox debug level for ogre Critical");
[1535]155    }
[612]156
[5695]157    /**
158    @brief
159        Loads the renderer and creates the render window if not yet done so.
160    @remarks
161        This operation is irreversible without recreating the GraphicsManager!
162        So if it throws you HAVE to recreate the GraphicsManager!!!
163        It therefore offers almost no exception safety.
164    */
165    void GraphicsManager::upgradeToGraphics()
[2801]166    {
[5695]167        if (renderWindow_ != NULL)
168            return;
[2801]169
[6075]170        // load all the required plugins for Ogre
171        this->loadOgrePlugins();
172
[5695]173        this->loadRenderer();
[2801]174
[5695]175        // Initialise all resources (do this AFTER the renderer has been loaded!)
176        // Note: You can only do this once! Ogre will check whether a resource group has
177        // already been initialised. If you need to load resources later, you will have to
178        // choose another resource group.
179        Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
[2801]180    }
181
[1755]182    /**
183    @brief
[2801]184        Creates the Ogre Root object and sets up the ogre log.
[1755]185    */
[5695]186    void GraphicsManager::loadOgreRoot()
[1538]187    {
[2801]188        COUT(3) << "Setting up Ogre..." << std::endl;
189
[6417]190        if (ogreConfigFile_.empty())
[2801]191        {
192            COUT(2) << "Warning: Ogre config file set to \"\". Defaulting to config.cfg" << std::endl;
193            ModifyConfigValue(ogreConfigFile_, tset, "config.cfg");
194        }
[6417]195        if (ogreLogFile_.empty())
[2801]196        {
197            COUT(2) << "Warning: Ogre log file set to \"\". Defaulting to ogre.log" << std::endl;
198            ModifyConfigValue(ogreLogFile_, tset, "ogre.log");
199        }
200
[5929]201        boost::filesystem::path ogreConfigFilepath(PathConfig::getConfigPath() / this->ogreConfigFile_);
202        boost::filesystem::path ogreLogFilepath(PathConfig::getLogPath() / this->ogreLogFile_);
[2801]203
204        // create a new logManager
205        // Ogre::Root will detect that we've already created a Log
[5695]206        ogreLogger_.reset(new Ogre::LogManager());
[2801]207        COUT(4) << "Ogre LogManager created" << std::endl;
208
209        // create our own log that we can listen to
210        Ogre::Log *myLog;
[5695]211        myLog = ogreLogger_->createLog(ogreLogFilepath.string(), true, false, false);
[2801]212        COUT(4) << "Ogre Log created" << std::endl;
213
214        myLog->setLogDetail(Ogre::LL_BOREME);
215        myLog->addListener(this);
216
217        COUT(4) << "Creating Ogre Root..." << std::endl;
218
219        // check for config file existence because Ogre displays (caught) exceptions if not
220        if (!boost::filesystem::exists(ogreConfigFilepath))
221        {
222            // create a zero sized file
223            std::ofstream creator;
224            creator.open(ogreConfigFilepath.string().c_str());
225            creator.close();
226        }
227
228        // Leave plugins file empty. We're going to do that part manually later
[5695]229        ogreRoot_.reset(new Ogre::Root("", ogreConfigFilepath.string(), ogreLogFilepath.string()));
[2801]230
231        COUT(3) << "Ogre set up done." << std::endl;
[1538]232    }
[2801]233
234    void GraphicsManager::loadOgrePlugins()
235    {
236        // just to make sure the next statement doesn't segfault
[6417]237        if (ogrePluginsDirectory_.empty())
238            ogrePluginsDirectory_ = '.';
[2801]239
[5695]240        boost::filesystem::path folder(ogrePluginsDirectory_);
[2801]241        // Do some SubString magic to get the comma separated list of plugins
[7284]242        SubString plugins(ogrePlugins_, ",", " ", false, '\\', false, '"', false, '{', '}', false, '\0');
[2801]243        // Use backslash paths on Windows! file_string() already does that though.
244        for (unsigned int i = 0; i < plugins.size(); ++i)
245            ogreRoot_->loadPlugin((folder / plugins[i]).file_string());
246    }
247
248    void GraphicsManager::loadRenderer()
249    {
250        CCOUT(4) << "Configuring Renderer" << std::endl;
251
[7870]252        if (!ogreRoot_->restoreConfig() || Core::getInstance().getOgreConfigTimestamp() > Core::getInstance().getLastLevelTimestamp())
253        {
[2801]254            if (!ogreRoot_->showConfigDialog())
[7868]255                ThrowException(InitialisationFailed, "OGRE graphics configuration dialogue canceled.");
[7870]256            else
257                Core::getInstance().updateOgreConfigTimestamp();
258        }
[2801]259
260        CCOUT(4) << "Creating render window" << std::endl;
261
262        this->renderWindow_ = ogreRoot_->initialise(true, "Orxonox");
[5695]263        // Propagate the size of the new winodw
[3327]264        this->ogreWindowEventListener_->windowResized(renderWindow_);
[2801]265
[5695]266        Ogre::WindowEventUtilities::addWindowEventListener(this->renderWindow_, ogreWindowEventListener_.get());
[2801]267
[5695]268        // create a full screen default viewport
269        // Note: This may throw when adding a viewport with an existing z-order!
270        //       But in our case we only have one viewport for now anyway, therefore
271        //       no ScopeGuards or anything to handle exceptions.
272        this->viewport_ = this->renderWindow_->addViewport(0, 0);
273
[6524]274        Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(Ogre::MIP_UNLIMITED);
[2801]275
[5695]276        // add console commands
[7284]277        ModifyConsoleCommand(__CC_printScreen_name).setFunction(&GraphicsManager::printScreen, this);
[2801]278    }
279
[5929]280    void GraphicsManager::loadDebugOverlay()
281    {
282        // Load debug overlay to show info about fps and tick time
283        COUT(4) << "Loading Debug Overlay..." << std::endl;
284        debugOverlay_.reset(new XMLFile("debug.oxo"));
285        Loader::open(debugOverlay_.get());
286    }
287
288    /**
289    @note
290        A note about the Ogre::FrameListener: Even though we don't use them,
291        they still get called. However, the delta times are not correct (except
292        for timeSinceLastFrame, which is the most important). A little research
293        as shown that there is probably only one FrameListener that doesn't even
294        need the time. So we shouldn't run into problems.
295    */
[6417]296    void GraphicsManager::postUpdate(const Clock& time)
[2801]297    {
[5695]298        Ogre::FrameEvent evt;
299        evt.timeSinceLastFrame = time.getDeltaTime();
300        evt.timeSinceLastEvent = time.getDeltaTime(); // note: same time, but shouldn't matter anyway
301
302        // don't forget to call _fireFrameStarted to OGRE to make sure
303        // everything goes smoothly
304        ogreRoot_->_fireFrameStarted(evt);
305
306        // Pump messages in all registered RenderWindows
307        // This calls the WindowEventListener objects.
308        Ogre::WindowEventUtilities::messagePump();
309        // make sure the window stays active even when not focused
310        // (probably only necessary on windows)
311        this->renderWindow_->setActive(true);
312
313        // Time before rendering
314        uint64_t timeBeforeTick = time.getRealMicroseconds();
315
316        // Render frame
317        ogreRoot_->_updateAllRenderTargets();
318
319        uint64_t timeAfterTick = time.getRealMicroseconds();
320        // Subtract the time used for rendering from the tick time counter
[6502]321        Game::getInstance().subtractTickTime((int32_t)(timeAfterTick - timeBeforeTick));
[5695]322
323        // again, just to be sure OGRE works fine
324        ogreRoot_->_fireFrameEnded(evt); // note: uses the same time as _fireFrameStarted
[2801]325    }
326
[5695]327    void GraphicsManager::setCamera(Ogre::Camera* camera)
328    {
329        this->viewport_->setCamera(camera);
330    }
331
[2801]332    /**
333    @brief
334        Method called by the LogListener interface from Ogre.
335        We use it to capture Ogre log messages and handle it ourselves.
336    @param message
337        The message to be logged
338    @param lml
339        The message level the log is using
340    @param maskDebug
341        If we are printing to the console or not
342    @param logName
343        The name of this log (so you can have several listeners
344        for different logs, and identify them)
345    */
346    void GraphicsManager::messageLogged(const std::string& message,
347        Ogre::LogMessageLevel lml, bool maskDebug, const std::string& logName)
348    {
349        int orxonoxLevel;
[6417]350        std::string introduction;
351        // Do not show caught OGRE exceptions in front
352        if (message.find("EXCEPTION") != std::string::npos)
[2801]353        {
[6417]354            orxonoxLevel = OutputLevel::Debug;
355            introduction = "Ogre, caught exception: ";
[2801]356        }
[6417]357        else
358        {
359            switch (lml)
360            {
361            case Ogre::LML_TRIVIAL:
362                orxonoxLevel = this->ogreLogLevelTrivial_;
363                break;
364            case Ogre::LML_NORMAL:
365                orxonoxLevel = this->ogreLogLevelNormal_;
366                break;
367            case Ogre::LML_CRITICAL:
368                orxonoxLevel = this->ogreLogLevelCritical_;
369                break;
370            default:
371                orxonoxLevel = 0;
372            }
373            introduction = "Ogre: ";
374        }
[6105]375        OutputHandler::getOutStream(orxonoxLevel)
[6417]376            << introduction << message << std::endl;
[2801]377    }
378
[5695]379    size_t GraphicsManager::getRenderWindowHandle()
380    {
381        size_t windowHnd = 0;
382        renderWindow_->getCustomAttribute("WINDOW", &windowHnd);
383        return windowHnd;
384    }
385
386    bool GraphicsManager::isFullScreen() const
387    {
388        Ogre::ConfigOptionMap& options = ogreRoot_->getRenderSystem()->getConfigOptions();
389        if (options.find("Full Screen") != options.end())
390        {
391            if (options["Full Screen"].currentValue == "Yes")
392                return true;
393            else
394                return false;
395        }
396        else
397        {
398            COUT(0) << "Could not find 'Full Screen' render system option. Fix This!!!" << std::endl;
399            return false;
400        }
401    }
402
[2801]403    void GraphicsManager::printScreen()
404    {
405        assert(this->renderWindow_);
[6417]406        this->renderWindow_->writeContentsToTimestampedFile(PathConfig::getLogPathString() + "screenShot_", ".png");
[2801]407    }
[612]408}
Note: See TracBrowser for help on using the repository browser.