Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

Merged revisions 7978 - 8096 from kicklib to kicklib2.

  • Property svn:eol-style set to native
File size: 20.7 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#if BOOST_FILESYSTEM_VERSION < 3
263            ogreRoot_->loadPlugin((folder / plugins[i]).file_string());
264#else
265            ogreRoot_->loadPlugin((folder / plugins[i]).string());
266#endif
267    }
268
269    void GraphicsManager::loadRenderer()
270    {
271        CCOUT(4) << "Configuring Renderer" << std::endl;
272
273        bool updatedConfig = Core::getInstance().getOgreConfigTimestamp() > Core::getInstance().getLastLevelTimestamp();
274        if (updatedConfig)
275            COUT(2) << "Ogre config file has changed, but no level was started since then. Displaying config dialogue again to verify the changes." << std::endl;
276
277        if (!ogreRoot_->restoreConfig() || updatedConfig)
278        {
279            if (!ogreRoot_->showConfigDialog())
280                ThrowException(InitialisationFailed, "OGRE graphics configuration dialogue canceled.");
281            else
282                Core::getInstance().updateOgreConfigTimestamp();
283        }
284
285        CCOUT(4) << "Creating render window" << std::endl;
286
287        this->renderWindow_ = ogreRoot_->initialise(true, "Orxonox");
288        // Propagate the size of the new winodw
289        this->ogreWindowEventListener_->windowResized(renderWindow_);
290
291        Ogre::WindowEventUtilities::addWindowEventListener(this->renderWindow_, ogreWindowEventListener_.get());
292
293// HACK
294#ifdef ORXONOX_PLATFORM_APPLE
295        //INFO: This will give our window focus, and not lock it to the terminal
296        ProcessSerialNumber psn = {0, kCurrentProcess};
297        TransformProcessType(&psn, kProcessTransformToForegroundApplication);
298        SetFrontProcess(&psn);
299#endif
300// End of HACK
301
302        // create a full screen default viewport
303        // Note: This may throw when adding a viewport with an existing z-order!
304        //       But in our case we only have one viewport for now anyway, therefore
305        //       no ScopeGuards or anything to handle exceptions.
306        this->viewport_ = this->renderWindow_->addViewport(0, 0);
307
308        Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(Ogre::MIP_UNLIMITED);
309
310        // add console commands
311        ModifyConsoleCommand(__CC_printScreen_name).setFunction(&GraphicsManager::printScreen, this);
312        ModifyConsoleCommand(__CC_GraphicsManager_group, __CC_setScreenResolution_name).setFunction(&GraphicsManager::setScreenResolution, this);
313        ModifyConsoleCommand(__CC_GraphicsManager_group, __CC_setFSAA_name).setFunction(&GraphicsManager::setFSAA, this);
314        ModifyConsoleCommand(__CC_GraphicsManager_group, __CC_setVSync_name).setFunction(&GraphicsManager::setVSync, this);
315    }
316
317    void GraphicsManager::loadDebugOverlay()
318    {
319        // Load debug overlay to show info about fps and tick time
320        COUT(4) << "Loading Debug Overlay..." << std::endl;
321        debugOverlay_.reset(new XMLFile("debug.oxo"));
322        Loader::open(debugOverlay_.get());
323    }
324
325    /**
326    @note
327        A note about the Ogre::FrameListener: Even though we don't use them,
328        they still get called.
329    */
330    void GraphicsManager::postUpdate(const Clock& time)
331    {
332        // Time before rendering
333        uint64_t timeBeforeTick = time.getRealMicroseconds();
334
335        // Ogre's time keeping object
336        Ogre::FrameEvent evt;
337
338        // Translate to Ogre float times before the update
339        float temp = lastFrameStartTime_;
340        lastFrameStartTime_ = (float)timeBeforeTick * 0.000001f;
341        evt.timeSinceLastFrame = lastFrameStartTime_ - temp;
342        evt.timeSinceLastEvent = lastFrameStartTime_ - lastFrameEndTime_;
343
344        // Ogre requires the time too
345        ogreRoot_->_fireFrameStarted(evt);
346
347        // Pump messages in all registered RenderWindows
348        // This calls the WindowEventListener objects.
349        Ogre::WindowEventUtilities::messagePump();
350        // Make sure the window stays active even when not focused
351        // (probably only necessary on windows)
352        this->renderWindow_->setActive(true);
353
354        // Render frame
355        ogreRoot_->_updateAllRenderTargets();
356
357        uint64_t timeAfterTick = time.getRealMicroseconds();
358        // Subtract the time used for rendering from the tick time counter
359        Game::getInstance().subtractTickTime((int32_t)(timeAfterTick - timeBeforeTick));
360
361        // Translate to Ogre float times after the update
362        temp = lastFrameEndTime_;
363        lastFrameEndTime_ = (float)timeBeforeTick * 0.000001f;
364        evt.timeSinceLastFrame = lastFrameEndTime_ - temp;
365        evt.timeSinceLastEvent = lastFrameEndTime_ - lastFrameStartTime_;
366
367        // Ogre also needs the time after the frame finished
368        ogreRoot_->_fireFrameEnded(evt);
369    }
370
371    void GraphicsManager::setCamera(Ogre::Camera* camera)
372    {
373        Ogre::Camera* oldCamera = this->viewport_->getCamera();
374
375        this->viewport_->setCamera(camera);
376        GUIManager::getInstance().setCamera(camera);
377
378        for (ObjectList<ViewportEventListener>::iterator it = ObjectList<ViewportEventListener>::begin(); it != ObjectList<ViewportEventListener>::end(); ++it)
379            it->cameraChanged(this->viewport_, oldCamera);
380    }
381
382    /**
383    @brief
384        Method called by the LogListener interface from Ogre.
385        We use it to capture Ogre log messages and handle it ourselves.
386    @param message
387        The message to be logged
388    @param lml
389        The message level the log is using
390    @param maskDebug
391        If we are printing to the console or not
392    @param logName
393        The name of this log (so you can have several listeners
394        for different logs, and identify them)
395    */
396    void GraphicsManager::messageLogged(const std::string& message,
397        Ogre::LogMessageLevel lml, bool maskDebug, const std::string& logName)
398    {
399        int orxonoxLevel;
400        std::string introduction;
401        // Do not show caught OGRE exceptions in front
402        if (message.find("EXCEPTION") != std::string::npos)
403        {
404            orxonoxLevel = OutputLevel::Debug;
405            introduction = "Ogre, caught exception: ";
406        }
407        else
408        {
409            switch (lml)
410            {
411            case Ogre::LML_TRIVIAL:
412                orxonoxLevel = this->ogreLogLevelTrivial_;
413                break;
414            case Ogre::LML_NORMAL:
415                orxonoxLevel = this->ogreLogLevelNormal_;
416                break;
417            case Ogre::LML_CRITICAL:
418                orxonoxLevel = this->ogreLogLevelCritical_;
419                break;
420            default:
421                orxonoxLevel = 0;
422            }
423            introduction = "Ogre: ";
424        }
425        OutputHandler::getOutStream(orxonoxLevel)
426            << introduction << message << std::endl;
427    }
428
429    size_t GraphicsManager::getRenderWindowHandle()
430    {
431        size_t windowHnd = 0;
432        renderWindow_->getCustomAttribute("WINDOW", &windowHnd);
433        return windowHnd;
434    }
435
436    bool GraphicsManager::isFullScreen() const
437    {
438        return this->renderWindow_->isFullScreen();
439    }
440
441    unsigned int GraphicsManager::getWindowWidth() const
442    {
443        return this->renderWindow_->getWidth();
444    }
445
446    unsigned int GraphicsManager::getWindowHeight() const
447    {
448        return this->renderWindow_->getHeight();
449    }
450
451    bool GraphicsManager::hasVSyncEnabled() const
452    {
453        Ogre::ConfigOptionMap& options = ogreRoot_->getRenderSystem()->getConfigOptions();
454        Ogre::ConfigOptionMap::iterator it = options.find("VSync");
455        if (it != options.end())
456            return (it->second.currentValue == "Yes");
457        else
458            return false;
459    }
460
461    std::string GraphicsManager::getFSAAMode() const
462    {
463        Ogre::ConfigOptionMap& options = ogreRoot_->getRenderSystem()->getConfigOptions();
464        Ogre::ConfigOptionMap::iterator it = options.find("FSAA");
465        if (it != options.end())
466            return it->second.currentValue;
467        else
468            return "";
469    }
470
471    std::string GraphicsManager::setScreenResolution(unsigned int width, unsigned int height, bool fullscreen)
472    {
473        // workaround to detect if the colour depth should be written to the config file
474        bool bWriteColourDepth = false;
475        Ogre::ConfigOptionMap& options = ogreRoot_->getRenderSystem()->getConfigOptions();
476        Ogre::ConfigOptionMap::iterator it = options.find("Video Mode");
477        if (it != options.end())
478            bWriteColourDepth = (it->second.currentValue.find('@') != std::string::npos);
479
480        if (bWriteColourDepth)
481        {
482            this->ogreRoot_->getRenderSystem()->setConfigOption("Video Mode", multi_cast<std::string>(width)
483                                                                    + " x " + multi_cast<std::string>(height)
484                                                                    + " @ " + multi_cast<std::string>(this->getRenderWindow()->getColourDepth()) + "-bit colour");
485        }
486        else
487        {
488            this->ogreRoot_->getRenderSystem()->setConfigOption("Video Mode", multi_cast<std::string>(width)
489                                                                    + " x " + multi_cast<std::string>(height));
490        }
491
492        this->ogreRoot_->getRenderSystem()->setConfigOption("Full Screen", fullscreen ? "Yes" : "No");
493
494        std::string validate = this->ogreRoot_->getRenderSystem()->validateConfigOptions();
495
496        if (validate == "")
497        {
498            GraphicsManager::getInstance().getRenderWindow()->setFullscreen(fullscreen, width, height);
499            this->ogreRoot_->saveConfig();
500            Core::getInstance().updateOgreConfigTimestamp();
501            // Also reload the input devices
502            InputManager::getInstance().reload();
503        }
504
505        return validate;
506    }
507
508    std::string GraphicsManager::setFSAA(const std::string& mode)
509    {
510        this->ogreRoot_->getRenderSystem()->setConfigOption("FSAA", mode);
511
512        std::string validate = this->ogreRoot_->getRenderSystem()->validateConfigOptions();
513
514        if (validate == "")
515        {
516            //this->ogreRoot_->getRenderSystem()->reinitialise(); // can't use this that easily, because it recreates the render window, invalidating renderWindow_
517            this->ogreRoot_->saveConfig();
518            Core::getInstance().updateOgreConfigTimestamp();
519        }
520
521        return validate;
522    }
523
524    std::string GraphicsManager::setVSync(bool vsync)
525    {
526        this->ogreRoot_->getRenderSystem()->setConfigOption("VSync", vsync ? "Yes" : "No");
527
528        std::string validate = this->ogreRoot_->getRenderSystem()->validateConfigOptions();
529
530        if (validate == "")
531        {
532            //this->ogreRoot_->getRenderSystem()->reinitialise(); // can't use this that easily, because it recreates the render window, invalidating renderWindow_
533            this->ogreRoot_->saveConfig();
534            Core::getInstance().updateOgreConfigTimestamp();
535        }
536
537        return validate;
538    }
539
540    void GraphicsManager::printScreen()
541    {
542        assert(this->renderWindow_);
543        this->renderWindow_->writeContentsToTimestampedFile(PathConfig::getLogPathString() + "screenShot_", ".png");
544    }
545}
Note: See TracBrowser for help on using the repository browser.