source: trunk/src/ticker.cpp @ 2183

Last change on this file since 2183 was 2183, checked in by sam, 7 years ago

build: fix the WTFPL site URL in all code comments.

  • Property svn:keywords set to Id
File size: 12.6 KB
Line 
1//
2// Lol Engine
3//
4// Copyright: (c) 2010-2012 Sam Hocevar <sam@hocevar.net>
5//   This program is free software; you can redistribute it and/or
6//   modify it under the terms of the Do What The Fuck You Want To
7//   Public License, Version 2, as published by Sam Hocevar. See
8//   http://www.wtfpl.net/ for more details.
9//
10
11#if defined HAVE_CONFIG_H
12#   include "config.h"
13#endif
14
15#include <cstdlib>
16#include <stdint.h>
17
18#include "core.h"
19
20namespace lol
21{
22
23/*
24 * Ticker implementation class
25 */
26
27static class TickerData
28{
29    friend class Ticker;
30
31public:
32    TickerData() :
33        todolist(0), autolist(0),
34        nentities(0),
35        frame(0), recording(0), deltatime(0), bias(0), fps(0),
36#if LOL_DEBUG
37        keepalive(0),
38#endif
39        quit(0), quitframe(0), quitdelay(20), panic(0)
40    {
41        for (int i = 0; i < Entity::ALLGROUP_END; i++)
42            list[i] = NULL;
43    }
44
45    ~TickerData()
46    {
47#if !LOL_RELEASE
48        if (nentities)
49            Log::Error("still %i entities in ticker\n", nentities);
50        if (autolist)
51        {
52            int count = 0;
53            for (Entity *e = autolist; e; e = e->m_autonext, count++)
54                ;
55            Log::Error("still %i autoreleased entities\n", count);
56        }
57        Log::Debug("%i frames required to quit\n",
58                frame - quitframe);
59#endif
60        gametick.Push(0);
61        disktick.Push(0);
62        delete gamethread;
63        delete diskthread;
64    }
65
66private:
67    /* Entity management */
68    Entity *todolist, *autolist;
69    Entity *list[Entity::ALLGROUP_END];
70    int nentities;
71
72    /* Fixed framerate management */
73    int frame, recording;
74    Timer timer;
75    float deltatime, bias, fps;
76#if LOL_DEBUG
77    float keepalive;
78#endif
79
80    /* Background threads */
81    static void *GameThreadMain(void *p);
82    static void *DrawThreadMain(void *p); /* unused */
83    static void *DiskThreadMain(void *p);
84    Thread *gamethread, *drawthread, *diskthread;
85    Queue<int> gametick, drawtick, disktick;
86
87    /* Shutdown management */
88    int quit, quitframe, quitdelay, panic;
89}
90tickerdata;
91
92static TickerData * const data = &tickerdata;
93
94/*
95 * Ticker public class
96 */
97
98void Ticker::Register(Entity *entity)
99{
100    /* If we are called from its constructor, the object's vtable is not
101     * ready yet, so we do not know which group this entity belongs to. Wait
102     * until the first tick. */
103    entity->m_gamenext = data->todolist;
104    data->todolist = entity;
105    /* Objects are autoreleased by default. Put them in a circular list. */
106    entity->m_autorelease = 1;
107    entity->m_autonext = data->autolist;
108    data->autolist = entity;
109    entity->m_ref = 1;
110
111    data->nentities++;
112}
113
114void Ticker::Ref(Entity *entity)
115{
116#if !LOL_RELEASE
117    if (!entity)
118    {
119        Log::Error("referencing NULL entity\n");
120        return;
121    }
122    if (entity->m_destroy)
123        Log::Error("referencing entity scheduled for destruction\n");
124#endif
125    if (entity->m_autorelease)
126    {
127        /* Get the entity out of the m_autorelease list. This is usually
128         * very fast since the first entry in autolist is the last
129         * registered entity. */
130        for (Entity *e = data->autolist, *prev = NULL; e;
131             prev = e, e = e->m_autonext)
132        {
133            if (e == entity)
134            {
135                (prev ? prev->m_autonext : data->autolist) = e->m_autonext;
136                break;
137            }
138        }
139        entity->m_autorelease = 0;
140    }
141    else
142        entity->m_ref++;
143}
144
145int Ticker::Unref(Entity *entity)
146{
147#if !LOL_RELEASE
148    if (!entity)
149    {
150        Log::Error("dereferencing NULL entity\n");
151        return 0;
152    }
153    if (entity->m_ref <= 0)
154        Log::Error("dereferencing unreferenced entity\n");
155    if (entity->m_autorelease)
156        Log::Error("dereferencing autoreleased entity\n");
157#endif
158    return --entity->m_ref;
159}
160
161void *TickerData::GameThreadMain(void * /* p */)
162{
163#if LOL_DEBUG
164    Log::Info("ticker game thread initialised\n");
165#endif
166
167    for (;;)
168    {
169        int tick = data->gametick.Pop();
170        if (!tick)
171            break;
172
173        Profiler::Stop(Profiler::STAT_TICK_FRAME);
174        Profiler::Start(Profiler::STAT_TICK_FRAME);
175
176        Profiler::Start(Profiler::STAT_TICK_GAME);
177
178#if 0
179        Log::Debug("-------------------------------------\n");
180        for (int i = 0; i < Entity::ALLGROUP_END; i++)
181        {
182            Log::Debug("%s Group %i\n",
183                       (i < Entity::GAMEGROUP_END) ? "Game" : "Draw", i);
184
185            for (Entity *e = data->list[i]; e; )
186            {
187                Log::Debug("  \\-- %s (m_ref %i, destroy %i)\n", e->GetName(), e->m_ref, e->m_destroy);
188                e = (i < Entity::GAMEGROUP_END) ? e->m_gamenext : e->m_drawnext;
189            }
190        }
191#endif
192
193        data->frame++;
194
195        /* If recording with fixed framerate, set deltatime to a fixed value */
196        if (data->recording && data->fps)
197        {
198            data->deltatime = 1.f / data->fps;
199        }
200        else
201        {
202            data->deltatime = data->timer.Get();
203            data->bias += data->deltatime;
204        }
205
206        /* Do not go below 15 fps */
207        if (data->deltatime > 1.f / 15.f)
208        {
209            data->deltatime = 1.f / 15.f;
210            data->bias = 0.f;
211        }
212
213#if LOL_DEBUG
214        data->keepalive += data->deltatime;
215        if (data->keepalive > 10.f)
216        {
217            Log::Info("ticker keepalive: tick!\n");
218            data->keepalive = 0.f;
219        }
220#endif
221
222        /* If shutdown is stuck, kick the first entity we meet and see
223         * whether it makes things better. Note that it is always a bug to
224         * have referenced entities after 20 frames, but at least this
225         * safeguard makes it possible to exit the program cleanly. */
226        if (data->quit && !((data->frame - data->quitframe) % data->quitdelay))
227        {
228            int n = 0;
229            data->panic = 2 * (data->panic + 1);
230
231            for (int i = 0; i < Entity::ALLGROUP_END && n < data->panic; i++)
232            for (Entity *e = data->list[i]; e && n < data->panic; e = e->m_gamenext)
233                if (e->m_ref)
234                {
235#if !LOL_RELEASE
236                    Log::Error("poking %s\n", e->GetName());
237#endif
238                    e->m_ref--;
239                    n++;
240                }
241
242#if !LOL_RELEASE
243            if (n)
244                Log::Error("%i entities stuck after %i frames, poked %i\n",
245                           data->nentities, data->quitdelay, n);
246#endif
247
248            data->quitdelay = data->quitdelay > 1 ? data->quitdelay / 2 : 1;
249        }
250
251        /* Garbage collect objects that can be destroyed. We can do this
252         * before inserting awaiting objects, because only objects already
253         * inthe tick lists can be marked for destruction. */
254        for (int i = 0; i < Entity::ALLGROUP_END; i++)
255            for (Entity *e = data->list[i], *prev = NULL; e; )
256            {
257                if (e->m_destroy && i < Entity::GAMEGROUP_END)
258                {
259                    /* If entity is to be destroyed, remove it from the
260                     * game tick list. */
261                    (prev ? prev->m_gamenext : data->list[i]) = e->m_gamenext;
262
263                    e = e->m_gamenext;
264                }
265                else if (e->m_destroy)
266                {
267                    /* If entity is to be destroyed, remove it from the
268                     * draw tick list and destroy it. */
269                    (prev ? prev->m_drawnext : data->list[i]) = e->m_drawnext;
270
271                    Entity *tmp = e;
272                    e = e->m_drawnext; /* Can only be in a draw group list */
273                    delete tmp;
274
275                    data->nentities--;
276                }
277                else
278                {
279                    if (e->m_ref <= 0 && i >= Entity::DRAWGROUP_BEGIN)
280                        e->m_destroy = 1;
281                    prev = e;
282                    e = (i < Entity::GAMEGROUP_END) ? e->m_gamenext : e->m_drawnext;
283                }
284            }
285
286        /* Insert waiting objects into the appropriate lists */
287        while (data->todolist)
288        {
289            Entity *e = data->todolist;
290            data->todolist = e->m_gamenext;
291
292            e->m_gamenext = data->list[e->m_gamegroup];
293            data->list[e->m_gamegroup] = e;
294            e->m_drawnext = data->list[e->m_drawgroup];
295            data->list[e->m_drawgroup] = e;
296        }
297
298        /* Tick objects for the game loop */
299        for (int i = Entity::GAMEGROUP_BEGIN; i < Entity::GAMEGROUP_END; i++)
300            for (Entity *e = data->list[i]; e; e = e->m_gamenext)
301                if (!e->m_destroy)
302                {
303#if !LOL_RELEASE
304                    if (e->m_tickstate != Entity::STATE_IDLE)
305                        Log::Error("entity %s [%p] not idle for game tick\n",
306                                   e->GetName(), e);
307                    e->m_tickstate = Entity::STATE_PRETICK_GAME;
308#endif
309                    e->TickGame(data->deltatime);
310#if !LOL_RELEASE
311                    if (e->m_tickstate != Entity::STATE_POSTTICK_GAME)
312                        Log::Error("entity %s [%p] missed super game tick\n",
313                                   e->GetName(), e);
314                    e->m_tickstate = Entity::STATE_IDLE;
315#endif
316                }
317
318        Profiler::Stop(Profiler::STAT_TICK_GAME);
319
320        data->drawtick.Push(1);
321    }
322
323    data->drawtick.Push(0);
324
325#if LOL_DEBUG
326    Log::Info("ticker game thread terminated\n");
327#endif
328
329    return NULL;
330}
331
332void *TickerData::DrawThreadMain(void * /* p */)
333{
334    for (;;)
335    {
336        int tick = data->drawtick.Pop();
337        if (!tick)
338            break;
339
340        data->gametick.Push(1);
341    }
342
343    return NULL;
344}
345
346void *TickerData::DiskThreadMain(void * /* p */)
347{
348    /* FIXME: temporary hack to avoid crashes on the PS3 */
349    data->disktick.Pop();
350
351    return NULL;
352}
353
354void Ticker::SetState(Entity * /* entity */, uint32_t /* state */)
355{
356
357}
358
359void Ticker::SetStateWhenMatch(Entity * /* entity */, uint32_t /* state */,
360                               Entity * /* other_entity */, uint32_t /* other_state */)
361{
362
363}
364
365void Ticker::Setup(float fps)
366{
367    data->fps = fps;
368
369    data->gamethread = new Thread(TickerData::GameThreadMain, NULL);
370    data->gametick.Push(1);
371
372    data->diskthread = new Thread(TickerData::DiskThreadMain, NULL);
373}
374
375void Ticker::TickDraw()
376{
377    data->drawtick.Pop();
378
379    Profiler::Start(Profiler::STAT_TICK_DRAW);
380
381    /* Tick objects for the draw loop */
382    for (int i = Entity::DRAWGROUP_BEGIN; i < Entity::DRAWGROUP_END; i++)
383    {
384        switch (i)
385        {
386        case Entity::DRAWGROUP_BEGIN:
387            Scene::GetDefault()->Reset();
388            Video::Clear(ClearMask::All);
389            break;
390        case Entity::DRAWGROUP_HUD:
391            Video::SetDepth(false);
392            break;
393        default:
394            Video::SetDepth(true);
395            break;
396        }
397
398        for (Entity *e = data->list[i]; e; e = e->m_drawnext)
399            if (!e->m_destroy)
400            {
401#if !LOL_RELEASE
402                if (e->m_tickstate != Entity::STATE_IDLE)
403                    Log::Error("entity %s [%p] not idle for draw tick\n",
404                               e->GetName(), e);
405                e->m_tickstate = Entity::STATE_PRETICK_DRAW;
406#endif
407                e->TickDraw(data->deltatime);
408#if !LOL_RELEASE
409                if (e->m_tickstate != Entity::STATE_POSTTICK_DRAW)
410                    Log::Error("entity %s [%p] missed super draw tick\n",
411                               e->GetName(), e);
412                e->m_tickstate = Entity::STATE_IDLE;
413#endif
414            }
415
416        /* Do this render step */
417        Scene::GetDefault()->Render();
418    }
419
420    Profiler::Stop(Profiler::STAT_TICK_DRAW);
421    Profiler::Start(Profiler::STAT_TICK_BLIT);
422
423    /* Signal game thread that it can carry on */
424    data->gametick.Push(1);
425
426    /* Clamp FPS */
427    Profiler::Stop(Profiler::STAT_TICK_BLIT);
428
429    /* If framerate is fixed, force wait time to 1/FPS. Otherwise, set wait
430     * time to 0. */
431    float frametime = data->fps ? 1.f / data->fps : 0.f;
432
433    if (frametime > data->bias + .2f)
434        frametime = data->bias + .2f; // Don't go below 5 fps
435    if (frametime > data->bias)
436        data->timer.Wait(frametime - data->bias);
437
438    /* If recording, do not try to compensate for lag. */
439    if (!data->recording)
440        data->bias -= frametime;
441}
442
443void Ticker::StartRecording()
444{
445    data->recording++;
446}
447
448void Ticker::StopRecording()
449{
450    data->recording--;
451}
452
453int Ticker::GetFrameNum()
454{
455    return data->frame;
456}
457
458void Ticker::Shutdown()
459{
460    /* We're bailing out. Release all m_autorelease objects. */
461    while (data->autolist)
462    {
463        data->autolist->m_ref--;
464        data->autolist = data->autolist->m_autonext;
465    }
466
467    data->quit = 1;
468    data->quitframe = data->frame;
469}
470
471int Ticker::Finished()
472{
473    return !data->nentities;
474}
475
476} /* namespace lol */
477
Note: See TracBrowser for help on using the repository browser.