Debian Codegraph @

src/hiscores.c

raw symbols SCIP
1 /*
2 C-Dogs SDL
3 A port of the legendary (and fun) action/arcade cdogs.
4 Copyright (c) 2025 Cong Xu
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, this
11 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
19 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 POSSIBILITY OF SUCH DAMAGE.
27 */
28 #include "hiscores.h"
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <time.h>
34
35 #include <fcntl.h>
36 #include <sys/stat.h>
37 #include <sys/types.h>
38
39 #include <cdogs/draw/draw_actor.h>
40 #include <cdogs/events.h>
41 #include <cdogs/files.h>
42 #include <cdogs/font.h>
43 #include <cdogs/log.h>
44 #include <cdogs/yajl_utils.h>
45
46 #include "base64/base64.h"
47
48 #ifdef __EMSCRIPTEN__
49 #include <emscripten.h>
50 #endif
51
52 #define MAX_ENTRY 20
53
54 typedef struct
55 {
56 char *Name;
57 time_t Time;
58 Character Character;
59 NPlayerStats Stats;
60 WeaponUsages WeaponUsages;
61 } HighScoreEntry;
62 // High score structure is:
63 // campaign name > entries, sorted by score
64 // TODO: merge with autosaves
65 static map_t LoadHighScores(void);
66 static void SaveHighScores(map_t highScores);
67
68 // Get player high score if it applies, or 0 otherwise
69 static int GetPlayerHighScore(const Campaign *co, const PlayerData *p)
70 {
71 const bool isPlayerComplete =
72 (!co->IsQuit && !p->survived) || co->IsComplete;
73 if (isPlayerComplete && p->IsLocal && IsPlayerHuman(p))
74 {
75 return p->Totals.Score;
76 }
77 return 0;
78 }
79
80 // Dummy screen to calculate high scores and switch to high scores screens if
81 // required
82 typedef struct
83 {
84 Campaign *co;
85 GraphicsDevice *g;
86 } HighScoresScreenData;
87 static void HighScoresScreenTerminate(GameLoopData *data);
88 static GameLoopResult HighScoresScreenUpdate(
89 GameLoopData *data, LoopRunner *l);
90 GameLoopData *HighScoresScreen(Campaign *co, GraphicsDevice *g)
91 {
92 HighScoresScreenData *data;
93 CMALLOC(data, sizeof *data);
94 data->co = co;
95 data->g = g;
96 return GameLoopDataNew(
97 data, HighScoresScreenTerminate, NULL, NULL, NULL,
98 HighScoresScreenUpdate, NULL);
99 }
100 static void HighScoresScreenTerminate(GameLoopData *data)
101 {
102 HighScoresScreenData *hData = data->Data;
103 CFREE(hData);
104 }
105 static bool EnterHighScore(const PlayerData *data, CArray *scores);
106 static GameLoopData *DisplayAllTimeHighScores(
107 GraphicsDevice *graphics, CArray *scores);
108 static GameLoopResult HighScoresScreenUpdate(GameLoopData *data, LoopRunner *l)
109 {
110 // Make copy before popping loop
111 HighScoresScreenData hData = *(HighScoresScreenData *)data->Data;
112 LoopRunnerPop(l);
113 if (!IsPVP(hData.co->Entry.Mode) &&
114 GetNumPlayers(PLAYER_ANY, false, true) > 0)
115 {
116 map_t highScores = LoadHighScores();
117 CArray *scores = NULL;
118 if (hashmap_get(highScores, hData.co->Entry.Path, (any_t *)&scores) ==
119 MAP_MISSING)
120 {
121 CMALLOC(scores, sizeof *scores);
122 CArrayInit(scores, sizeof(HighScoreEntry));
123 hashmap_put(highScores, hData.co->Entry.Path, scores);
124 }
125
126 bool allTime = false;
127 CA_FOREACH(PlayerData, p, gPlayerDatas)
128 if (GetPlayerHighScore(hData.co, p) > 0)
129 {
130 if (EnterHighScore(p, scores))
131 {
132 allTime = true;
133 }
134 }
135
136 if (!p->survived)
137 {
138 // Reset scores because we died :(
139 memset(&p->Totals, 0, sizeof p->Totals);
140 p->missions = 0;
141 }
142 else
143 {
144 p->missions++;
145 }
146 p->lastMission = hData.co->MissionIndex;
147 CA_FOREACH_END()
148 SaveHighScores(highScores);
149
150 // Show high scores screen if high enough
151 if (allTime)
152 {
153 LoopRunnerPush(l, DisplayAllTimeHighScores(hData.g, scores));
154 }
155 }
156
157 return UPDATE_RESULT_OK;
158 }
159
160 static bool EnterHighScore(const PlayerData *data, CArray *scores)
161 {
162 // Find insertion point based on score
163 HighScoreEntry *entry = NULL;
164 CA_FOREACH(const HighScoreEntry, e, *scores)
165 if (e->Stats.Score <= data->Totals.Score)
166 {
167 HighScoreEntry new;
168 memset(&new, 0, sizeof new);
169 entry = CArrayInsert(scores, _ca_index, &new);
170 break;
171 }
172 CA_FOREACH_END()
173 if (entry == NULL)
174 {
175 if (scores->size >= MAX_ENTRY)
176 {
177 // score not high enough; exit
178 return false;
179 }
180 HighScoreEntry new;
181 memset(&new, 0, sizeof new);
182 entry = CArrayPushBack(scores, &new);
183 }
184 // TODO: get existing entry
185 CSTRDUP(entry->Name, data->name);
186 CharacterCopy(&entry->Character, &data->Char, NULL);
187 entry->Stats = data->Totals;
188 entry->WeaponUsages = hashmap_copy(data->WeaponUsages, NULL);
189 return true;
190 }
191
192 static void DisplayAt(int x, int y, const char *s, int hilite)
193 {
194 color_t mask = hilite ? colorRed : colorWhite;
195 FontStrMask(s, svec2i(x, y), mask);
196 }
197
198 #define INDEX_OFFSET 0
199 #define SCORE_OFFSET (INDEX_OFFSET + 25)
200 #define TIME_OFFSET (SCORE_OFFSET + 30)
201 #define KILLS_OFFSET (TIME_OFFSET + 20)
202 #define ACC_OFFSET (KILLS_OFFSET + 20)
203 #define FAV_WEP_OFFSET (ACC_OFFSET + 30)
204 #define FACE_OFFSET (FAV_WEP_OFFSET + 10)
205 #define NAME_OFFSET (FACE_OFFSET + 10)
206
207 static int DisplayEntry(
208 const int x, const int y, const int idx, const HighScoreEntry *e,
209 const bool hilite)
210 {
211 char s[10];
212
213 sprintf(s, "%d.", idx + 1);
214 DisplayAt(x + INDEX_OFFSET - FontStrW(s), y, s, hilite);
215 sprintf(s, "%d", (int)e->Stats.Score);
216 DisplayAt(x + SCORE_OFFSET - FontStrW(s), y, s, hilite);
217 const int timeSeconds = e->Stats.TimeTicks / FPS_FRAMELIMIT;
218 const int centiseconds =
219 (e->Stats.TimeTicks - timeSeconds * FPS_FRAMELIMIT) * 100 /
220 FPS_FRAMELIMIT;
221 sprintf(
222 s, "%d:%02d.%02d", timeSeconds / 60, timeSeconds % 60, centiseconds);
223 DisplayAt(x + TIME_OFFSET - FontStrW(s), y, s, hilite);
224 sprintf(s, "%d", (int)e->Stats.Kills);
225 DisplayAt(x + KILLS_OFFSET - FontStrW(s), y, s, hilite);
226 sprintf(s, "%d%%", (int)(WeaponUsagesGetAccuracy(e->WeaponUsages) * 100));
227 DisplayAt(x + ACC_OFFSET - FontStrW(s), y, s, hilite);
228 const WeaponClass *wc = WeaponUsagesGetFavorite(e->WeaponUsages);
229 if (wc && wc->Icon)
230 {
231 PicRender(
232 wc->Icon, gGraphicsDevice.gameWindow.renderer,
233 svec2i(x + FAV_WEP_OFFSET - 15, y), colorWhite, 0, svec2_one(),
234 SDL_FLIP_NONE, Rect2iZero());
235 }
236 DrawHead(
237 gGraphicsDevice.gameWindow.renderer, &e->Character, DIRECTION_DOWN,
238 svec2i(x + FACE_OFFSET, y + 4));
239 DisplayAt(x + NAME_OFFSET, y, e->Name, hilite);
240
241 return 1 + FontH();
242 }
243
244 static void DisplayPage(const CArray *entries)
245 {
246 int x = 60;
247 int y = 5 + FontH();
248
249 FontStr("High Scores:", svec2i(5, 5));
250
251 // Display headings
252 const char *s;
253 s = "Rank";
254 DisplayAt(x + INDEX_OFFSET - FontStrW(s), y, s, false);
255 s = "Score";
256 DisplayAt(x + SCORE_OFFSET - FontStrW(s), y, s, false);
257 s = "Time";
258 DisplayAt(x + TIME_OFFSET - FontStrW(s), y, s, false);
259 s = "Kills";
260 DisplayAt(x + KILLS_OFFSET - FontStrW(s), y, s, false);
261 s = "Acc.";
262 DisplayAt(x + ACC_OFFSET - FontStrW(s), y, s, false);
263 s = "Fav.Gun";
264 DisplayAt(x + FAV_WEP_OFFSET - FontStrW(s), y, s, false);
265 s = "Name";
266 DisplayAt(x + NAME_OFFSET, y, s, false);
267 y += 5 + FontH();
268
269 // Find all the high scores for local players
270 int localScores[MAX_LOCAL_PLAYERS];
271 memset(localScores, 0, sizeof localScores);
272 int pIdx = 0;
273 CA_FOREACH(const PlayerData, p, gPlayerDatas)
274 const int score = GetPlayerHighScore(&gCampaign, p);
275 if (score > 0)
276 {
277 localScores[pIdx] = score;
278 pIdx++;
279 }
280 CA_FOREACH_END()
281
282 int idx = 0;
283 CA_FOREACH(const HighScoreEntry, e, *entries)
284 bool isHighlighted = false;
285 for (int i = 0; i < MAX_LOCAL_PLAYERS; i++)
286 {
287 if (e->Stats.Score == localScores[i])
288 {
289 isHighlighted = true;
290 localScores[i] = 0;
291 break;
292 }
293 }
294 y += DisplayEntry(x, y, idx, e, isHighlighted);
295 if (y > 198 - FontH())
296 {
297 y = 20;
298 x += 100;
299 }
300 idx++;
301 CA_FOREACH_END()
302 }
303 static void HighScoreTerminate(GameLoopData *data);
304 static GameLoopResult HighScoreUpdate(GameLoopData *data, LoopRunner *l);
305 static void HighScoreDraw(GameLoopData *data);
306 static GameLoopData *DisplayAllTimeHighScores(
307 GraphicsDevice *graphics, CArray *scores)
308 {
309 HighScoresData *data;
310 CMALLOC(data, sizeof *data);
311 data->g = graphics;
312 // Take a copy of the scores as the parent will get destroyed
313 CArrayInit(&data->scores, sizeof(HighScoreEntry));
314 CArrayCopy(&data->scores, scores);
315 return GameLoopDataNew(
316 data, HighScoreTerminate, NULL, NULL, NULL, HighScoreUpdate,
317 HighScoreDraw);
318 }
319 static void HighScoreTerminate(GameLoopData *data)
320 {
321 HighScoresData *hData = data->Data;
322 HighScoresDataTerminate(hData);
323 CFREE(hData);
324 }
325 static void HighScoreDraw(GameLoopData *data)
326 {
327 HighScoresData *hData = data->Data;
328
329 HighScoresDraw(hData);
330 }
331 static GameLoopResult HighScoreUpdate(GameLoopData *data, LoopRunner *l)
332 {
333 UNUSED(data);
334 const EventWaitResult result = EventWaitForAnyKeyOrButton();
335
336 if (result != EVENT_WAIT_CONTINUE)
337 {
338 LoopRunnerPop(l);
339 }
340 return UPDATE_RESULT_OK;
341 }
342
343 typedef struct
344 {
345 yajl_gen g;
346 map_t highScores;
347 } SaveHighScoresData;
348 static int SaveWeaponUsage(any_t data, any_t item);
349 static int SaveHighScoreEntries(any_t data, any_t key)
350 {
351 SaveHighScoresData *sData = data;
352 yajl_gen g = sData->g;
353 CArray *entries;
354 const int error =
355 hashmap_get(sData->highScores, (const char *)key, (any_t *)&entries);
356 if (error != MAP_OK)
357 {
358 CASSERT(false, "cannot find high score entry");
359 return error;
360 }
361
362 #define YAJL_CHECK(func) \
363 { \
364 yajl_gen_status _status = func; \
365 if (_status != yajl_gen_status_ok) \
366 { \
367 LOG(LM_MAIN, LL_ERROR, \
368 "JSON generator error for high score %s: %d\n", \
369 (const char *)key, (int)_status); \
370 return MAP_MISSING; \
371 } \
372 }
373 YAJL_CHECK(yajl_gen_string(g, key, strlen(key)));
374 YAJL_CHECK(yajl_gen_array_open(g));
375
376 CA_FOREACH(const HighScoreEntry, entry, *entries)
377
378 // Save entry as a base64-encoded YAJL string
379 yajl_gen g2 = yajl_gen_alloc(NULL);
380 if (g2 == NULL)
381 {
382 LOG(LM_MAIN, LL_ERROR,
383 "Unable to alloc JSON generator for saving high score entry\n");
384 return MAP_MISSING;
385 }
386 YAJL_CHECK(yajl_gen_map_open(g2));
387
388 YAJL_CHECK(YAJLAddStringPair(g2, "Name", entry->Name));
389 YAJL_CHECK(YAJLAddIntPair(g2, "Time", (int)entry->Time));
390
391 YAJL_CHECK(yajl_gen_string(
392 g2, (const unsigned char *)"Character", strlen("Character")));
393 if (!CharacterSave(g2, &entry->Character))
394 {
395 return MAP_MISSING;
396 }
397
398 YAJL_CHECK(
399 yajl_gen_string(g2, (const unsigned char *)"Stats", strlen("Stats")));
400 YAJL_CHECK(yajl_gen_map_open(g2));
401 YAJL_CHECK(YAJLAddIntPair(g2, "Score", entry->Stats.Score));
402 YAJL_CHECK(YAJLAddIntPair(g2, "Kills", entry->Stats.Kills));
403 YAJL_CHECK(YAJLAddIntPair(g2, "Suicides", entry->Stats.Suicides));
404 YAJL_CHECK(YAJLAddIntPair(g2, "Friendlies", entry->Stats.Friendlies));
405 YAJL_CHECK(YAJLAddIntPair(g2, "TimeTicks", entry->Stats.TimeTicks));
406 YAJL_CHECK(yajl_gen_map_close(g2));
407
408 YAJL_CHECK(yajl_gen_string(
409 g2, (const unsigned char *)"WeaponUsages", strlen("WeaponUsages")));
410 YAJL_CHECK(yajl_gen_map_open(g2));
411 const int res = hashmap_iterate(entry->WeaponUsages, SaveWeaponUsage, g2);
412 if (res != MAP_OK)
413 {
414 return res;
415 }
416 YAJL_CHECK(yajl_gen_map_close(g2));
417
418 YAJL_CHECK(yajl_gen_map_close(g2));
419
420 // Convert to base64 string
421 const char *buf;
422 size_t len;
423 yajl_gen_get_buf(g2, (const unsigned char **)&buf, &len);
424 char *encodeOut;
425 CMALLOC(encodeOut, BASE64_ENCODE_OUT_SIZE(len));
426 const unsigned encodeLen = base64_encode((const unsigned char *)buf, (unsigned int)len, encodeOut);
427 YAJL_CHECK(
428 yajl_gen_string(g, (const unsigned char *)encodeOut, encodeLen));
429 if (g2)
430 {
431 yajl_gen_clear(g2);
432 yajl_gen_free(g2);
433 }
434 CFREE(encodeOut);
435 CA_FOREACH_END()
436 YAJL_CHECK(yajl_gen_array_close(g));
437 #undef YAJL_CHECK
438 return MAP_OK;
439 }
440 static int SaveWeaponUsage(any_t data, any_t item)
441 {
442 yajl_gen g = data;
443 NWeaponUsage *wu = item;
444 #define YAJL_CHECK(func) \
445 { \
446 yajl_gen_status _status = func; \
447 if (_status != yajl_gen_status_ok) \
448 { \
449 LOG(LM_MAIN, LL_ERROR, \
450 "JSON generator error for high score entry %s: %d\n", \
451 (const char *)wu->Weapon, (int)_status); \
452 return MAP_MISSING; \
453 } \
454 }
455 YAJL_CHECK(yajl_gen_string(
456 g, (const unsigned char *)wu->Weapon, strlen(wu->Weapon)));
457 YAJL_CHECK(yajl_gen_map_open(g));
458 YAJL_CHECK(YAJLAddIntPair(g, "Shots", (int)wu->Shots));
459 YAJL_CHECK(YAJLAddIntPair(g, "Hits", (int)wu->Hits));
460 YAJL_CHECK(yajl_gen_map_close(g));
461 #undef YAJL_CHECK
462 return MAP_OK;
463 }
464 static void SaveHighScores(map_t highScores)
465 {
466 yajl_gen g = yajl_gen_alloc(NULL);
467 if (g == NULL)
468 {
469 LOG(LM_MAIN, LL_ERROR,
470 "Unable to alloc JSON generator for saving high scores\n");
471 goto bail;
472 }
473
474 #define YAJL_CHECK(func) \
475 if (func != yajl_gen_status_ok) \
476 { \
477 LOG(LM_MAIN, LL_ERROR, "JSON generator error for high scores\n"); \
478 goto bail; \
479 }
480
481 YAJL_CHECK(yajl_gen_map_open(g));
482 SaveHighScoresData sData = {g, highScores};
483 if (hashmap_iterate_keys_sorted(
484 highScores, SaveHighScoreEntries, (any_t *)&sData) != MAP_OK)
485 {
486 LOG(LM_MAIN, LL_ERROR, "Failed to generate high score entries\n");
487 goto bail;
488 }
489 YAJL_CHECK(yajl_gen_map_close(g));
490
491 const char *path = GetConfigFilePath(SCORES_FILE);
492 if (!YAJLTrySaveJSONFile(g, path))
493 {
494 goto bail;
495 }
496
497 bail:
498 if (g)
499 {
500 yajl_gen_clear(g);
501 yajl_gen_free(g);
502 }
503 }
504
505 static map_t LoadHighScores(void)
506 {
507 map_t highScores = hashmap_new();
508 const char *path = GetConfigFilePath(SCORES_FILE);
509 yajl_val node = YAJLReadFile(path);
510 if (node == NULL)
511 {
512 LOG(LM_MAIN, LL_INFO, "Error reading high scores '%s'", path);
513 goto bail;
514 }
515 if (!YAJL_IS_OBJECT(node))
516 {
517 LOG(LM_MAIN, LL_ERROR, "Unexpected format for high scores\n");
518 goto bail;
519 }
520 for (int i = 0; i < (int)node->u.object.len; i++)
521 {
522 yajl_array entriesNode = YAJL_GET_ARRAY(node->u.object.values[i]);
523 const char *entriesPath = node->u.object.keys[i];
524 if (!entriesNode)
525 {
526 LOG(LM_MAIN, LL_ERROR, "Unexpected format for high scores %s\n",
527 entriesPath);
528 continue;
529 }
530 CArray *entries;
531 CMALLOC(entries, sizeof *entries);
532 CArrayInit(entries, sizeof(HighScoreEntry));
533 for (int j = 0; j < (int)entriesNode->len; j++)
534 {
535 // Decode base64-encoded entries
536 const char *entryEncoded = YAJL_GET_STRING(entriesNode->values[j]);
537 char *decodeOut;
538 const size_t decodeLen = strlen(entryEncoded);
539 CMALLOC(decodeOut, BASE64_DECODE_OUT_SIZE(decodeLen));
540 base64_decode(entryEncoded, (unsigned int)decodeLen, (unsigned char *)decodeOut);
541 char errbuf[1024];
542 yajl_val entryNode =
543 yajl_tree_parse(decodeOut, errbuf, sizeof errbuf);
544 if (entryNode == NULL)
545 {
546 LOG(LM_MAIN, LL_ERROR,
547 "Unexpected format for high score entry %s %d\n", path, j);
548 continue;
549 }
550 CFREE(decodeOut);
551
552 HighScoreEntry entry;
553 memset(&entry, 0, sizeof entry);
554 entry.WeaponUsages = WeaponUsagesNew();
555 YAJLStr(&entry.Name, entryNode, "Name");
556 int value;
557 YAJLInt(&value, entryNode, "Time");
558 entry.Time = (time_t)value;
559
560 const char *charPath[] = {"Character", NULL};
561 yajl_val charNode =
562 yajl_tree_get(entryNode, charPath, yajl_t_object);
563 if (!charNode)
564 {
565 LOG(LM_MAIN, LL_ERROR,
566 "Unexpected format for high score entry %s %d\n", path, j);
567 continue;
568 }
569 char *tmp = YAJLGetStr(charNode, "Class");
570 entry.Character.Class = StrCharacterClass(tmp);
571 CFREE(tmp);
572 YAJLStr(
573 &entry.Character.HeadParts[HEAD_PART_HAIR], charNode,
574 "HairType");
575 YAJLStr(
576 &entry.Character.HeadParts[HEAD_PART_FACEHAIR], charNode,
577 "FacehairType");
578 YAJLStr(
579 &entry.Character.HeadParts[HEAD_PART_HAT], charNode,
580 "HatType");
581 YAJLStr(
582 &entry.Character.HeadParts[HEAD_PART_GLASSES], charNode,
583 "GlassesType");
584 YAJLLoadColor(&entry.Character.Colors.Skin, charNode, "Skin");
585 YAJLLoadColor(&entry.Character.Colors.Arms, charNode, "Arms");
586 YAJLLoadColor(&entry.Character.Colors.Body, charNode, "Body");
587 YAJLLoadColor(&entry.Character.Colors.Legs, charNode, "Legs");
588 YAJLLoadColor(&entry.Character.Colors.Hair, charNode, "Hair");
589 YAJLLoadColor(&entry.Character.Colors.Feet, charNode, "Feet");
590 YAJLLoadColor(
591 &entry.Character.Colors.Facehair, charNode, "Facehair");
592 YAJLLoadColor(&entry.Character.Colors.Hat, charNode, "Hat");
593 YAJLLoadColor(
594 &entry.Character.Colors.Glasses, charNode, "Glasses");
595
596 // TODO: base64 decode
597 const char *statsPath[] = {"Stats", NULL};
598 yajl_val statsNode =
599 yajl_tree_get(entryNode, statsPath, yajl_t_object);
600 if (!statsNode)
601 {
602 LOG(LM_MAIN, LL_ERROR,
603 "Unexpected format for high score entry %s %d\n", path, j);
604 continue;
605 }
606 YAJLInt((int *)&entry.Stats.Score, statsNode, "Score");
607 YAJLInt((int *)&entry.Stats.Kills, statsNode, "Kills");
608 YAJLInt((int *)&entry.Stats.Suicides, statsNode, "Suicides");
609 YAJLInt((int *)&entry.Stats.Friendlies, statsNode, "Friendlies");
610 YAJLInt((int *)&entry.Stats.TimeTicks, statsNode, "TimeTicks");
611
612 const char *wuPath[] = {"WeaponUsages", NULL};
613 yajl_val wuNode = yajl_tree_get(entryNode, wuPath, yajl_t_object);
614 if (!wuNode || !YAJL_IS_OBJECT(wuNode))
615 {
616 LOG(LM_MAIN, LL_ERROR,
617 "Unexpected format for high score entry %s %d\n", path, j);
618 continue;
619 }
620 for (int k = 0; k < (int)wuNode->u.object.len; k++)
621 {
622 const char *weaponName = wuNode->u.object.keys[k];
623 yajl_val usageNode = wuNode->u.object.values[k];
624 NWeaponUsage *w = NULL;
625 CMALLOC(w, sizeof *w);
626 strcpy(w->Weapon, weaponName);
627 YAJLInt((int *)&w->Shots, usageNode, "Shots");
628 YAJLInt((int *)&w->Hits, usageNode, "Hits");
629 if (hashmap_put(entry.WeaponUsages, weaponName, w) != MAP_OK)
630 {
631 LOG(LM_MAIN, LL_ERROR, "failed to load high scores (%s)",
632 path);
633 continue;
634 }
635 }
636 CArrayPushBack(entries, &entry);
637 }
638 if (hashmap_put(highScores, entriesPath, (any_t *)entries) != MAP_OK)
639 {
640 LOG(LM_MAIN, LL_ERROR, "failed to load high scores (%s)", path);
641 continue;
642 }
643 }
644
645 bail:
646 yajl_tree_free(node);
647 return highScores;
648 }
649
650 HighScoresData HighScoresDataLoad(const Campaign *co, GraphicsDevice *g)
651 {
652 map_t highScores = LoadHighScores();
653 HighScoresData hData;
654 memset(&hData, 0, sizeof hData);
655 hData.g = g;
656 CArray *scores = NULL;
657 if (hashmap_get(highScores, co->Entry.Path, (any_t *)&scores) !=
658 MAP_MISSING)
659 {
660 // copy scores
661 CArrayInit(&hData.scores, sizeof(HighScoreEntry));
662 CArrayCopy(&hData.scores, scores);
663 CA_FOREACH(HighScoreEntry, entry, hData.scores)
664 const HighScoreEntry *src = CArrayGet(scores, _ca_index);
665 CSTRDUP(entry->Name, src->Name);
666 entry->WeaponUsages = hashmap_copy(src->WeaponUsages, NULL);
667 CA_FOREACH_END()
668 }
669 return hData;
670 }
671
672 void HighScoresDataTerminate(HighScoresData *hData)
673 {
674 CA_FOREACH(HighScoreEntry, entry, hData->scores)
675 CFREE(entry->Name);
676 WeaponUsagesTerminate(entry->WeaponUsages);
677 CA_FOREACH_END()
678 CArrayTerminate(&hData->scores);
679 }
680
681 void HighScoresDraw(const HighScoresData *hData)
682 {
683 BlitClearBuf(&gGraphicsDevice);
684 DisplayPage(&hData->scores);
685 BlitUpdateFromBuf(&gGraphicsDevice, gGraphicsDevice.screen);
686 }