50711c744c9758cd1a15e965b6166582a5ec35b9
[chaz/yoink] / src / Moof / Engine.cc
1
2 /*******************************************************************************
3
4 Copyright (c) 2009, Charles McGarvey
5 All rights reserved.
6
7 Redistribution and use in source and binary forms, with or without
8 modification, are permitted provided that the following conditions are met:
9
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.
15
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.
26
27 *******************************************************************************/
28
29 #include <algorithm>
30 #include <cstdlib> // exit, srand
31 #include <ctime> // time
32 #include <list>
33 #include <string>
34
35 #include <AL/alc.h>
36 #include <SDL/SDL.h>
37 #include "fastevents.h"
38
39
40 #include "Engine.hh"
41 #include "Event.hh"
42 #include "Log.hh"
43 #include "Math.hh"
44 #include "Settings.hh"
45 #include "Timer.hh"
46
47
48 namespace Mf {
49
50
51 class Engine::Impl
52 {
53 public:
54
55 Impl() :
56 mError(Error::NONE),
57 mTimestep(0.01),
58 mPrintFps(false)
59 {
60 // first, initialize the libraries
61
62 #if defined(_WIN32) || defined(__WIN32__)
63 if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) != 0)
64 #else
65 if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTTHREAD) != 0)
66 #endif
67 {
68 const char* error = SDL_GetError();
69 mError.init(Error::SDL_INIT, error);
70 //throw Exception(Error::SDL_INIT, error);
71 }
72 else
73 {
74 char vdName[128];
75 SDL_VideoDriverName(vdName, sizeof(vdName));
76 logInfo << "initialized SDL; using video driver `"
77 << vdName << "'" << std::endl;
78 }
79
80 if (FE_Init() != 0)
81 {
82 const char* error = FE_GetError();
83 mError.init(Error::FASTEVENTS_INIT, error);
84 //throw Exception(Error::FASTEVENTS_INIT, error);
85 }
86
87 mAlDevice = alcOpenDevice(0);
88 mAlContext = alcCreateContext(mAlDevice, 0);
89 if (!mAlDevice || !mAlContext)
90 {
91 const char* error = alcGetString(mAlDevice,alcGetError(mAlDevice));
92 logError << "error while creating audio context: "
93 << error << std::endl;
94 }
95 else
96 {
97 alcMakeContextCurrent(mAlContext);
98 logInfo << "opened sound device `"
99 << alcGetString(mAlDevice, ALC_DEFAULT_DEVICE_SPECIFIER)
100 << "'" << std::endl;
101 }
102
103 // now load the settings the engine needs
104
105 Settings& settings = Settings::getInstance();
106
107 unsigned randomSeed;
108 if (settings.get("rngseed", randomSeed)) srand(randomSeed);
109 else srand(time(0));
110
111 Scalar timestep = 80.0;
112 settings.get("timestep", timestep);
113 mTimestep = 1.0 / timestep;
114
115 Scalar maxFps = 40.0;
116 settings.get("maxfps", maxFps);
117 mMaxFps = 1.0 / maxFps;
118 capFps();
119
120 settings.get("printfps", mPrintFps);
121 }
122
123 ~Impl()
124 {
125 // the video object must be destroyed before we can shutdown SDL
126 mVideo.reset();
127
128 alcMakeContextCurrent(0);
129 alcDestroyContext(mAlContext);
130 alcCloseDevice(mAlDevice);
131
132 FE_Quit();
133 SDL_Quit();
134 }
135
136
137 /**
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.
142 */
143
144 void run()
145 {
146 Scalar ticksNow = Timer::getTicks();
147
148 Scalar nextStep = ticksNow;
149 Scalar nextDraw = ticksNow;
150 Scalar nextFpsUpdate = ticksNow + 1.0;
151
152 Scalar totalTime = 0.0;
153 Scalar deltaTime = 0.0;
154 Scalar accumulator = mTimestep;
155
156 mFps = 0;
157 int frameAccum = 0;
158
159 do
160 {
161 Scalar newTicks = Timer::getTicks();
162 deltaTime = newTicks - ticksNow;
163 ticksNow = newTicks;
164
165 // don't slow the animation until 4Hz, which is unplayable anyway
166 if (deltaTime >= 0.25) deltaTime = 0.25;
167 accumulator += deltaTime;
168
169 Timer::fireIfExpired(ticksNow);
170 dispatchEvents();
171
172 while (accumulator >= mTimestep)
173 {
174 update(totalTime, mTimestep);
175
176 totalTime += mTimestep;
177 accumulator -= mTimestep;
178
179 nextStep += mTimestep;
180 }
181 if (ticksNow >= nextStep)
182 {
183 nextStep = ticksNow + mTimestep;
184 }
185
186 if (ticksNow >= nextDraw)
187 {
188 frameAccum++;
189
190 if (ticksNow >= nextFpsUpdate) // determine the actual fps
191 {
192 mFps = frameAccum;
193 frameAccum = 0;
194
195 nextFpsUpdate += 1.0;
196 if (ticksNow >= nextFpsUpdate)
197 {
198 nextFpsUpdate = ticksNow + 1.0;
199 }
200
201 if (mPrintFps)
202 {
203 logInfo << mFps << " fps" << std::endl;
204 }
205 }
206
207 draw(accumulator / mTimestep);
208 mVideo->swap();
209
210 nextDraw += mMaxFps;
211 if (ticksNow >= nextDraw)
212 {
213 // we missed some scheduled draws, so reset the schedule
214 nextDraw = ticksNow + mMaxFps;
215 }
216 }
217
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);
221 }
222 while (!mStack.empty());
223
224 mDispatch.dispatch("engine.stopping");
225 }
226
227 void dispatchEvents()
228 {
229 SDL_Event event;
230
231 while (FE_PollEvent(&event) == 1)
232 {
233 switch (event.type)
234 {
235 case SDL_KEYDOWN:
236 if (event.key.keysym.sym == SDLK_ESCAPE &&
237 (SDL_GetModState() & KMOD_CTRL) )
238 {
239 // emergency escape
240 logWarning("escape forced");
241 exit(1);
242 }
243 break;
244
245 case SDL_VIDEORESIZE:
246 mVideo->resize(event.resize.w, event.resize.h);
247 break;
248 }
249
250 handleEvent(event);
251 }
252 }
253
254
255 void update(Scalar t, Scalar dt)
256 {
257 for (mStackIt = mStack.begin(); mStackIt != mStack.end(); ++mStackIt)
258 {
259 (*mStackIt)->update(t, dt);
260 }
261 }
262
263 void draw(Scalar alpha)
264 {
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)
268 {
269 (*it)->draw(alpha);
270 }
271 }
272
273 void handleEvent(const Event& event)
274 {
275 for (mStackIt = mStack.begin(); mStackIt != mStack.end(); ++mStackIt)
276 {
277 if ((*mStackIt)->handleEvent(event)) break;
278 }
279 }
280
281
282 void push(LayerP layer)
283 {
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();
289 }
290
291 LayerP pop()
292 {
293 bool fixIt = false;
294 if (mStack.begin() == mStackIt) fixIt = true;
295
296 LayerP layer = mStack.front();
297 mStack.pop_front();
298 logInfo << "stack: " << mStack.size()
299 << " [popped " << layer.get() << "]" << std::endl;
300 layer->poppedFromEngine();
301
302 if (fixIt) mStackIt = --mStack.begin();
303
304 return layer;
305 }
306
307 LayerP pop(Layer* layer)
308 {
309 bool fixIt = false;
310
311 std::list<LayerP> layers;
312
313 std::list<LayerP>::iterator it;
314 for (it = mStack.begin(); it != mStack.end(); ++it)
315 {
316 layers.push_back(*it);
317
318 if (it == mStackIt) fixIt = true;
319
320 if ((*it).get() == layer)
321 {
322 ++it;
323 mStack.erase(mStack.begin(), it);
324
325 for (it = layers.begin(); it != layers.end(); ++it)
326 {
327 (*it)->poppedFromEngine();
328 logInfo << "stack: " << mStack.size()
329 << " [popped " << (*it).get() << "]" << std::endl;
330 }
331
332 if (fixIt) mStackIt = --mStack.begin();
333
334 return layers.back();
335 }
336 }
337
338 return LayerP();
339 }
340
341 void clear()
342 {
343 mStack.clear();
344 mStackIt = mStack.begin();
345 logInfo("stack: 0 [cleared]");
346 }
347
348
349 void capFps()
350 {
351 if (mMaxFps < mTimestep)
352 {
353 logWarning << "capping maximum fps to timestep ("
354 << mTimestep << ")" << std::endl;
355 mMaxFps = mTimestep;
356 }
357 }
358
359
360 Error mError;
361
362 VideoP mVideo;
363 Dispatch mDispatch;
364
365 ALCdevice* mAlDevice;
366 ALCcontext* mAlContext;
367
368 std::list<LayerP> mStack;
369 std::list<LayerP>::iterator mStackIt;
370
371 Scalar mTimestep;
372 Scalar mMaxFps;
373
374 int mFps;
375 bool mPrintFps;
376 };
377
378
379 Engine::Engine() :
380 // pass through
381 mImpl(new Engine::Impl) {}
382
383
384 const Error& Engine::getError() const
385 {
386 // pass through
387 return mImpl->mError;
388 }
389
390
391 void Engine::setVideo(VideoP video)
392 {
393 // pass through
394 mImpl->mVideo = video;
395 }
396
397 VideoP Engine::getVideo() const
398 {
399 return mImpl->mVideo;
400 }
401
402
403 void Engine::setTimestep(int ts)
404 {
405 mImpl->mTimestep = 1.0 / Scalar(ts);
406 mImpl->capFps();
407 }
408
409 int Engine::getTimestep() const
410 {
411 return int(1.0 / mImpl->mTimestep);
412 }
413
414
415 void Engine::setMaxFps(int maxFps)
416 {
417 mImpl->mMaxFps = 1.0 / Scalar(maxFps);
418 mImpl->capFps();
419 }
420
421 int Engine::getMaxFps() const
422 {
423 return int(1.0 / mImpl->mMaxFps);
424 }
425
426
427 int Engine::getFps() const
428 {
429 return mImpl->mFps;
430 }
431
432
433 void Engine::push(LayerP layer)
434 {
435 // pass through
436 mImpl->push(layer);
437 }
438
439 LayerP Engine::pop()
440 {
441 // pass through
442 return mImpl->pop();
443 }
444
445 LayerP Engine::pop(Layer* layer)
446 {
447 // pass through
448 return mImpl->pop(layer);
449 }
450
451 void Engine::clear()
452 {
453 // pass through
454 mImpl->clear();
455 }
456
457 int Engine::getSize() const
458 {
459 return mImpl->mStack.size();
460 }
461
462
463 void Engine::run()
464 {
465 // pass through
466 return mImpl->run();
467 }
468
469
470 Dispatch::Handler Engine::addHandler(const std::string& event,
471 const Dispatch::Function& callback)
472 {
473 return mImpl->mDispatch.addHandler(event, callback);
474 }
475
476 Dispatch::Handler Engine::addHandler(const std::string& event,
477 const Dispatch::Function& callback, Dispatch::Handler handler)
478 {
479 return mImpl->mDispatch.addHandler(event, callback, handler);
480 }
481
482 void Engine::dispatch(const std::string& event,
483 const Dispatch::Message* message)
484 {
485 mImpl->mDispatch.dispatch(event, message);
486 }
487
488
489 Engine engine;
490
491
492 } // namespace Mf
493
494 /** vim: set ts=4 sw=4 tw=80: *************************************************/
495
This page took 0.053331 seconds and 3 git commands to generate.