Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/resource2/src/core/GraphicsManager.cc @ 5654

Last change on this file since 5654 was 5654, checked in by rgrieder, 15 years ago
  • Implemented file management via resource manager and loading of resource locations via XML. Changes made:
    • SoundManager loads via memory stream rather than via file
    • Loader uses LuaState::includeFile() to load an XML file and passes the lua tag remover function to its LuaState.
    • ConfigFileManager still loads with hard paths because the files are required before Ogre gets created
  • Renamed LuaBind to LuaState, deSingletonised it and added new features:
    • doFile(), doString(), includeFile(), includeString() where include will preparse the string with a function provided with LuaState::setIncludeParser
    • Moved lua tags replace function to Loader (since it's actually an XML related task)
    • Using data_path/lua/LuaInitScript.lua to provide the following functions
      • logMessage(level, message)
      • doFile, dofile, include (all working with relative paths but within the same resource group)
  • Modified Script class to work with LuaState and fixed its XML Loader
  • Adjusted all level and include files (both "include" and "dofile" lua commands)
  • Property svn:eol-style set to native
File size: 12.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/**
31@file
32@brief
33    Implementation of an partial interface to Ogre.
34*/
35
36#include "GraphicsManager.h"
37
38#include <fstream>
39#include <boost/filesystem.hpp>
40
41#include <OgreFrameListener.h>
42#include <OgreRoot.h>
43#include <OgreLogManager.h>
44#include <OgreException.h>
45#include <OgreRenderWindow.h>
46#include <OgreRenderSystem.h>
47#include <OgreResourceGroupManager.h>
48#include <OgreViewport.h>
49#include <OgreWindowEventUtilities.h>
50
51#include "SpecialConfig.h"
52#include "util/Exception.h"
53#include "util/StringUtils.h"
54#include "util/SubString.h"
55#include "Clock.h"
56#include "ConsoleCommand.h"
57#include "ConfigValueIncludes.h"
58#include "CoreIncludes.h"
59#include "Core.h"
60#include "Game.h"
61#include "GameMode.h"
62#include "Loader.h"
63#include "WindowEventListener.h"
64#include "XMLFile.h"
65
66namespace orxonox
67{
68    class OgreWindowEventListener : public Ogre::WindowEventListener
69    {
70    public:
71        void windowResized     (Ogre::RenderWindow* rw)
72            { orxonox::WindowEventListener::resizeWindow(rw->getWidth(), rw->getHeight()); }
73        void windowFocusChange (Ogre::RenderWindow* rw)
74            { orxonox::WindowEventListener::changeWindowFocus(); }
75        void windowClosed      (Ogre::RenderWindow* rw)
76            { orxonox::Game::getInstance().stop(); }
77        void windowMoved       (Ogre::RenderWindow* rw)
78            { orxonox::WindowEventListener::moveWindow(); }
79    };
80
81    GraphicsManager* GraphicsManager::singletonPtr_s = 0;
82
83    /**
84    @brief
85        Non-initialising constructor.
86    */
87    GraphicsManager::GraphicsManager(bool bLoadRenderer)
88        : renderWindow_(0)
89        , viewport_(0)
90        , ogreWindowEventListener_(new OgreWindowEventListener())
91    {
92        RegisterObject(GraphicsManager);
93
94        this->setConfigValues();
95
96        // Ogre setup procedure (creating Ogre::Root)
97        this->loadOgreRoot();
98        // load all the required plugins for Ogre
99        this->loadOgrePlugins();
100
101        // At first, add the root paths of the data directories as resource locations
102        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(Core::getDataPathString(), "FileSystem", "dataRoot", false);
103        // Load resources
104        resources_.reset(new XMLFile("resources.oxr", "dataRoot"));
105        Loader::open(resources_.get());
106
107        // Only for development runs
108        if (Core::isDevelopmentRun())
109        {
110            Ogre::ResourceGroupManager::getSingleton().addResourceLocation(Core::getExternalDataPathString(), "FileSystem", "externalDataRoot", false);
111            extResources_.reset(new XMLFile("resources.oxr", "externalDataRoot"));
112            Loader::open(extResources_.get());
113        }
114
115        if (bLoadRenderer)
116        {
117            // Reads the ogre config and creates the render window
118            this->upgradeToGraphics();
119        }
120    }
121
122    /**
123    @brief
124        Destruction is done by the member scoped_ptrs.
125    */
126    GraphicsManager::~GraphicsManager()
127    {
128        // TODO: Destroy the console command
129    }
130
131    void GraphicsManager::setConfigValues()
132    {
133        SetConfigValue(ogreConfigFile_,  "ogre.cfg")
134            .description("Location of the Ogre config file");
135        SetConfigValue(ogrePluginsDirectory_, specialConfig::ogrePluginsDirectory)
136            .description("Folder where the Ogre plugins are located.");
137        SetConfigValue(ogrePlugins_, specialConfig::ogrePlugins)
138            .description("Comma separated list of all plugins to load.");
139        SetConfigValue(ogreLogFile_,     "ogre.log")
140            .description("Logfile for messages from Ogre. Use \"\" to suppress log file creation.");
141        SetConfigValue(ogreLogLevelTrivial_ , 5)
142            .description("Corresponding orxonox debug level for ogre Trivial");
143        SetConfigValue(ogreLogLevelNormal_  , 4)
144            .description("Corresponding orxonox debug level for ogre Normal");
145        SetConfigValue(ogreLogLevelCritical_, 2)
146            .description("Corresponding orxonox debug level for ogre Critical");
147    }
148
149    /**
150    @brief
151        Loads the renderer and creates the render window if not yet done so.
152    @remarks
153        This operation is irreversible without recreating the GraphicsManager!
154    */
155    void GraphicsManager::upgradeToGraphics()
156    {
157        if (renderWindow_ != NULL)
158            return;
159
160        this->loadRenderer();
161
162        // RESOURCE MANAGEMENT
163
164        // Load graphical resources
165        resourcesGraphics_.reset(new XMLFile("resources_graphics.oxr", "dataRoot"));
166        Loader::open(resourcesGraphics_.get());
167
168        // Consider external data folder for dev runs
169        if (Core::isDevelopmentRun())
170        {
171            extResourcesGraphics_.reset(new XMLFile("resources_graphics.oxr", "externalDataRoot"));
172            Loader::open(extResourcesGraphics_.get());
173        }
174
175        // Initialise all resources
176        // Note: You can only do this once! Ogre will check whether a resource group has
177        // already been initialised. If you need to load resources later, you will have to
178        // choose another resource group.
179        Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
180    }
181
182    /**
183    @brief
184        Creates the Ogre Root object and sets up the ogre log.
185    */
186    void GraphicsManager::loadOgreRoot()
187    {
188        COUT(3) << "Setting up Ogre..." << std::endl;
189
190        if (ogreConfigFile_ == "")
191        {
192            COUT(2) << "Warning: Ogre config file set to \"\". Defaulting to config.cfg" << std::endl;
193            ModifyConfigValue(ogreConfigFile_, tset, "config.cfg");
194        }
195        if (ogreLogFile_ == "")
196        {
197            COUT(2) << "Warning: Ogre log file set to \"\". Defaulting to ogre.log" << std::endl;
198            ModifyConfigValue(ogreLogFile_, tset, "ogre.log");
199        }
200
201        boost::filesystem::path ogreConfigFilepath(Core::getConfigPath() / this->ogreConfigFile_);
202        boost::filesystem::path ogreLogFilepath(Core::getLogPath() / this->ogreLogFile_);
203
204        // create a new logManager
205        // Ogre::Root will detect that we've already created a Log
206        ogreLogger_.reset(new Ogre::LogManager());
207        COUT(4) << "Ogre LogManager created" << std::endl;
208
209        // create our own log that we can listen to
210        Ogre::Log *myLog;
211        myLog = ogreLogger_->createLog(ogreLogFilepath.string(), true, false, false);
212        COUT(4) << "Ogre Log created" << std::endl;
213
214        myLog->setLogDetail(Ogre::LL_BOREME);
215        myLog->addListener(this);
216
217        COUT(4) << "Creating Ogre Root..." << std::endl;
218
219        // check for config file existence because Ogre displays (caught) exceptions if not
220        if (!boost::filesystem::exists(ogreConfigFilepath))
221        {
222            // create a zero sized file
223            std::ofstream creator;
224            creator.open(ogreConfigFilepath.string().c_str());
225            creator.close();
226        }
227
228        // Leave plugins file empty. We're going to do that part manually later
229        ogreRoot_.reset(new Ogre::Root("", ogreConfigFilepath.string(), ogreLogFilepath.string()));
230
231        COUT(3) << "Ogre set up done." << std::endl;
232    }
233
234    void GraphicsManager::loadOgrePlugins()
235    {
236        // just to make sure the next statement doesn't segfault
237        if (ogrePluginsDirectory_ == "")
238            ogrePluginsDirectory_ = ".";
239
240        boost::filesystem::path folder(ogrePluginsDirectory_);
241        // Do some SubString magic to get the comma separated list of plugins
242        SubString plugins(ogrePlugins_, ",", " ", false, '\\', false, '"', false, '(', ')', false, '\0');
243        // Use backslash paths on Windows! file_string() already does that though.
244        for (unsigned int i = 0; i < plugins.size(); ++i)
245            ogreRoot_->loadPlugin((folder / plugins[i]).file_string());
246    }
247
248    void GraphicsManager::loadRenderer()
249    {
250        CCOUT(4) << "Configuring Renderer" << std::endl;
251
252        if (!ogreRoot_->restoreConfig())
253            if (!ogreRoot_->showConfigDialog())
254                ThrowException(InitialisationFailed, "OGRE graphics configuration dialogue failed.");
255
256        CCOUT(4) << "Creating render window" << std::endl;
257
258        this->renderWindow_ = ogreRoot_->initialise(true, "Orxonox");
259        // Propagate the size of the new winodw
260        this->ogreWindowEventListener_->windowResized(renderWindow_);
261
262        Ogre::WindowEventUtilities::addWindowEventListener(this->renderWindow_, ogreWindowEventListener_.get());
263
264        // create a full screen default viewport
265        // Note: This may throw when adding a viewport with an existing z-order!
266        //       But in our case we only have one viewport for now anyway, therefore
267        //       no ScopeGuards or anything to handle exceptions.
268        this->viewport_ = this->renderWindow_->addViewport(0, 0);
269
270        // add console commands
271        FunctorMember<GraphicsManager>* functor1 = createFunctor(&GraphicsManager::printScreen);
272        ccPrintScreen_ = createConsoleCommand(functor1->setObject(this), "printScreen");
273        CommandExecutor::addConsoleCommandShortcut(ccPrintScreen_);
274    }
275
276    void GraphicsManager::update(const Clock& time)
277    {
278        Ogre::FrameEvent evt;
279        evt.timeSinceLastFrame = time.getDeltaTime();
280        evt.timeSinceLastEvent = time.getDeltaTime(); // note: same time, but shouldn't matter anyway
281
282        // don't forget to call _fireFrameStarted to OGRE to make sure
283        // everything goes smoothly
284        ogreRoot_->_fireFrameStarted(evt);
285
286        // Pump messages in all registered RenderWindows
287        // This calls the WindowEventListener objects.
288        Ogre::WindowEventUtilities::messagePump();
289        // make sure the window stays active even when not focused
290        // (probably only necessary on windows)
291        this->renderWindow_->setActive(true);
292
293        // Time before rendering
294        uint64_t timeBeforeTick = time.getRealMicroseconds();
295
296        // Render frame
297        ogreRoot_->_updateAllRenderTargets();
298
299        uint64_t timeAfterTick = time.getRealMicroseconds();
300        // Subtract the time used for rendering from the tick time counter
301        Game::getInstance().subtractTickTime(timeAfterTick - timeBeforeTick);
302
303        // again, just to be sure OGRE works fine
304        ogreRoot_->_fireFrameEnded(evt); // note: uses the same time as _fireFrameStarted
305    }
306
307    void GraphicsManager::setCamera(Ogre::Camera* camera)
308    {
309        this->viewport_->setCamera(camera);
310    }
311
312    /**
313    @brief
314        Method called by the LogListener interface from Ogre.
315        We use it to capture Ogre log messages and handle it ourselves.
316    @param message
317        The message to be logged
318    @param lml
319        The message level the log is using
320    @param maskDebug
321        If we are printing to the console or not
322    @param logName
323        The name of this log (so you can have several listeners
324        for different logs, and identify them)
325    */
326    void GraphicsManager::messageLogged(const std::string& message,
327        Ogre::LogMessageLevel lml, bool maskDebug, const std::string& logName)
328    {
329        int orxonoxLevel;
330        switch (lml)
331        {
332        case Ogre::LML_TRIVIAL:
333            orxonoxLevel = this->ogreLogLevelTrivial_;
334            break;
335        case Ogre::LML_NORMAL:
336            orxonoxLevel = this->ogreLogLevelNormal_;
337            break;
338        case Ogre::LML_CRITICAL:
339            orxonoxLevel = this->ogreLogLevelCritical_;
340            break;
341        default:
342            orxonoxLevel = 0;
343        }
344        OutputHandler::getOutStream().setOutputLevel(orxonoxLevel)
345            << "Ogre: " << message << std::endl;
346    }
347
348    void GraphicsManager::printScreen()
349    {
350        assert(this->renderWindow_);
351       
352        this->renderWindow_->writeContentsToTimestampedFile(Core::getLogPathString() + "screenShot_", ".jpg");
353    }
354}
Note: See TracBrowser for help on using the repository browser.