Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/core5/src/libraries/core/GraphicsManager.cc @ 5855

Last change on this file since 5855 was 5855, checked in by rgrieder, 15 years ago

Moved Clock from core to util (used in Scope anyway).

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