]> Dogcows Code - chaz/yoink/blobdiff - src/Moof/Engine.cc
removed Random.{cc,hh}; obsoleted by cml
[chaz/yoink] / src / Moof / Engine.cc
index 16da8d40620edd59199a02e46ef43302113f8984..785cb4b41ed67ee342cf8df535f9e6726e5d3a35 100644 (file)
 *******************************************************************************/
 
 #include <algorithm>
-#include <cstdlib>                     // exit
+#include <cstdlib>                     // exit, srand
+#include <ctime>                       // time
 #include <list>
 #include <string>
 
+#include <AL/alc.h>
 #include <SDL/SDL.h>
 #include "fastevents.h"
-#include <AL/alut.h>
 
-#include "Dispatcher.hh"
+
 #include "Engine.hh"
 #include "Event.hh"
+#include "Exception.hh"
 #include "Log.hh"
-#include "Random.hh"
+#include "Math.hh"
 #include "Settings.hh"
 #include "Timer.hh"
-#include "Video.hh"
 
 
 namespace Mf {
@@ -51,57 +52,79 @@ namespace Mf {
 class Engine::Impl
 {
 public:
-       Impl(int argc, char* argv[], const std::string& name,
-                       const std::string& iconFile, const std::string& configFile,
-                       Engine& engine) :
-               interface(engine),
-               timestep(0.01),
-               printFps(false)
+
+       Impl(Engine& engine) :
+               mInterface(engine),
+               mTimestep(0.01),
+               mPrintFps(false)
        {
-#if defined(_WIN32) || defined (_WIN64) || defined(__WIN32__)
+               // first, initialize the libraries
+
+#if defined(_WIN32) || defined(__WIN32__)
                if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) != 0)
 #else
                if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTTHREAD) != 0)
 #endif
                {
-                       logError("sdl is complaining: %s", SDL_GetError());
-                       throw Exception(Exception::SDL_ERROR);
+                       const char* error = SDL_GetError();
+                       throw Exception(ErrorCode::SDL_INIT, error);
                }
+               else
+               {
+                       char vdName[128];
+                       SDL_VideoDriverName(vdName, sizeof(vdName));
+                       logDebug("initialized SDL; using video driver `%s'", vdName);
+               }
+
                if (FE_Init() != 0)
                {
-                       logError("fast events error: %s", FE_GetError());
-                       throw Exception(Exception::SDL_ERROR);
+                       const char* error = FE_GetError();
+                       throw Exception(ErrorCode::FASTEVENTS_INIT, error);
                }
-               alutInit(&argc, argv);
+
+               mAlDevice = alcOpenDevice(0);
+               mAlContext = alcCreateContext(mAlDevice, 0);
+               if (!mAlDevice || !mAlContext)
+               {
+                       const char* error = alcGetString(mAlDevice,alcGetError(mAlDevice));
+                       logError("error while creating audio context: %s", error);
+               }
+               else
+               {
+                       alcMakeContextCurrent(mAlContext);
+                       logDebug("opened sound device `%s'",
+                                       alcGetString(mAlDevice, ALC_DEFAULT_DEVICE_SPECIFIER));
+               }
+
+               // now load the settings the engine needs
 
                Settings& settings = Settings::getInstance();
-               settings.loadFromFile(configFile);
-               settings.parseArgs(argc, argv);
 
-               long randomSeed;
-               if (settings.get("rngseed", randomSeed)) setSeed(randomSeed);
-               else setSeed();
+               unsigned randomSeed;
+               if (settings.get("rngseed", randomSeed)) srand(randomSeed);
+               else srand(time(0));
 
-               Scalar timeStep = 80.0;
-               settings.get("timestep", timeStep);
-               timestep = 1.0 / timeStep;
+               Scalar timestep = 80.0;
+               settings.get("timestep", timestep);
+               mTimestep = 1.0 / timestep;
 
                Scalar maxFps = 40.0;
                settings.get("maxfps", maxFps);
-               drawRate = 1.0 / maxFps;
+               mMaxFps = 1.0 / maxFps;
+               capFps();
 
