2 /*******************************************************************************
4 Copyright (c) 2009, Charles McGarvey
7 Redistribution and use in source and binary forms, with or without
8 modification, are permitted provided that the following conditions are met:
10 * Redistributions of source code must retain the above copyright notice,
11 this list of conditions and the following disclaimer.
12 * Redistributions in binary form must reproduce the above copyright notice,
13 this list of conditions and the following disclaimer in the documentation
14 and/or other materials provided with the distribution.
16 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
20 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
23 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *******************************************************************************/
30 #include <cstdlib> // exit, srand
31 #include <ctime> // time
37 #include "fastevents.h"
44 #include "Settings.hh"
60 // first, initialize the libraries
62 #if defined(_WIN32) || defined(__WIN32__)
63 if (SDL_Init(SDL_INIT_VIDEO
| SDL_INIT_TIMER
) != 0)
65 if (SDL_Init(SDL_INIT_VIDEO
| SDL_INIT_EVENTTHREAD
) != 0)
68 const char* error
= SDL_GetError();
69 mError
.init(Error::SDL_INIT
, error
);
70 //throw Exception(Error::SDL_INIT, error);
75 SDL_VideoDriverName(vdName
, sizeof(vdName
));
76 logInfo
<< "initialized SDL; using video driver `"
77 << vdName
<< "'" << std::endl
;
82 const char* error
= FE_GetError();
83 mError
.init(Error::FASTEVENTS_INIT
, error
);
84 //throw Exception(Error::FASTEVENTS_INIT, error);
87 mAlDevice
= alcOpenDevice(0);
88 mAlContext
= alcCreateContext(mAlDevice
, 0);
89 if (!mAlDevice
|| !mAlContext
)
91 const char* error
= alcGetString(mAlDevice
,alcGetError(mAlDevice
));
92 logError
<< "error while creating audio context: "
93 << error
<< std::endl
;
97 alcMakeContextCurrent(mAlContext
);
98 logInfo
<< "opened sound device `"
99 << alcGetString(mAlDevice
, ALC_DEFAULT_DEVICE_SPECIFIER
)
103 // now load the settings the engine needs
105 Settings
& settings
= Settings::getInstance();
108 if (settings
.get("rngseed", randomSeed
)) srand(randomSeed
);
111 Scalar timestep
= 80.0;
112 settings
.get("timestep", timestep
);
113 mTimestep
= 1.0 / timestep
;
115 Scalar maxFps
= 40.0;
116 settings
.get("maxfps", maxFps
);
117 mMaxFps
= 1.0 / maxFps
;
120 settings
.get("printfps", mPrintFps
);
125 // the video object must be destroyed before we can shutdown SDL
128 alcMakeContextCurrent(0);
129 alcDestroyContext(mAlContext
);
130 alcCloseDevice(mAlDevice
);
138 * The main loop. This just calls dispatchEvents(), update(), and draw()
139 * over and over again. The timing of the update and draw are decoupled.
140 * The actual frame rate is also calculated here. This function will return
141 * the exit code used to stop the loop.
146 Scalar ticksNow
= Timer::getTicks();
148 Scalar nextStep
= ticksNow
;
149 Scalar nextDraw
= ticksNow
;
150 Scalar nextFpsUpdate
= ticksNow
+ 1.0;
152 Scalar totalTime
= 0.0;
153 Scalar deltaTime
= 0.0;
154 Scalar accumulator
= mTimestep
;
161 Scalar newTicks
= Timer::getTicks();
162 deltaTime
= newTicks
- ticksNow
;
165 // don't slow the animation until 4Hz, which is unplayable anyway
166 if (deltaTime
>= 0.25) deltaTime
= 0.25;
167 accumulator
+= deltaTime
;
169 Timer::fireIfExpired(ticksNow
);
172 while (accumulator
>= mTimestep
)
174 update(totalTime
, mTimestep
);
176 totalTime
+= mTimestep
;
177 accumulator
-= mTimestep
;
179 nextStep
+= mTimestep
;
181 if (ticksNow
>= nextStep
)
183 nextStep
= ticksNow
+ mTimestep
;
186 if (ticksNow
>= nextDraw
)
190 if (ticksNow
>= nextFpsUpdate
) // determine the actual fps
195 nextFpsUpdate
+= 1.0;
196 if (ticksNow
>= nextFpsUpdate
)
198 nextFpsUpdate
= ticksNow
+ 1.0;
203 logInfo
<< mFps
<< " fps" << std::endl
;
207 draw(accumulator
/ mTimestep
);
211 if (ticksNow
>= nextDraw
)
213 // we missed some scheduled draws, so reset the schedule
214 nextDraw
= ticksNow
+ mMaxFps
;
218 // be a good citizen and give back what you don't need
219 Timer::sleep(std::min(std::min(nextStep
, nextDraw
),
220 Timer::getNextFire()), Timer::ACTUAL
);
222 while (!mStack
.empty());
224 mDispatch
.dispatch("engine.stopping");
227 void dispatchEvents()
231 while (FE_PollEvent(&event
) == 1)
236 if (event
.key
.keysym
.sym
== SDLK_ESCAPE
&&
237 (SDL_GetModState() & KMOD_CTRL
) )
240 logWarning("escape forced");
245 case SDL_VIDEORESIZE
:
246 mVideo
->resize(event
.resize
.w
, event
.resize
.h
);
255 void update(Scalar t
, Scalar dt
)
257 for (mStackIt
= mStack
.begin(); mStackIt
!= mStack
.end(); ++mStackIt
)
259 (*mStackIt
)->update(t
, dt
);
263 void draw(Scalar alpha
)
265 // FIXME - this will crash if the layer being drawn pops itself
266 std::list
<LayerP
>::reverse_iterator it
;
267 for (it
= mStack
.rbegin(); it
!= mStack
.rend(); ++it
)
273 void handleEvent(const Event
& event
)
275 for (mStackIt
= mStack
.begin(); mStackIt
!= mStack
.end(); ++mStackIt
)
277 if ((*mStackIt
)->handleEvent(event
)) break;
282 void push(LayerP layer
)
284 ASSERT(layer
&& "cannot push null layer");
285 mStack
.push_front(layer
);
286 logInfo
<< "stack: " << mStack
.size()
287 << " [pushed " << layer
.get() << "]" << std::endl
;
288 layer
->pushedOntoEngine();
294 if (mStack
.begin() == mStackIt
) fixIt
= true;
296 LayerP layer
= mStack
.front();
298 logInfo
<< "stack: " << mStack
.size()
299 << " [popped " << layer
.get() << "]" << std::endl
;
300 layer
->poppedFromEngine();
302 if (fixIt
) mStackIt
= --mStack
.begin();
307 LayerP
pop(Layer
* layer
)
311 std::list
<LayerP
> layers
;
313 std::list
<LayerP
>::iterator it
;
314 for (it
= mStack
.begin(); it
!= mStack
.end(); ++it
)
316 layers
.push_back(*it
);
318 if (it
== mStackIt
) fixIt
= true;
320 if ((*it
).get() == layer
)
323 mStack
.erase(mStack
.begin(), it
);
325 for (it
= layers
.begin(); it
!= layers
.end(); ++it
)
327 (*it
)->poppedFromEngine();
328 logInfo
<< "stack: " << mStack
.size()
329 << " [popped " << (*it
).get() << "]" << std::endl
;
332 if (fixIt
) mStackIt
= --mStack
.begin();
334 return layers
.back();
344 mStackIt
= mStack
.begin();
345 logInfo("stack: 0 [cleared]");
351 if (mMaxFps
< mTimestep
)
353 logWarning
<< "capping maximum fps to timestep ("
354 << mTimestep
<< ")" << std::endl
;
365 ALCdevice
* mAlDevice
;
366 ALCcontext
* mAlContext
;
368 std::list
<LayerP
> mStack
;
369 std::list
<LayerP
>::iterator mStackIt
;
381 mImpl(new Engine::Impl
) {}
384 const Error
& Engine::getError() const
387 return mImpl
->mError
;
391 void Engine::setVideo(VideoP video
)
394 mImpl
->mVideo
= video
;
397 VideoP
Engine::getVideo() const
399 return mImpl
->mVideo
;
403 void Engine::setTimestep(int ts
)
405 mImpl
->mTimestep
= 1.0 / Scalar(ts
);
409 int Engine::getTimestep() const
411 return int(1.0 / mImpl
->mTimestep
);
415 void Engine::setMaxFps(int maxFps
)
417 mImpl
->mMaxFps
= 1.0 / Scalar(maxFps
);
421 int Engine::getMaxFps() const
423 return int(1.0 / mImpl
->mMaxFps
);
427 int Engine::getFps() const
433 void Engine::push(LayerP layer
)
445 LayerP
Engine::pop(Layer
* layer
)
448 return mImpl
->pop(layer
);
457 int Engine::getSize() const
459 return mImpl
->mStack
.size();
470 Dispatch::Handler
Engine::addHandler(const std::string
& event
,
471 const Dispatch::Function
& callback
)
473 return mImpl
->mDispatch
.addHandler(event
, callback
);
476 Dispatch::Handler
Engine::addHandler(const std::string
& event
,
477 const Dispatch::Function
& callback
, Dispatch::Handler handler
)
479 return mImpl
->mDispatch
.addHandler(event
, callback
, handler
);
482 void Engine::dispatch(const std::string
& event
,
483 const Dispatch::Message
* message
)
485 mImpl
->mDispatch
.dispatch(event
, message
);
494 /** vim: set ts=4 sw=4 tw=80: *************************************************/