Debian Codegraph @

src/game_loop.c

raw symbols SCIP
1 /*
2 C-Dogs SDL
3 A port of the legendary (and fun) action/arcade cdogs.
4
5 Copyright (c) 2014, 2016-2018, 2021-2023 Cong Xu
6 All rights reserved.
7
8 Redistribution and use in source and binary forms, with or without
9 modification, are permitted provided that the following conditions are met:
10
11 Redistributions of source code must retain the above copyright notice, this
12 list of conditions and the following disclaimer.
13 Redistributions in binary form must reproduce the above copyright notice,
14 this list of conditions and the following disclaimer in the documentation
15 and/or other materials provided with the distribution.
16
17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
21 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 POSSIBILITY OF SUCH DAMAGE.
28 */
29 #include "game_loop.h"
30
31 #include <SDL_timer.h>
32
33 #include "config.h"
34 #include "events.h"
35 #include "net_client.h"
36 #include "net_server.h"
37 #include "sounds.h"
38
39 #ifdef __EMSCRIPTEN__
40 #include <autosave.h>
41 #include <cdogs/character_class.h>
42 #include <cdogs/config_io.h>
43 #include <cdogs/config_json.h>
44 #include <cdogs/files.h>
45 #include <cdogs/player_template.h>
46 #include <emscripten.h>
47 #include <hiscores.h>
48
49 bool emscripten_fs_ready = false;
50
51 void emscriptenLoadFiles()
52 {
53 // options.cnf
54 FILE *file_options = fopen(GetConfigFilePath(CONFIG_FILE), "r");
55 if (file_options)
56 {
57 fclose(file_options);
58 ConfigLoadJSON(&gConfig, GetConfigFilePath(CONFIG_FILE));
59 ConfigApply(&gConfig, NULL);
60 }
61 else
62 {
63 ConfigSave(&gConfig, GetConfigFilePath(CONFIG_FILE));
64 }
65
66 // autosave.json
67 FILE *file_autosave = fopen(GetConfigFilePath(AUTOSAVE_FILE), "r");
68 if (file_autosave)
69 {
70 fclose(file_autosave);
71 AutosaveLoad(&gAutosave, GetConfigFilePath(AUTOSAVE_FILE));
72 }
73 else
74 {
75 AutosaveSave(&gAutosave, GetConfigFilePath(AUTOSAVE_FILE));
76 }
77
78 // scores.dat
79 FILE *file_scores = fopen(GetConfigFilePath(SCORES_FILE), "r");
80 if (file_scores)
81 {
82 fclose(file_scores);
83 }
84
85 // players.cnf
86 FILE *file_players = fopen(GetConfigFilePath(PLAYER_TEMPLATE_FILE), "r");
87 if (file_players)
88 {
89 fclose(file_players);
90 PlayerTemplatesLoad(&gPlayerTemplates, &gCharacterClasses);
91 }
92 else
93 {
94 PlayerTemplatesSave(&gPlayerTemplates);
95 }
96 }
97
98 bool emscriptenPersistData()
99 {
100 if (emscripten_fs_ready)
101 return true;
102
103 if (emscripten_run_script_int("Module.syncdone") == 1)
104 {
105 FILE *config_file = fopen(GetConfigFilePath(CONFIG_FILE), "r");
106 if (config_file == NULL)
107 {
108 // persist Emscripten current data to Indexed Db
109 EM_ASM(Module.print("Start File sync.."); Module.syncdone = 0;
110 FS.syncfs(
111 false, function(err) {
112 assert(!err);
113 Module.print("End File sync..");
114 Module.syncdone = 1;
115 }););
116 emscriptenLoadFiles();
117 return false;
118 }
119 else
120 {
121 fclose(config_file);
122 emscripten_fs_ready = true;
123 emscriptenLoadFiles();
124 return true;
125 }
126 }
127 return false;
128 }
129 #endif
130
131 GameLoopData *GameLoopDataNew(
132 void *data, void (*onTerminate)(GameLoopData *),
133 void (*onEnter)(GameLoopData *), void (*onExit)(GameLoopData *),
134 void (*inputFunc)(GameLoopData *),
135 GameLoopResult (*updateFunc)(GameLoopData *, LoopRunner *),
136 void (*drawFunc)(GameLoopData *))
137 {
138 GameLoopData *g;
139 CCALLOC(g, sizeof *g);
140 g->Data = data;
141 g->OnTerminate = onTerminate;
142 g->OnEnter = onEnter;
143 g->OnExit = onExit;
144 g->InputFunc = inputFunc;
145 g->UpdateFunc = updateFunc;
146 g->DrawFunc = drawFunc;
147 g->FPS = 30;
148 return g;
149 }
150
151 static GameLoopData *GetCurrentLoop(LoopRunner *l);
152 static GameLoopData *GetParentLoop(LoopRunner *l);
153
154 LoopRunner LoopRunnerNew(void)
155 {
156 LoopRunner l;
157 CArrayInit(&l.Loops, sizeof(GameLoopData *));
158 return l;
159 }
160 static void GameLoopTerminate(GameLoopData *data);
161 void LoopRunnerTerminate(LoopRunner *l)
162 {
163 for (int i = (int)l->Loops.size - 1; i >= 0; i--)
164 {
165 GameLoopData *g = CArrayGet(&l->Loops, i);
166 GameLoopTerminate(g);
167 }
168 CArrayTerminate(&l->Loops);
169 }
170
171 static void GameLoopOnEnter(GameLoopData *data);
172 static void GameLoopOnExit(GameLoopData *data);
173 typedef struct
174 {
175 GameLoopResult Result;
176 Uint32 TicksNow;
177 Uint32 TicksElapsed;
178 int FrameDurationMs;
179 int FramesSkipped;
180 int MaxFrameskip;
181 } LoopRunParams;
182 typedef struct
183 {
184 LoopRunner *l;
185 GameLoopData *data;
186 LoopRunParams p;
187 } LoopRunInnerData;
188 static LoopRunParams LoopRunParamsNew(const GameLoopData *data);
189 static bool LoopRunParamsShouldSleep(LoopRunParams *p);
190 static bool LoopRunParamsShouldSkip(LoopRunParams *p);
191 bool LoopRunnerRunInner(LoopRunInnerData *ctx)
192 {
193 #ifndef __EMSCRIPTEN__
194 // Frame rate control
195 if (LoopRunParamsShouldSleep(&(ctx->p)))
196 {
197 SDL_Delay(1);
198 return true;
199 }
200 #endif
201
202 // Input
203 EventPoll(&gEventHandlers, ctx->p.TicksElapsed, NULL);
204 if (ctx->data->InputFunc)
205 {
206 ctx->data->InputFunc(ctx->data);
207 }
208
209 NetClientPoll(&gNetClient);
210 NetServerPoll(&gNetServer);
211
212 // Update
213 ctx->p.Result = ctx->data->UpdateFunc(ctx->data, ctx->l);
214 GameLoopData *newData = GetCurrentLoop(ctx->l);
215 if (newData == NULL)
216 {
217 return false;
218 }
219 else if (newData != ctx->data)
220 {
221 GameLoopData *parent = GetParentLoop(ctx->l);
222 CA_FOREACH(GameLoopData *, data, ctx->l->Loops)
223 if (*data == newData)
224 {
225 continue;
226 }
227 // Don't exit the parent yet if we need to draw it
228 if (*data == parent && newData->DrawParent && (*data)->DrawFunc)
229 {
230 continue;
231 }
232 GameLoopOnExit(*data);
233 CA_FOREACH_END()
234 ctx->data = newData;
235 GameLoopOnEnter(ctx->data);
236 ctx->p = LoopRunParamsNew(ctx->data);
237 return true;
238 }
239
240 NetServerFlush(&gNetServer);
241 NetClientFlush(&gNetClient);
242
243 bool draw = !ctx->data->HasDrawnFirst;
244 switch (ctx->p.Result)
245 {
246 case UPDATE_RESULT_OK:
247 // Do nothing
248 break;
249 case UPDATE_RESULT_DRAW:
250 draw = true;
251 break;
252 default:
253 CASSERT(false, "Unknown loop result");
254 break;
255 }
256 ctx->data->Frames++;
257 #ifndef __EMSCRIPTEN__
258 // frame skip
259 if (LoopRunParamsShouldSkip(&(ctx->p)))
260 {
261 return true;
262 }
263 #endif
264
265 // Draw
266 if (draw)
267 {
268 WindowContextPreRender(&gGraphicsDevice.gameWindow);
269 if (gGraphicsDevice.cachedConfig.SecondWindow)
270 {
271 WindowContextPreRender(&gGraphicsDevice.secondWindow);
272 }
273 if (ctx->data->DrawParent)
274 {
275 GameLoopData *parent = GetParentLoop(ctx->l);
276 if (parent && parent->DrawFunc)
277 {
278 GameLoopOnEnter(parent);
279 parent->DrawFunc(parent);
280 }
281 }
282 if (ctx->data->DrawFunc)
283 {
284 ctx->data->DrawFunc(ctx->data);
285 }
286 WindowContextPostRender(&gGraphicsDevice.gameWindow);
287 if (gGraphicsDevice.cachedConfig.SecondWindow)
288 {
289 WindowContextPostRender(&gGraphicsDevice.secondWindow);
290 }
291 ctx->data->HasDrawnFirst = true;
292 }
293
294 return true;
295 }
296
297 #ifdef __EMSCRIPTEN__
298 void EmscriptenMainLoop(void *arg)
299 {
300 if (!emscriptenPersistData())
301 return;
302
303 LoopRunnerRunInner((LoopRunInnerData *)arg);
304 }
305 #endif
306 void LoopRunnerRun(LoopRunner *l)
307 {
308 GameLoopData *data = GetCurrentLoop(l);
309 if (data == NULL)
310 {
311 return;
312 }
313 GameLoopOnEnter(data);
314
315 LoopRunInnerData ctx;
316 ctx.l = l;
317 ctx.data = data;
318 ctx.p = LoopRunParamsNew(data);
319
320 #ifdef __EMSCRIPTEN__
321 // TODO use GameLoopData->FPS instead of FPS_FRAMELIMIT?
322 emscripten_set_main_loop_arg(EmscriptenMainLoop, &ctx, FPS_FRAMELIMIT, 1);
323 #else
324 for (;;)
325 {
326 if (!LoopRunnerRunInner(&ctx))
327 {
328 break;
329 }
330 }
331 #endif
332 }
333 static LoopRunParams LoopRunParamsNew(const GameLoopData *data)
334 {
335 LoopRunParams p;
336 p.Result = UPDATE_RESULT_OK;
337 p.TicksNow = SDL_GetTicks();
338 p.TicksElapsed = 0;
339 p.FrameDurationMs = 1000 / data->FPS;
340 p.FramesSkipped = 0;
341 p.MaxFrameskip = data->FPS / 5;
342 return p;
343 }
344 static bool LoopRunParamsShouldSleep(LoopRunParams *p)
345 {
346 const Uint32 ticksThen = p->TicksNow;
347 p->TicksNow = SDL_GetTicks();
348 p->TicksElapsed += p->TicksNow - ticksThen;
349 return (int)p->TicksElapsed < p->FrameDurationMs;
350 }
351 static bool LoopRunParamsShouldSkip(LoopRunParams *p)
352 {
353 p->TicksElapsed -= p->FrameDurationMs;
354 // frame skip
355 if ((int)p->TicksElapsed > p->FrameDurationMs)
356 {
357 p->FramesSkipped++;
358 if (p->FramesSkipped == p->MaxFrameskip)
359 {
360 // We've skipped too many frames; give up
361 p->TicksElapsed = 0;
362 }
363 else
364 {
365 return true;
366 }
367 }
368 p->FramesSkipped = 0;
369 return false;
370 }
371
372 void LoopRunnerChange(LoopRunner *l, GameLoopData *newData)
373 {
374 LoopRunnerPop(l);
375 LoopRunnerPush(l, newData);
376 }
377 void LoopRunnerPush(LoopRunner *l, GameLoopData *newData)
378 {
379 CArrayPushBack(&l->Loops, &newData);
380 }
381 void LoopRunnerPop(LoopRunner *l)
382 {
383 GameLoopData *data = GetCurrentLoop(l);
384 GameLoopOnExit(data);
385 GameLoopTerminate(data);
386 CArrayDelete(&l->Loops, l->Loops.size - 1);
387 }
388
389 static void GameLoopTerminate(GameLoopData *data)
390 {
391 if (data->OnTerminate)
392 {
393 data->OnTerminate(data);
394 }
395 CFREE(data);
396 }
397
398 static void GameLoopOnEnter(GameLoopData *data)
399 {
400 if (!data->HasEntered && data->OnEnter)
401 {
402 data->OnEnter(data);
403 }
404 EventReset(&gEventHandlers);
405 data->HasEntered = true;
406 data->HasExited = false;
407 }
408 static void GameLoopOnExit(GameLoopData *data)
409 {
410 if (!data->HasExited && data->OnExit)
411 {
412 data->OnExit(data);
413 }
414 data->HasExited = true;
415 data->HasEntered = false;
416 }
417
418 static GameLoopData *GetCurrentLoop(LoopRunner *l)
419 {
420 if (l->Loops.size == 0)
421 {
422 return NULL;
423 }
424 return *(GameLoopData **)CArrayGet(&l->Loops, l->Loops.size - 1);
425 }
426 static GameLoopData *GetParentLoop(LoopRunner *l)
427 {
428 if (l->Loops.size <= 1)
429 {
430 return NULL;
431 }
432 return *(GameLoopData **)CArrayGet(&l->Loops, l->Loops.size - 2);
433 }