-               settings.get("printfps", printFps);
-
-               video = Video::alloc(name, iconFile);
-               video->makeActive();
+               settings.get("printfps", mPrintFps);
        }
 
        ~Impl()
        {
                // the video object must be destroyed before we can shutdown SDL
-               video.reset();
+               mVideo.reset();
+
+               alcMakeContextCurrent(0);
+               alcDestroyContext(mAlContext);
+               alcCloseDevice(mAlDevice);
 
-               alutExit();
                FE_Quit();
                SDL_Quit();
        }
@@ -124,9 +147,9 @@ public:
 
                Scalar totalTime = 0.0;
                Scalar deltaTime = 0.0;
-               Scalar accumulator = timestep;
+               Scalar accumulator = mTimestep;
 
-               fps = 0;
+               mFps = 0;
                int frameAccum = 0;
 
                do
@@ -135,24 +158,25 @@ public:
                        deltaTime = newTicks - ticksNow;
                        ticksNow = newTicks;
 
+                       // don't slow the animation until 4Hz, which is unplayable anyway
                        if (deltaTime >= 0.25) deltaTime = 0.25;
                        accumulator += deltaTime;
 
                        Timer::fireIfExpired(ticksNow);
+                       dispatchEvents();
 
-                       while (accumulator >= timestep)
+                       while (accumulator >= mTimestep)
                        {
-                               dispatchEvents();
-                               update(totalTime, timestep);
+                               update(totalTime, mTimestep);
 
-                               totalTime += timestep;
-                               accumulator -= timestep;
+                               totalTime += mTimestep;
+                               accumulator -= mTimestep;
 
-                               nextStep += timestep;
+                               nextStep += mTimestep;
                        }
                        if (ticksNow >= nextStep)
                        {
-                               nextStep = ticksNow + timestep;
+                               nextStep = ticksNow + mTimestep;
                        }
 
                        if (ticksNow >= nextDraw)
@@ -161,7 +185,7 @@ public:
 
                                if (ticksNow >= nextFpsUpdate) // determine the actual fps
                                {
-                                       fps = frameAccum;
+                                       mFps = frameAccum;
                                        frameAccum = 0;
 
                                        nextFpsUpdate += 1.0;
@@ -170,28 +194,28 @@ public:
                                                nextFpsUpdate = ticksNow + 1.0;
                                        }
 
-                                       if (printFps)
+                                       if (mPrintFps)
                                        {
-                                               logInfo("%d fps", fps);
+                                               logInfo("%d fps", mFps);
                                        }
                                }
 
-                               draw(accumulator / timestep);
-                               video->swap();
+                               draw(accumulator / mTimestep);
+                               mVideo->swap();
 
-                               nextDraw += drawRate;
+                               nextDraw += mMaxFps;
                                if (ticksNow >= nextDraw)
                                {
                                        // we missed some scheduled draws, so reset the schedule
-                                       nextDraw = ticksNow + drawRate;
+                                       nextDraw = ticksNow + mMaxFps;
                                }
                        }
 
                        // be a good citizen and give back what you don't need
                        Timer::sleep(std::min(std::min(nextStep, nextDraw),
-                                               Timer::getNextFire()), true);
+                                               Timer::getNextFire()), Timer::ACTUAL);
                }
-               while (!stack.empty());
+               while (!mStack.empty());
        }
 
        void dispatchEvents()
@@ -207,12 +231,13 @@ public:
                                                        (SDL_GetModState() & KMOD_CTRL) )
                                        {
                                                // emergency escape
-                                               exit(0);
+                                               logWarning("escape forced");
+                                               exit(1);
                                        }
                                        break;
 
                                case SDL_VIDEORESIZE:
-                                       video->resize(event.resize.w, event.resize.h);
+                                       mVideo->resize(event.resize.w, event.resize.h);
                                        break;
                        }
 
@@ -223,9 +248,9 @@ public:
 
        void update(Scalar t, Scalar dt)
        {
-               for (stackIt = stack.begin(); stackIt != stack.end(); ++stackIt)
+               for (mStackIt = mStack.begin(); mStackIt != mStack.end(); ++mStackIt)
                {
-                       (*stackIt)->update(t, dt);
+                       (*mStackIt)->update(mInterface, t, dt);
                }
        }
 
