Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/mergeFS18/src/libraries/core/GraphicsManager.cc @ 12264

Last change on this file since 12264 was 11795, checked in by landauf, 7 years ago

merged ogre1.9 (including cegui0.8) into new branch

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