forked from MiSTer-devel/Main_MiSTer
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathachievements.cpp
More file actions
2144 lines (1873 loc) · 70.7 KB
/
Copy pathachievements.cpp
File metadata and controls
2144 lines (1873 loc) · 70.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// achievements.cpp — RetroAchievements integration for MiSTer FPGA
//
// Phase 4: Full pipeline with OSD notifications — achievement popups,
// login/game status, progress indicators, status info panel.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <time.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>
#include <execinfo.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netdb.h>
#include "achievements.h"
#include "achievements_console.h"
#include "ra_ramread.h"
#include "ra_http.h"
#include "user_io.h"
#include "cfg.h"
#include "file_io.h"
#include "menu.h"
#include "osd.h"
#include "hardware.h"
#include "lib/md5/md5.h"
#include "ra_cdreader_chd.h"
#ifdef HAS_RCHEEVOS
#include "rc_client.h"
#include "rc_consoles.h"
#include "rc_api_request.h"
#include "rc_hash.h"
#endif
// ---------------------------------------------------------------------------
// Debug logging
// ---------------------------------------------------------------------------
static FILE *g_logfile = NULL;
static int g_ra_debug = 0; // forward decl — defined/loaded in ra_load_credentials
#define RA_LOG(fmt, ...) ra_log_impl("RA: " fmt "\n", ##__VA_ARGS__)
void ra_log_write(const char *fmt, ...)
{
if (!g_ra_debug) return;
va_list args;
va_start(args, fmt);
printf("\033[1;35m");
vprintf(fmt, args);
printf("\033[0m");
va_end(args);
if (g_logfile) {
va_start(args, fmt);
vfprintf(g_logfile, fmt, args);
va_end(args);
fflush(g_logfile);
}
}
static void ra_log_impl(const char *fmt, ...)
{
if (!g_ra_debug) return;
va_list args;
// stdout with color
va_start(args, fmt);
printf("\033[1;35m");
vprintf(fmt, args);
printf("\033[0m");
va_end(args);
// log file without color
if (g_logfile) {
va_start(args, fmt);
vfprintf(g_logfile, fmt, args);
va_end(args);
fflush(g_logfile);
}
}
static void ra_log_open(void)
{
if (!g_logfile) {
g_logfile = fopen("/tmp/ra_debug.log", "w");
if (g_logfile) {
time_t now = time(NULL);
fprintf(g_logfile, "=== RetroAchievements Debug Log ===\n");
fprintf(g_logfile, "Started: %s\n", ctime(&now));
fflush(g_logfile);
}
}
}
static void ra_log_close(void)
{
if (g_logfile) {
time_t now = time(NULL);
fprintf(g_logfile, "Closed: %s\n", ctime(&now));
fclose(g_logfile);
g_logfile = NULL;
}
}
// ---------------------------------------------------------------------------
// Crash signal handler — writes backtrace to log before dying
// ---------------------------------------------------------------------------
static void ra_crash_handler(int sig)
{
const char *name = (sig == SIGSEGV) ? "SIGSEGV" :
(sig == SIGBUS) ? "SIGBUS" :
(sig == SIGABRT) ? "SIGABRT" :
(sig == SIGFPE) ? "SIGFPE" : "UNKNOWN";
// Write directly to log file (async-signal-safe is best-effort here)
if (g_logfile) {
fprintf(g_logfile, "\n!!! CRASH: signal %s (%d) !!!\n", name, sig);
void *bt[32];
int n = backtrace(bt, 32);
backtrace_symbols_fd(bt, n, fileno(g_logfile));
fflush(g_logfile);
}
// Also print to stderr
fprintf(stderr, "\n!!! RA CRASH: signal %s (%d) !!!\n", name, sig);
void *bt[32];
int n = backtrace(bt, 32);
backtrace_symbols_fd(bt, n, STDERR_FILENO);
// Re-raise to get default behavior (core dump)
signal(sig, SIG_DFL);
raise(sig);
}
// ---------------------------------------------------------------------------
// State
// ---------------------------------------------------------------------------
static void *g_ra_map = NULL; // DDRAM mirror mmap pointer
static uint32_t g_last_frame = 0; // Last processed frame counter
static uint32_t g_first_frame = 0; // First valid frame seen (for uptime tracking)
static int g_game_loaded = 0; // Game is loaded and identified
static int g_mirror_validated = 0; // DDRAM mirror has been validated at least once
static char g_rom_md5[33] = {}; // MD5 hex string of current ROM
static char g_rom_path[1024] = {}; // Path to current ROM
// Active console handler (set in achievements_init, dispatches all per-console logic)
static const console_handler_t *g_active_handler = NULL;
#ifdef HAS_RCHEEVOS
static rc_client_t *g_client = NULL;
#endif
// Credentials
static char g_ra_user[128] = {};
static char g_ra_password[128] = {};
static int g_has_credentials = 0;
static int g_logged_in = 0;
static int g_login_pending = 0;
static int g_game_load_pending = 0;
static int g_login_deferred = 0; // login deferred until FPGA mirror validated
static int g_game_load_deferred = 0; // game load deferred until
static int g_mirror_confirming = 0; // magic seen, waiting for frame counter to advance
static uint32_t g_mirror_initial_frame = 0; // frame when magic was first seen (stale detection) FPGA mirror validated
// Debug counters
static uint32_t g_frames_processed = 0;
static uint32_t g_frames_skipped = 0; // frames where busy flag was set
static time_t g_load_time = 0;
void ra_frame_processed(uint32_t frame)
{
g_last_frame = frame;
g_frames_processed++;
}
// Config file path
#define RA_CFG_PATH "/media/fat/retroachievements.cfg"
#define RA_SFX_PATH "/media/fat/achievement.wav"
// Popup display settings (from retroachievements.cfg)
static int g_show_challenge_show_popup = 1; // 1 = show popup on challenge SHOW event
static int g_show_challenge_hide_popup = 1; // 1 = show popup on challenge HIDE event
static int g_show_progress_popups = 1; // 1 = show progress indicator popups
static int g_show_progress_name = 1; // 1 = include achievement name in progress popup
static int g_leaderboards_enabled = 1; // [deprecated] fallback only when both new leaderboard popup flags are absent
static int g_show_leaderboards_updates = 1; // 1 = show STARTED/FAILED/TRACKER SHOW/TRACKER UPDATE popups
static int g_show_leaderboards_submission = 1; // 1 = show SUBMITTED/SCOREBOARD popups
static int g_hardcore = 0; // 1 = hardcore mode (disables cheats & save states)
static int g_force_hardcore = 0; // 1 = force hardcore mode even if core doesn't support it
static int g_stall_recovery = 0; // 1 = enable OptionC stall recovery (disabled by default)
static int g_rtquery_enabled = 1; // 1 = enable realtime queries for AddAddress resolution
static int g_gba_reset_ram = 1; // 1 = clear IWRAM+EWRAM on game load (retroachievements.cfg: gba_reset_ram)
static int g_recollect_interval = 600; // frames between address re-collections (PSX default 600, SNES 18000)
static int g_smart_cache = -1; // -1 = default per console, 1 = smart cache: rtquery on cache miss, no periodic recollect
static int g_n64_snapshot = 0; // 1 = snapshot RDRAM at VBlank for consistent reads
static int g_multiline_desc = 0; // 1 = wrap long text to extra lines instead of truncating with "..."
static char g_ua_clause[64] = ""; // rcheevos user-agent clause (e.g. "rcheevos/11.6")
static char g_fpga_core_version[8] = "0.1"; // version reported by FPGA in DDRAM header
// ---------------------------------------------------------------------------
// Per-achievement event state (rate-limiting CHALLENGE, dedup PROGRESS)
// ---------------------------------------------------------------------------
#define RA_ACH_STATE_MAX 128
struct ra_ach_state_t {
uint32_t id;
time_t challenge_last_popup; // monotonic: last time SHOW popup was shown
char progress_last[32]; // last progress string displayed
};
static ra_ach_state_t g_ach_state[RA_ACH_STATE_MAX];
static int g_ach_state_count = 0;
#define CHALLENGE_POPUP_COOLDOWN_SEC 10 // suppress CHALLENGE SHOW popup if one was shown < 10s ago
#define PROGRESS_SAME_VAL_COOLDOWN_SEC 5 // suppress PROGRESS popup if same value shown < 5s ago
static ra_ach_state_t *ra_ach_state_get(uint32_t id)
{
for (int i = 0; i < g_ach_state_count; i++)
if (g_ach_state[i].id == id) return &g_ach_state[i];
if (g_ach_state_count < RA_ACH_STATE_MAX) {
ra_ach_state_t *s = &g_ach_state[g_ach_state_count++];
s->id = id;
s->challenge_last_popup = 0;
s->progress_last[0] = '\0';
return s;
}
return NULL;
}
// Returns 1 if CHALLENGE SHOW popup should be suppressed (fired too recently)
static int ra_challenge_popup_suppressed(uint32_t id)
{
ra_ach_state_t *s = ra_ach_state_get(id);
if (!s) return 0;
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
time_t elapsed = now.tv_sec - s->challenge_last_popup;
if (elapsed < CHALLENGE_POPUP_COOLDOWN_SEC) return 1;
s->challenge_last_popup = now.tv_sec;
return 0;
}
// Returns 1 if PROGRESS popup should be suppressed (same value shown recently)
static int ra_progress_popup_suppressed(uint32_t id, const char *progress)
{
ra_ach_state_t *s = ra_ach_state_get(id);
if (!s) return 0;
if (strcmp(s->progress_last, progress) == 0) {
// Same value as last time — suppress unless it's been a while
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
// (future: could add time-based override here)
return 1;
}
// New value — update and allow
snprintf(s->progress_last, sizeof(s->progress_last), "%s", progress);
return 0;
}
// ---------------------------------------------------------------------------
// Achievement Sound
// ---------------------------------------------------------------------------
static void *ra_play_thread(void *arg)
{
(void)arg;
// Only play if the file exists — silent no-op otherwise
if (access(RA_SFX_PATH, R_OK) == 0)
system("aplay -q " RA_SFX_PATH " 2>/dev/null");
return NULL;
}
static void ra_play_achievement_sound(void)
{
pthread_t th;
if (pthread_create(&th, NULL, ra_play_thread, NULL) == 0)
pthread_detach(th);
}
// ---------------------------------------------------------------------------
// OSD Notification — two-tier system
//
// Tier 1 URGENT (queued): achievement unlocked, game completed.
// → Multiple unlocks accumulate; each is shown in order, never interrupted.
//
// Tier 2 INSTANT (single slot, last-wins): progress, challenge, etc.
// → Shows immediately, overwriting any currently displayed instant.
// → Silently discarded if a Tier 1 notification is on screen.
// ---------------------------------------------------------------------------
#define NOTIF_QUEUE_CAP 8
#define NOTIF_TEXT_MAX 200
struct ra_notif {
char text[NOTIF_TEXT_MAX];
int duration_ms;
int play_sound;
};
// Tier 1 — urgent queue
static ra_notif s_urgent_queue[NOTIF_QUEUE_CAP];
static int s_urgent_head = 0;
static int s_urgent_tail = 0;
static int s_urgent_showing = 0;
static unsigned long s_urgent_timer = 0;
// Tier 2 — instant slot
static char s_instant_text[NOTIF_TEXT_MAX] = {0};
static int s_instant_duration_ms = 3000;
static int s_instant_pending = 0;
static int s_instant_showing = 0;
static unsigned long s_instant_timer = 0;
// Add to urgent queue (never dropped by instant notifications)
static void ra_notify_urgent(const char *text, int duration_ms = 4000, int play_sound = 0)
{
int count = s_urgent_head - s_urgent_tail;
if (count >= NOTIF_QUEUE_CAP) {
s_urgent_tail++;
RA_LOG("OSD: Urgent queue full, dropping oldest");
}
ra_notif *n = &s_urgent_queue[s_urgent_head % NOTIF_QUEUE_CAP];
snprintf(n->text, NOTIF_TEXT_MAX, "%s", text);
n->duration_ms = duration_ms;
n->play_sound = play_sound;
s_urgent_head++;
}
// Set instant slot — last event wins; discarded in poll if urgent is showing
static void ra_notify_instant(const char *text, int duration_ms = 3000)
{
snprintf(s_instant_text, NOTIF_TEXT_MAX, "%s", text);
s_instant_duration_ms = duration_ms;
s_instant_pending = 1;
}
// Aliases kept for call-site readability
static void ra_notify(const char *text, int duration_ms = 3000)
{
ra_notify_instant(text, duration_ms);
}
static void ra_notify_progress(const char *text)
{
ra_notify_instant(text, 2500);
}
// Drive OSD display — called every achievements_poll() tick
static void ra_osd_poll(void)
{
// Expire timers
if (s_urgent_showing && CheckTimer(s_urgent_timer))
s_urgent_showing = 0;
if (s_instant_showing && CheckTimer(s_instant_timer))
s_instant_showing = 0;
if (menu_present()) return;
// Tier 1: show next urgent as soon as previous one expires
if (!s_urgent_showing && s_urgent_head != s_urgent_tail) {
ra_notif *n = &s_urgent_queue[s_urgent_tail % NOTIF_QUEUE_CAP];
s_urgent_tail++;
Info(n->text, n->duration_ms + 500, 0, 0, 1);
if (n->play_sound) ra_play_achievement_sound();
s_urgent_timer = GetTimer(n->duration_ms);
s_urgent_showing = 1;
// Urgent takes over the display — discard any pending instant
s_instant_pending = 0;
s_instant_showing = 0;
RA_LOG("OSD: Showing urgent notification (%dms)", n->duration_ms);
return;
}
// Tier 2: instant slot — show immediately; discard if urgent is on screen
if (s_instant_pending) {
s_instant_pending = 0;
if (!s_urgent_showing) {
Info(s_instant_text, s_instant_duration_ms + 500, 0, 0, 1);
s_instant_timer = GetTimer(s_instant_duration_ms);
s_instant_showing = 1;
RA_LOG("OSD: Showing instant notification (%dms)", s_instant_duration_ms);
} else {
RA_LOG("OSD: Instant notification discarded (urgent showing)");
}
}
}
// ---------------------------------------------------------------------------
// ROM MD5 calculation
// ---------------------------------------------------------------------------
static int ra_get_console_id(void); // forward declaration
static int ra_core_supported(void); // forward declaration
// Compute the RetroAchievements MD5 for a ROM file.
// For NES: skips the 16-byte iNES header (and optional 512-byte trainer)
// so the hash matches what RetroAchievements expects.
static int ra_calculate_rom_md5(const char *path, char *md5_hex_out)
{
fileTYPE f = {};
if (!FileOpen(&f, path, 1)) {
RA_LOG("ERROR: Cannot open ROM file: %s", path);
return 0;
}
uint32_t file_size = f.size;
RA_LOG("Hashing ROM: %s (%u bytes)", path, file_size);
// Read entire file
uint8_t *rom_data = (uint8_t *)malloc(file_size);
if (!rom_data) {
RA_LOG("ERROR: malloc failed for ROM buffer (%u bytes)", file_size);
FileClose(&f);
return 0;
}
int rd = FileReadAdv(&f, rom_data, file_size);
FileClose(&f);
if (rd <= 0 || (uint32_t)rd != file_size) {
RA_LOG("ERROR: Failed to read ROM (got %d of %u bytes)", rd, file_size);
free(rom_data);
return 0;
}
const uint8_t *hash_data = rom_data;
uint32_t hash_size = file_size;
// NES: skip iNES header ("NES\x1a") + optional 512-byte trainer
if (file_size > 16 &&
rom_data[0] == 0x4E && rom_data[1] == 0x45 && // 'N' 'E'
rom_data[2] == 0x53 && rom_data[3] == 0x1A) { // 'S' 0x1a
uint32_t skip = 16;
if (rom_data[6] & 0x04) skip += 512; // trainer present
RA_LOG("iNES header detected, skipping %u bytes (trainer=%d)",
skip, (rom_data[6] & 0x04) ? 1 : 0);
hash_data = rom_data + skip;
hash_size = file_size - skip;
}
// FDS: skip fwNES FDS header ("FDS\x1a")
if (file_size > 16 &&
rom_data[0] == 0x46 && rom_data[1] == 0x44 && // 'F' 'D'
rom_data[2] == 0x53 && rom_data[3] == 0x1A) { // 'S' 0x1a
RA_LOG("FDS header detected, skipping 16 bytes");
hash_data = rom_data + 16;
hash_size = file_size - 16;
}
// SNES: skip optional 512-byte SMC/SWC copier header
if ((file_size % 1024) == 512 && file_size > 512) {
RA_LOG("SNES SMC header detected (file_size %% 1024 == 512), skipping 512 bytes");
hash_data = rom_data + 512;
hash_size = file_size - 512;
}
struct MD5Context ctx;
MD5Init(&ctx);
MD5Update(&ctx, hash_data, hash_size);
unsigned char digest[16];
MD5Final(digest, &ctx);
for (int i = 0; i < 16; i++)
sprintf(md5_hex_out + i * 2, "%02x", digest[i]);
md5_hex_out[32] = '\0';
free(rom_data);
RA_LOG("ROM MD5: %s", md5_hex_out);
return 1;
}
// ---------------------------------------------------------------------------
// Credentials loading
// ---------------------------------------------------------------------------
// Config file format (/media/fat/retroachievements.cfg):
// username=YourRAUsername
// password=YourRAPassword
// # Lines starting with # are comments
static int ra_load_credentials(void)
{
g_ra_user[0] = '\0';
g_ra_password[0] = '\0';
int legacy_leaderboards_defined = 0;
int show_leaderboards_updates_defined = 0;
int show_leaderboards_submission_defined = 0;
FILE *f = fopen(RA_CFG_PATH, "r");
if (!f) {
RA_LOG("Credentials file not found: %s", RA_CFG_PATH);
RA_LOG("To enable RetroAchievements, create the file with:");
RA_LOG(" username=YourRAUsername");
RA_LOG(" password=YourRAPassword");
return 0;
}
char line[512];
while (fgets(line, sizeof(line), f)) {
// Strip newline
char *nl = strchr(line, '\n');
if (nl) *nl = '\0';
nl = strchr(line, '\r');
if (nl) *nl = '\0';
// Skip comments and empty lines
if (line[0] == '#' || line[0] == '\0') continue;
char *eq = strchr(line, '=');
if (!eq) continue;
*eq = '\0';
const char *key = line;
const char *val = eq + 1;
// Trim leading spaces from value
while (*val == ' ' || *val == '\t') val++;
if (!strcasecmp(key, "username")) {
snprintf(g_ra_user, sizeof(g_ra_user), "%s", val);
} else if (!strcasecmp(key, "password")) {
snprintf(g_ra_password, sizeof(g_ra_password), "%s", val);
} else if (!strcasecmp(key, "show_challenge_show_popup")) {
g_show_challenge_show_popup = atoi(val);
} else if (!strcasecmp(key, "show_challenge_hide_popup")) {
g_show_challenge_hide_popup = atoi(val);
} else if (!strcasecmp(key, "show_progress_popups")) {
g_show_progress_popups = atoi(val);
} else if (!strcasecmp(key, "show_progress_name")) {
g_show_progress_name = atoi(val);
} else if (!strcasecmp(key, "show_leaderboards_updates") ||
!strcasecmp(key, "show-leaderboards-updates")) {
g_show_leaderboards_updates = atoi(val);
show_leaderboards_updates_defined = 1;
} else if (!strcasecmp(key, "show_leaderboards_submission") ||
!strcasecmp(key, "show-leaderboards-submission")) {
g_show_leaderboards_submission = atoi(val);
show_leaderboards_submission_defined = 1;
} else if (!strcasecmp(key, "leaderboards-enabled") ||
!strcasecmp(key, "leaderboards_enabled")) {
g_leaderboards_enabled = atoi(val);
legacy_leaderboards_defined = 1;
} else if (!strcasecmp(key, "hardcore")) {
g_hardcore = atoi(val);
} else if (!strcasecmp(key, "force_hardcore")) {
g_force_hardcore = atoi(val);
} else if (!strcasecmp(key, "stall_recovery")) {
g_stall_recovery = atoi(val);
} else if (!strcasecmp(key, "rtquery_enabled") ||
!strcasecmp(key, "rtquery")) {
g_rtquery_enabled = atoi(val);
} else if (!strcasecmp(key, "recollect_interval")) {
g_recollect_interval = atoi(val);
if (g_recollect_interval < 60) g_recollect_interval = 60; // minimum 1 second
} else if (!strcasecmp(key, "smart_cache")) {
g_smart_cache = atoi(val);
} else if (!strcasecmp(key, "debug")) {
g_ra_debug = atoi(val);
} else if (!strcasecmp(key, "n64_snapshot")) {
g_n64_snapshot = atoi(val);
} else if (!strcasecmp(key, "gba_reset_ram")) {
g_gba_reset_ram = atoi(val);
} else if (!strcasecmp(key, "multiline_desc")) {
g_multiline_desc = atoi(val);
}
}
fclose(f);
/* Backward compatibility: transfer deprecated value only when both new keys are absent. */
if (!show_leaderboards_updates_defined && !show_leaderboards_submission_defined && legacy_leaderboards_defined) {
g_show_leaderboards_updates = g_leaderboards_enabled;
g_show_leaderboards_submission = g_leaderboards_enabled;
}
if (!g_ra_user[0] || !g_ra_password[0]) {
RA_LOG("Credentials incomplete (need both username and password)");
return 0;
}
RA_LOG("Credentials loaded: user=%s password=***(%zu chars)", g_ra_user, strlen(g_ra_password));
RA_LOG("Config: show_challenge_show=%d show_challenge_hide=%d show_progress=%d show_progress_name=%d show_leaderboards_updates=%d show_leaderboards_submission=%d leaderboards_enabled(deprecated)=%d hardcore=%d force_hardcore=%d stall_recovery=%d rtquery=%d recollect=%d smart_cache=%d n64_snapshot=%d gba_reset_ram=%d multiline_desc=%d debug=%d",
g_show_challenge_show_popup, g_show_challenge_hide_popup,
g_show_progress_popups, g_show_progress_name,
g_show_leaderboards_updates, g_show_leaderboards_submission, g_leaderboards_enabled,
g_hardcore, g_force_hardcore, g_stall_recovery, g_rtquery_enabled, g_recollect_interval, g_smart_cache, g_n64_snapshot, g_gba_reset_ram, g_multiline_desc, g_ra_debug);
return 1;
}
// ---------------------------------------------------------------------------
// Text formatting helper: truncate with "..." or wrap to multiple lines
// ---------------------------------------------------------------------------
static void ra_format_text(const char *text, char *out, size_t out_size, int trunc_width, int wrap_width, int max_lines)
{
if (!text || !out || out_size == 0) return;
size_t len = strlen(text);
if (!g_multiline_desc) {
if (len <= (size_t)trunc_width) {
snprintf(out, out_size, "%s", text);
return;
}
size_t copy = (size_t)trunc_width < out_size - 1 ? (size_t)trunc_width : out_size - 1;
memcpy(out, text, copy);
out[copy] = '\0';
if (copy + 3 < out_size) strcat(out, "...");
} else {
if (len <= (size_t)wrap_width) {
snprintf(out, out_size, "%s", text);
return;
}
size_t pos = 0, written = 0;
for (int line = 0; line < max_lines && pos < len && written + 1 < out_size; line++) {
if (line > 0) { out[written++] = '\n'; out[written] = '\0'; }
size_t take = len - pos;
if (take > (size_t)wrap_width) take = (size_t)wrap_width;
size_t avail = out_size - written - 1;
if (take > avail) take = avail;
memcpy(out + written, text + pos, take);
written += take;
out[written] = '\0';
pos += take;
}
if (pos < len && written + 3 < out_size) strcat(out, "...");
}
}
// ---------------------------------------------------------------------------
// rcheevos callbacks (compiled only if library is available)
// ---------------------------------------------------------------------------
#ifdef HAS_RCHEEVOS
static uint32_t ra_read_memory(uint32_t address, uint8_t *buffer,
uint32_t num_bytes, rc_client_t *client)
{
(void)client;
if (!g_ra_map || !ra_ramread_active(g_ra_map)) {
memset(buffer, 0, num_bytes);
return ra_core_supported() ? num_bytes : 0;
}
// Dispatch to active console handler
if (g_active_handler && g_active_handler->read_memory) {
uint32_t r = g_active_handler->read_memory(g_ra_map, address, buffer, num_bytes);
if (r > 0) return r;
}
// Fallback: VBlank-gated region reads for NES and SNES
int console = ra_get_console_id();
if (console == 7) // NES
return ra_ramread_nes_read(g_ra_map, address, buffer, num_bytes);
if (console == 3) // SNES VBlank-gated (handler returned 0 = not optionc)
return ra_ramread_snes_read(g_ra_map, address, buffer, num_bytes);
memset(buffer, 0, num_bytes);
return num_bytes;
}
static void ra_server_call(const rc_api_request_t *request,
rc_client_server_callback_t callback, void *callback_data,
rc_client_t *client)
{
(void)client;
// Log the request (mask token for security)
if (request->post_data) {
const char *token_pos = strstr(request->post_data, "&t=");
if (token_pos) {
int prefix_len = (int)(token_pos - request->post_data);
RA_LOG("HTTP: POST %s [%.*s&t=***]", request->url, prefix_len, request->post_data);
} else {
RA_LOG("HTTP: POST %s [%.80s%s]", request->url,
request->post_data, strlen(request->post_data) > 80 ? "..." : "");
}
} else {
RA_LOG("HTTP: GET %s", request->url);
}
// Bridge struct: passed through ra_http as opaque userdata
struct ra_http_bridge {
rc_client_server_callback_t rc_callback;
void *rc_callback_data;
};
ra_http_bridge *bridge = (ra_http_bridge *)malloc(sizeof(ra_http_bridge));
if (!bridge) {
RA_LOG("ERROR: malloc failed for HTTP bridge");
rc_api_server_response_t resp;
memset(&resp, 0, sizeof(resp));
resp.http_status_code = RC_API_SERVER_RESPONSE_RETRYABLE_CLIENT_ERROR;
resp.body = "malloc failed";
resp.body_length = strlen(resp.body);
callback(&resp, callback_data);
return;
}
bridge->rc_callback = callback;
bridge->rc_callback_data = callback_data;
// The ra_http callback adapts our ra_http_resp into rc_api_server_response_t
auto http_done = [](const void *resp_ptr, void *userdata) {
struct ra_http_resp_view {
int http_status;
char *body;
size_t body_len;
};
const ra_http_resp_view *hr = (const ra_http_resp_view *)resp_ptr;
ra_http_bridge *br = (ra_http_bridge *)userdata;
rc_api_server_response_t rc_resp;
memset(&rc_resp, 0, sizeof(rc_resp));
rc_resp.http_status_code = hr->http_status;
rc_resp.body = hr->body ? hr->body : "";
rc_resp.body_length = hr->body_len;
// Log response body with token masked
{
char body_preview[220];
snprintf(body_preview, sizeof(body_preview), "%.200s", rc_resp.body);
// Mask "Token":"<value>" in response JSON
char *tp = strstr(body_preview, "\"Token\":\"");
if (tp) {
char *val_start = tp + 9; // skip "Token":" (9 chars)
char *val_end = strchr(val_start, '"');
if (val_end) {
memmove(val_start + 3, val_end, strlen(val_end) + 1);
memcpy(val_start, "***", 3);
}
}
RA_LOG("HTTP response: status=%d body_len=%zu body=%s",
hr->http_status, hr->body_len, body_preview);
}
if (hr->http_status == 0) {
// curl failed entirely — mark as retryable
rc_resp.http_status_code = RC_API_SERVER_RESPONSE_RETRYABLE_CLIENT_ERROR;
}
br->rc_callback(&rc_resp, br->rc_callback_data);
free(br);
};
ra_http_request(request->url, request->post_data, NULL,
http_done, bridge);
}
static void ra_event_handler(const rc_client_event_t *event, rc_client_t *client)
{
(void)client;
RA_LOG("Event: type=%d", event->type);
switch (event->type) {
case RC_CLIENT_EVENT_ACHIEVEMENT_TRIGGERED:
{
if (event->achievement->id == 101000001) {
ra_notify_urgent("HARDCORE mode DISABLED\nCORE still not supported", 3500);
} else {
RA_LOG("*** ACHIEVEMENT TRIGGERED: [%u] %s — %s ***",
event->achievement->id, event->achievement->title,
event->achievement->description);
gba_dump_trigger(event->achievement->id);
char title_buf[96];
char desc_buf[192];
ra_format_text(event->achievement->title, title_buf, sizeof(title_buf), 28, 28, 2);
ra_format_text(event->achievement->description, desc_buf, sizeof(desc_buf), 28, 28, 3);
// In multiline mode, prefix desc with "\-> " so it reads as a sub-line of the title
char desc_display[200];
if (g_multiline_desc)
snprintf(desc_display, sizeof(desc_display), "\\-> %s", desc_buf);
else
snprintf(desc_display, sizeof(desc_display), "%s", desc_buf);
char buf[NOTIF_TEXT_MAX];
snprintf(buf, sizeof(buf),
">> ACHIEVEMENT <<\n\n%s\n%s",
title_buf, desc_display);
ra_notify_urgent(buf, 4000, 1);
}
}
break;
case RC_CLIENT_EVENT_ACHIEVEMENT_CHALLENGE_INDICATOR_SHOW:
{
RA_LOG("CHALLENGE SHOW: [%u] %s",
event->achievement->id, event->achievement->title);
if (g_show_challenge_show_popup &&
!ra_challenge_popup_suppressed(event->achievement->id)) {
char title_buf[96];
ra_format_text(event->achievement->title, title_buf, sizeof(title_buf), 28, 28, 2);
char buf[NOTIF_TEXT_MAX];
snprintf(buf, sizeof(buf), "CHALLENGE ACTIVE\n\n%s", title_buf);
ra_notify(buf, 3000);
}
}
break;
case RC_CLIENT_EVENT_ACHIEVEMENT_CHALLENGE_INDICATOR_HIDE:
{
RA_LOG("CHALLENGE HIDE: [%u] %s",
event->achievement->id, event->achievement->title);
if (g_show_challenge_hide_popup) {
char title_buf[96];
ra_format_text(event->achievement->title, title_buf, sizeof(title_buf), 28, 28, 2);
char buf[NOTIF_TEXT_MAX];
snprintf(buf, sizeof(buf), "CHALLENGE MISSED\n\n%s", title_buf);
ra_notify(buf, 3000);
}
}
break;
case RC_CLIENT_EVENT_ACHIEVEMENT_PROGRESS_INDICATOR_SHOW:
case RC_CLIENT_EVENT_ACHIEVEMENT_PROGRESS_INDICATOR_UPDATE:
{
RA_LOG("PROGRESS: %s — %s", event->achievement->title, event->achievement->measured_progress);
// Dump all cached values on progress events
if (g_ra_map) {
int cnt = ra_snes_addrlist_count();
const uint32_t *addrs = ra_snes_addrlist_addrs();
for (int i = 0; i < cnt; i++) {
uint8_t v = ra_snes_addrlist_read_cached(g_ra_map, addrs[i]);
RA_LOG(" COND[%d] addr=0x%05X val=0x%02X", i, addrs[i], v);
}
}
if (g_show_progress_popups &&
!ra_progress_popup_suppressed(event->achievement->id, event->achievement->measured_progress)) {
char buf[NOTIF_TEXT_MAX];
if (g_show_progress_name) {
char title_buf[96];
ra_format_text(event->achievement->title, title_buf, sizeof(title_buf), 28, 28, 2);
snprintf(buf, sizeof(buf), "%s\nProgress: %s",
title_buf, event->achievement->measured_progress);
} else {
snprintf(buf, sizeof(buf), "Progress: %s",
event->achievement->measured_progress);
}
ra_notify_progress(buf);
}
}
break;
case RC_CLIENT_EVENT_LEADERBOARD_STARTED:
{
if (!g_show_leaderboards_updates || !event->leaderboard)
break;
RA_LOG("LEADERBOARD STARTED: [%u] %s",
event->leaderboard->id, event->leaderboard->title);
const int title_max = 28;
char title_buf[32];
snprintf(title_buf, title_max + 1, "%s", event->leaderboard->title);
if (strlen(event->leaderboard->title) > (size_t)title_max)
strcat(title_buf, "...");
char buf[NOTIF_TEXT_MAX];
snprintf(buf, sizeof(buf), "LEADERBOARD START\n\n%s", title_buf);
ra_notify(buf, 2500);
}
break;
case RC_CLIENT_EVENT_LEADERBOARD_FAILED:
{
if (!g_show_leaderboards_updates || !event->leaderboard)
break;
RA_LOG("LEADERBOARD FAILED: [%u] %s",
event->leaderboard->id, event->leaderboard->title);
const int title_max = 28;
char title_buf[32];
snprintf(title_buf, title_max + 1, "%s", event->leaderboard->title);
if (strlen(event->leaderboard->title) > (size_t)title_max)
strcat(title_buf, "...");
char buf[NOTIF_TEXT_MAX];
snprintf(buf, sizeof(buf), "LEADERBOARD FAILED\n\n%s", title_buf);
ra_notify(buf, 2500);
}
break;
case RC_CLIENT_EVENT_LEADERBOARD_SUBMITTED:
{
if (!g_show_leaderboards_submission || !event->leaderboard)
break;
RA_LOG("LEADERBOARD SUBMITTED: [%u] %s",
event->leaderboard->id, event->leaderboard->title);
const int title_max = 28;
char title_buf[32];
char value_buf[RC_CLIENT_LEADERBOARD_DISPLAY_SIZE] = "-";
snprintf(title_buf, title_max + 1, "%s", event->leaderboard->title);
if (strlen(event->leaderboard->title) > (size_t)title_max)
strcat(title_buf, "...");
if (event->leaderboard->tracker_value && event->leaderboard->tracker_value[0])
snprintf(value_buf, sizeof(value_buf), "%s", event->leaderboard->tracker_value);
char buf[NOTIF_TEXT_MAX];
snprintf(buf, sizeof(buf), "LEADERBOARD SUBMITTED\n\n%s\nScore: %s",
title_buf, value_buf);
ra_notify_urgent(buf, 3500);
}
break;
case RC_CLIENT_EVENT_LEADERBOARD_TRACKER_SHOW:
case RC_CLIENT_EVENT_LEADERBOARD_TRACKER_UPDATE:
{
if (!g_show_leaderboards_updates || !event->leaderboard_tracker)
break;
RA_LOG("LEADERBOARD TRACKER: id=%u value=%s",
event->leaderboard_tracker->id,
event->leaderboard_tracker->display);
char buf[NOTIF_TEXT_MAX];
snprintf(buf, sizeof(buf), "LB #%u\n%s",
event->leaderboard_tracker->id,
event->leaderboard_tracker->display);
ra_notify_progress(buf);
}
break;
case RC_CLIENT_EVENT_LEADERBOARD_TRACKER_HIDE:
{
if (!g_show_leaderboards_updates || !event->leaderboard_tracker)
break;
RA_LOG("LEADERBOARD TRACKER HIDE: id=%u",
event->leaderboard_tracker->id);
}
break;
case RC_CLIENT_EVENT_LEADERBOARD_SCOREBOARD:
{
if (!g_show_leaderboards_submission || !event->leaderboard_scoreboard)
break;
RA_LOG("LEADERBOARD SCOREBOARD: id=%u submitted=%s best=%s rank=%u entries=%u",
event->leaderboard_scoreboard->leaderboard_id,
event->leaderboard_scoreboard->submitted_score,
event->leaderboard_scoreboard->best_score,
event->leaderboard_scoreboard->new_rank,
event->leaderboard_scoreboard->num_entries);
char buf[NOTIF_TEXT_MAX];
snprintf(buf, sizeof(buf),
"LEADERBOARD RESULT\n\nRank: #%u/%u\nSubmitted: %s\nBest: %s",
event->leaderboard_scoreboard->new_rank,
event->leaderboard_scoreboard->num_entries,
event->leaderboard_scoreboard->submitted_score,
event->leaderboard_scoreboard->best_score);
ra_notify_urgent(buf, 4000);
}
break;
case RC_CLIENT_EVENT_GAME_COMPLETED:
RA_LOG("*** GAME COMPLETED! ***");
ra_notify_urgent("** GAME COMPLETED! **\n\nCongratulations!", 5000);
ra_play_achievement_sound();
break;
case RC_CLIENT_EVENT_SERVER_ERROR:
{
RA_LOG("SERVER ERROR: %s", event->server_error->error_message);
char buf[NOTIF_TEXT_MAX];
snprintf(buf, sizeof(buf),
"RA Server Error\n\n%.60s",
event->server_error->error_message);
ra_notify(buf, 3000);
}
break;
default:
RA_LOG("EVENT: type=%d", event->type);
break;
}
}
static void ra_log_callback(const char *message, const rc_client_t *client)
{
(void)client;
RA_LOG("rcheevos: %s", message);
}
// Forward declaration (used in ra_login_callback)
static void ra_load_game_callback(int result, const char *error_message,
rc_client_t *client, void *userdata);
static void ra_login_callback(int result, const char *error_message,
rc_client_t *client, void *userdata)
{
(void)client;
(void)userdata;