@@ -233,17 +258,17 @@ public:
        {
                // FIXME - this will crash if the layer being drawn pops itself
                std::list<LayerP>::reverse_iterator it;
-               for (it = stack.rbegin(); it != stack.rend(); ++it)
+               for (it = mStack.rbegin(); it != mStack.rend(); ++it)
                {
-                       (*it)->draw(alpha);
+                       (*it)->draw(mInterface, alpha);
                }
        }
 
        void handleEvent(const Event& event)
        {
-               for (stackIt = stack.begin(); stackIt != stack.end(); ++stackIt)
+               for (mStackIt = mStack.begin(); mStackIt != mStack.end(); ++mStackIt)
                {
-                       if ((*stackIt)->handleEvent(event)) break;
+                       if ((*mStackIt)->handleEvent(mInterface, event)) break;
                }
        }
 
@@ -251,52 +276,53 @@ public:
        void push(LayerP layer)
        {
                ASSERT(layer && "cannot push null layer");
-               stack.push_front(layer);
-               logInfo(" push: %d", stack.size());
-               layer->pushed(interface);
+               mStack.push_front(layer);
+               logDebug("stack: %d [pushed %X]", mStack.size(), layer.get());
+               layer->pushed(mInterface);
        }
 
        LayerP pop()
        {
                bool fixIt = false;
-               if (stack.begin() == stackIt) fixIt = true;
+               if (mStack.begin() == mStackIt) fixIt = true;
 
-               LayerP popped = stack.front();
-               stack.pop_front();
-               logInfo("  pop: %d", stack.size());
-               popped->popped(interface);
+               LayerP layer = mStack.front();
+               mStack.pop_front();
+               logDebug("stack: %d [popped %X]", mStack.size(), layer.get());
+               layer->popped(mInterface);
 
-               if (fixIt) stackIt = --stack.begin();
+               if (fixIt) mStackIt = --mStack.begin();
 
-               return popped;
+               return layer;
        }
 
        LayerP pop(Layer* layer)
        {
                bool fixIt = false;
 
-               std::list<LayerP> popped;
+               std::list<LayerP> layers;
 
                std::list<LayerP>::iterator it;
-               for (it = stack.begin(); it != stack.end(); ++it)
+               for (it = mStack.begin(); it != mStack.end(); ++it)
                {
-                       popped.push_back(*it);
+                       layers.push_back(*it);
 
-                       if (it == stackIt) fixIt = true;
+                       if (it == mStackIt) fixIt = true;
 
                        if ((*it).get() == layer)
                        {
                                ++it;
-                               stack.erase(stack.begin(), it);
+                               mStack.erase(mStack.begin(), it);
 
-                               for (it = popped.begin(); it != popped.end(); ++it)
+                               for (it = layers.begin(); it != layers.end(); ++it)
                                {
-                                       (*it)->popped(interface);
+                                       (*it)->popped(mInterface);
+                                       logDebug("stack: %d [popped %X]", mStack.size(), (*it).get());
                                }
 
-                               if (fixIt) stackIt = --stack.begin();
+                               if (fixIt) mStackIt = --mStack.begin();
 
-                               return popped.back();
+                               return layers.back();
                        }
                }
 
@@ -305,105 +331,146 @@ public:
 
        void clear()
        {
-               stack.clear();
-               stackIt = stack.begin();
-               logInfo("clear: %d", stack.size());
+               mStack.clear();
+               mStackIt = mStack.begin();
+               logDebug("stack: 0 [cleared]");
        }
 
 
-       Engine&                         interface;
+       void capFps()
+       {
+               if (mMaxFps < mTimestep)
+               {
+                       logWarning("capping maximum fps to timestep (%f)", mTimestep);
+                       mMaxFps = mTimestep;
+               }
+       }
 
-       VideoP                          video;
 
-       std::list<LayerP>                       stack;
-       std::list<LayerP>::iterator     stackIt;
+       Engine&                                         mInterface;
+       VideoP                                          mVideo;
+       Dispatch                                        mDispatch;
 
-       Scalar                          timestep;
-       Scalar                          drawRate;
+       ALCdevice*                                      mAlDevice;
+       ALCcontext*                                     mAlContext;
 
-       long                            fps;
-       bool                            printFps;
-};
+       std::list<LayerP>                       mStack;
+       std::list<LayerP>::iterator     mStackIt;
 
