Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/kicklib2/src/libraries/core/GraphicsManager.cc @ 8283

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

Merged revisions 7940-7974 from kicklib to kicklib2.

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