Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/ois_update/src/libraries/core/GraphicsManager.cc @ 7664

Last change on this file since 7664 was 7664, checked in by youngk, 13 years ago

Corrected some serious bug in OpenAL Mac and reduced warnings.

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