+       Scalar                                          mTimestep;
+       Scalar                                          mMaxFps;
 
-static Engine* instance = 0;
+       int                                                     mFps;
+       bool                                            mPrintFps;
+};
 
-Engine::Engine(int argc, char* argv[], const std::string& name,
-               const std::string& iconFile, const std::string& configFile) :
-       impl_(new Engine::Impl(argc, argv, name, iconFile, configFile, *this))
-{
-       instance = this;
-}
 
+Engine::Engine() :
+       // pass through
+       mImpl(new Engine::Impl(*this)) {}
 
 Engine& Engine::getInstance()
 {
-       ASSERT(instance && "dereferencing null pointer");
-       return *instance;
-       //static Engine engine;
-       //return engine;
+       static Engine engine;
+       return engine;
 }
 
 
-void Engine::run()
+void Engine::setVideo(VideoP video)
 {
-       return impl_->run();
+       // pass through
+       mImpl->mVideo = video;
 }
 
-void Engine::setTimestep(Scalar ts)
+VideoP Engine::getVideo() const
 {
-       impl_->timestep = ts;
+       return mImpl->mVideo;
 }
 
-Scalar Engine::getTimestep() const
+
+void Engine::setTimestep(int ts)
 {
-       return impl_->timestep;
+       mImpl->mTimestep = 1.0 / Scalar(ts);
+       mImpl->capFps();
 }
 
-void Engine::setMaxFrameRate(long maxFps)
+int Engine::getTimestep() const
 {
-       impl_->drawRate = 1.0 / Scalar(maxFps);
+       return int(1.0 / mImpl->mTimestep);
 }
 
-long Engine::getMaxFrameRate() const
+
+void Engine::setMaxFps(int maxFps)
 {
-       return long(1.0 / impl_->drawRate);
+       mImpl->mMaxFps = 1.0 / Scalar(maxFps);
+       mImpl->capFps();
 }
 
-
-Video& Engine::getVideo() const
+int Engine::getMaxFps() const
 {
-       return *impl_->video;
+       return int(1.0 / mImpl->mMaxFps);
 }
 
-long Engine::getFrameRate() const
+
+int Engine::getFps() const
 {
-       return impl_->fps;
+       return mImpl->mFps;
 }
 
 
 void Engine::push(LayerP layer)
 {
        // pass through
-       impl_->push(layer);
+       mImpl->push(layer);
 }
 
 LayerP Engine::pop()
 {
        // pass through
-       return impl_->pop();
+       return mImpl->pop();
 }
 
 LayerP Engine::pop(Layer* layer)
 {
        // pass through
-       return impl_->pop(layer);
+       return mImpl->pop(layer);
 }
 
 void Engine::clear()
 {
        // pass through
-       impl_->clear();
+       mImpl->clear();
+}
+
+int Engine::getSize() const
+{
+       return mImpl->mStack.size();
+}
+
+
+void Engine::run()
+{
+       // pass through
+       return mImpl->run();
+}
+
+
+Dispatch::Handler Engine::addHandler(const std::string& event,
+               const Dispatch::Function& callback)
+{
+       return mImpl->mDispatch.addHandler(event, callback);
+}
+
+Dispatch::Handler Engine::addHandler(const std::string& event,
+               const Dispatch::Function& callback, Dispatch::Handler handler)
+{
+       return mImpl->mDispatch.addHandler(event, callback, handler);
+}
+
+void Engine::dispatch(const std::string& event,
+               const Dispatch::Message* message)
+{
+       mImpl->mDispatch.dispatch(event, message);
 }
 
 
This page took 0.037253 seconds and 4 git commands to generate.