forked from snes9xgit/snes9x
-
Notifications
You must be signed in to change notification settings - Fork 15
/
lua-engine.cpp
6455 lines (5833 loc) · 178 KB
/
lua-engine.cpp
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
#ifdef HAVE_LUA
#include "port.h"
#include "snes9x.h"
#include "display.h"
#include "ppu.h"
#include "movie.h"
#include "snapshot.h"
#include "pixform.h"
#include "screenshot.h"
#include "controls.h"
#include "lua-engine.h"
#include <assert.h>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
#include "zlib.h"
#ifdef __WIN32__
#include <windows.h>
#include <direct.h>
#include "win32/wsnes9x.h"
#include "win32/render.h"
#define g_hWnd GUI.hWnd
#ifdef UNICODE
#undef fopen
#define fopen fopenA
#undef open
#define open openA
#endif
#endif
bool g_disableStatestateWarnings = false;
bool g_onlyCallSavestateCallbacks = false;
// the emulator must provide these so that we can implement
// the various functions the user can call from their lua script
// (this interface with the emulator needs cleanup, I know)
// adapted from gens-rr, nitsuja + upthorn
extern int (*Update_Frame)();
extern int (*Update_Frame_Fast)();
extern "C" {
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include "lstate.h"
};
enum SpeedMode
{
SPEEDMODE_NORMAL,
SPEEDMODE_NOTHROTTLE,
SPEEDMODE_TURBO,
SPEEDMODE_MAXIMUM,
};
struct LuaGUIData
{
uint32 *data;
int stridePix;
int xOrigin, yOrigin;
int xMin, yMin, xMax, yMax;
};
uint32 luaGuiDataBuf[SNES_WIDTH * SNES_HEIGHT_EXTENDED];
struct LuaContextInfo {
lua_State* L; // the Lua state
bool started; // script has been started and hasn't yet been terminated, although it may not be currently running
bool running; // script is currently running code (either the main call to the script or the callbacks it registered)
bool returned; // main call to the script has returned (but it may still be active if it registered callbacks)
bool crashed; // true if script has errored out
bool restart; // if true, tells the script-running code to restart the script when the script stops
bool restartLater; // set to true when a still-running script is stopped so that RestartAllLuaScripts can know which scripts to restart
unsigned int worryCount; // counts up as the script executes, gets reset when the application is able to process messages, triggers a warning prompt if it gets too high
bool stopWorrying; // set to true if the user says to let the script run forever despite appearing to be frozen
bool panic; // if set to true, tells the script to terminate as soon as it can do so safely (used because directly calling lua_close() or luaL_error() is unsafe in some contexts)
bool ranExit; // used to prevent a registered exit callback from ever getting called more than once
bool guiFuncsNeedDeferring; // true whenever GUI drawing would be cleared by the next emulation update before it would be visible, and thus needs to be deferred until after the next emulation update
bool ranFrameAdvance; // false if emu.frameadvance() hasn't been called yet
int transparencyModifier; // values less than 255 will scale down the opacity of whatever the GUI renders, values greater than 255 will increase the opacity of anything transparent the GUI renders
SpeedMode speedMode; // determines how emu.frameadvance() acts
char panicMessage [72]; // a message to print if the script terminates due to panic being set
std::string lastFilename; // path to where the script last ran from so that restart can work (note: storing the script in memory instead would not be useful because we always want the most up-to-date script from file)
std::string nextFilename; // path to where the script should run from next, mainly used in case the restart flag is true
unsigned int dataSaveKey; // crc32 of the save data key, used to decide which script should get which data... by default (if no key is specified) it's calculated from the script filename
unsigned int dataLoadKey; // same as dataSaveKey but set through registerload instead of registersave if the two differ
bool dataSaveLoadKeySet; // false if the data save keys are unset or set to their default value
bool rerecordCountingDisabled; // true if this script has disabled rerecord counting for the savestates it loads
std::vector<std::string> persistVars; // names of the global variables to persist, kept here so their associated values can be output when the script exits
LuaSaveData newDefaultData; // data about the default state of persisted global variables, which we save on script exit so we can detect when the default value has changed to make it easier to reset persisted variables
unsigned int numMemHooks; // number of registered memory functions (1 per hooked byte)
LuaGUIData guiData;
// callbacks into the lua window... these don't need to exist per context the way I'm using them, but whatever
void(*print)(int uid, const char* str);
void(*onstart)(int uid);
void(*onstop)(int uid, bool statusOK);
};
std::map<int, LuaContextInfo*> luaContextInfo;
std::map<lua_State*, int> luaStateToUIDMap;
int g_numScriptsStarted = 0;
bool g_anyScriptsHighSpeed = false;
bool g_stopAllScriptsEnabled = true;
#define USE_INFO_STACK
#ifdef USE_INFO_STACK
std::vector<LuaContextInfo*> infoStack;
#define GetCurrentInfo() *infoStack.front() // should be faster but relies on infoStack correctly being updated to always have the current info in the first element
#else
std::map<lua_State*, LuaContextInfo*> luaStateToContextMap;
#define GetCurrentInfo() *luaStateToContextMap[L] // should always work but might be slower
#endif
//#define ASK_USER_ON_FREEZE // dialog on freeze is disabled now because it seems to be unnecessary, but this can be re-defined to enable it
static std::map<lua_CFunction, const char*> s_cFuncInfoMap;
// using this macro you can define a callable-from-Lua function
// while associating with it some information about its arguments.
// that information will show up if the user tries to print the function
// or otherwise convert it to a string.
// (for example, "writebyte=function(addr,value)" instead of "writebyte=function:0A403490")
// note that the user can always use addressof(func) if they want to retrieve the address.
#define DEFINE_LUA_FUNCTION(name, argstring) \
static int name(lua_State* L); \
static const char* name##_args = s_cFuncInfoMap[name] = argstring; \
static int name(lua_State* L)
#ifdef _MSC_VER
#define snprintf _snprintf
#define vscprintf _vscprintf
#else
#define stricmp strcasecmp
#define strnicmp strncasecmp
#define __forceinline __attribute__((always_inline))
#endif
static const char* luaCallIDStrings [] =
{
"CALL_BEFOREEMULATION",
"CALL_AFTEREMULATION",
"CALL_AFTEREMULATIONGUI",
"CALL_BEFOREEXIT",
"CALL_BEFORESAVE",
"CALL_AFTERLOAD",
"CALL_ONSTART",
"CALL_HOTKEY_1",
"CALL_HOTKEY_2",
"CALL_HOTKEY_3",
"CALL_HOTKEY_4",
"CALL_HOTKEY_5",
"CALL_HOTKEY_6",
"CALL_HOTKEY_7",
"CALL_HOTKEY_8",
"CALL_HOTKEY_9",
"CALL_HOTKEY_10",
"CALL_HOTKEY_11",
"CALL_HOTKEY_12",
"CALL_HOTKEY_13",
"CALL_HOTKEY_14",
"CALL_HOTKEY_15",
"CALL_HOTKEY_16",
};
static const int _makeSureWeHaveTheRightNumberOfStrings [sizeof(luaCallIDStrings)/sizeof(*luaCallIDStrings) == LUACALL_COUNT ? 1 : 0];
static const char* luaMemHookTypeStrings [] =
{
"MEMHOOK_WRITE",
"MEMHOOK_READ",
"MEMHOOK_EXEC",
"MEMHOOK_WRITE_SUB",
"MEMHOOK_READ_SUB",
"MEMHOOK_EXEC_SUB",
};
static const int _makeSureWeHaveTheRightNumberOfStrings2 [sizeof(luaMemHookTypeStrings)/sizeof(*luaMemHookTypeStrings) == LUAMEMHOOK_COUNT ? 1 : 0];
void StopScriptIfFinished(int uid, bool justReturned = false);
void SetSaveKey(LuaContextInfo& info, const char* key);
void SetLoadKey(LuaContextInfo& info, const char* key);
void RefreshScriptStartedStatus();
void RefreshScriptSpeedStatus();
static char* rawToCString(lua_State* L, int idx=0);
static const char* toCString(lua_State* L, int idx=0);
static void CalculateMemHookRegions(LuaMemHookType hookType);
static int memory_registerHook(lua_State* L, LuaMemHookType hookType, int defaultSize)
{
// get first argument: address
unsigned int addr = luaL_checkinteger(L,1);
if((addr & ~0xFFFFFF) == ~0xFFFFFF)
addr &= 0xFFFFFF;
// get optional second argument: size
int size = defaultSize;
int funcIdx = 2;
if(lua_isnumber(L,2))
{
size = luaL_checkinteger(L,2);
if(size < 0)
{
size = -size;
addr -= size;
}
funcIdx++;
}
// check last argument: callback function
bool clearing = lua_isnil(L,funcIdx);
if(!clearing)
luaL_checktype(L, funcIdx, LUA_TFUNCTION);
lua_settop(L,funcIdx);
// get the address-to-callback table for this hook type of the current script
lua_getfield(L, LUA_REGISTRYINDEX, luaMemHookTypeStrings[hookType]);
// count how many callback functions we'll be displacing
int numFuncsAfter = clearing ? 0 : size;
int numFuncsBefore = 0;
for(unsigned int i = addr; i != addr+size; i++)
{
lua_rawgeti(L, -1, i);
if(lua_isfunction(L, -1))
numFuncsBefore++;
lua_pop(L,1);
}
// put the callback function in the address slots
for(unsigned int i = addr; i != addr+size; i++)
{
lua_pushvalue(L, -2);
lua_rawseti(L, -2, i);
}
// adjust the count of active hooks
LuaContextInfo& info = GetCurrentInfo();
info.numMemHooks += numFuncsAfter - numFuncsBefore;
// re-cache regions of hooked memory across all scripts
CalculateMemHookRegions(hookType);
StopScriptIfFinished(luaStateToUIDMap[L]);
return 0;
}
LuaMemHookType MatchHookTypeToCPU(lua_State* L, LuaMemHookType hookType)
{
int cpuID = 0;
int cpunameIndex = 0;
if(lua_type(L,2) == LUA_TSTRING)
cpunameIndex = 2;
else if(lua_type(L,3) == LUA_TSTRING)
cpunameIndex = 3;
if(cpunameIndex)
{
const char* cpuName = lua_tostring(L, cpunameIndex);
//if(stricmp(cpuName, "sa1") == 0)
// cpuID = 1;
lua_remove(L, cpunameIndex);
}
switch(cpuID)
{
case 0: // 65c816:
return hookType;
// case 1: // sa1:
// switch(hookType)
// {
// case LUAMEMHOOK_WRITE: return LUAMEMHOOK_WRITE_SUB;
// case LUAMEMHOOK_READ: return LUAMEMHOOK_READ_SUB;
// case LUAMEMHOOK_EXEC: return LUAMEMHOOK_EXEC_SUB;
// }
}
return hookType;
}
DEFINE_LUA_FUNCTION(memory_registerwrite, "address,[size=1,][cpuname=\"main\",]func")
{
return memory_registerHook(L, MatchHookTypeToCPU(L,LUAMEMHOOK_WRITE), 1);
}
DEFINE_LUA_FUNCTION(memory_registerread, "address,[size=1,][cpuname=\"main\",]func")
{
return memory_registerHook(L, MatchHookTypeToCPU(L,LUAMEMHOOK_READ), 1);
}
DEFINE_LUA_FUNCTION(memory_registerexec, "address,[size=2,][cpuname=\"main\",]func")
{
return memory_registerHook(L, MatchHookTypeToCPU(L,LUAMEMHOOK_EXEC), 2);
}
DEFINE_LUA_FUNCTION(emu_registerbefore, "func")
{
if (!lua_isnil(L,1))
luaL_checktype(L, 1, LUA_TFUNCTION);
lua_settop(L,1);
lua_getfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_BEFOREEMULATION]);
lua_insert(L,1);
lua_setfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_BEFOREEMULATION]);
StopScriptIfFinished(luaStateToUIDMap[L]);
return 1;
}
DEFINE_LUA_FUNCTION(emu_registerafter, "func")
{
if (!lua_isnil(L,1))
luaL_checktype(L, 1, LUA_TFUNCTION);
lua_settop(L,1);
lua_getfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_AFTEREMULATION]);
lua_insert(L,1);
lua_setfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_AFTEREMULATION]);
StopScriptIfFinished(luaStateToUIDMap[L]);
return 1;
}
DEFINE_LUA_FUNCTION(emu_registerexit, "func")
{
if (!lua_isnil(L,1))
luaL_checktype(L, 1, LUA_TFUNCTION);
lua_settop(L,1);
lua_getfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_BEFOREEXIT]);
lua_insert(L,1);
lua_setfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_BEFOREEXIT]);
StopScriptIfFinished(luaStateToUIDMap[L]);
return 1;
}
DEFINE_LUA_FUNCTION(emu_registerstart, "func")
{
if (!lua_isnil(L,1))
luaL_checktype(L, 1, LUA_TFUNCTION);
lua_settop(L,1);
lua_getfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_ONSTART]);
lua_insert(L,1);
lua_pushvalue(L,-1); // copy the function so we can also call it
lua_setfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_ONSTART]);
if (!lua_isnil(L,-1) && !Settings.StopEmulation)
lua_call(L,0,0); // call the function now since the game has already started and this start function hasn't been called yet
StopScriptIfFinished(luaStateToUIDMap[L]);
return 1;
}
DEFINE_LUA_FUNCTION(gui_register, "func")
{
if (!lua_isnil(L,1))
luaL_checktype(L, 1, LUA_TFUNCTION);
lua_settop(L,1);
lua_getfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_AFTEREMULATIONGUI]);
lua_insert(L,1);
lua_setfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_AFTEREMULATIONGUI]);
StopScriptIfFinished(luaStateToUIDMap[L]);
return 1;
}
DEFINE_LUA_FUNCTION(state_registersave, "func[,savekey]")
{
if (!lua_isnil(L,1))
luaL_checktype(L, 1, LUA_TFUNCTION);
if (!lua_isnoneornil(L,2))
SetSaveKey(GetCurrentInfo(), rawToCString(L,2));
lua_settop(L,1);
lua_getfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_BEFORESAVE]);
lua_insert(L,1);
lua_setfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_BEFORESAVE]);
StopScriptIfFinished(luaStateToUIDMap[L]);
return 1;
}
DEFINE_LUA_FUNCTION(state_registerload, "func[,loadkey]")
{
if (!lua_isnil(L,1))
luaL_checktype(L, 1, LUA_TFUNCTION);
if (!lua_isnoneornil(L,2))
SetLoadKey(GetCurrentInfo(), rawToCString(L,2));
lua_settop(L,1);
lua_getfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_AFTERLOAD]);
lua_insert(L,1);
lua_setfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_AFTERLOAD]);
StopScriptIfFinished(luaStateToUIDMap[L]);
return 1;
}
DEFINE_LUA_FUNCTION(input_registerhotkey, "keynum,func")
{
int hotkeyNumber = luaL_checkinteger(L,1);
if(hotkeyNumber < 1 || hotkeyNumber > 16)
{
luaL_error(L, "input.registerhotkey(n,func) requires 1 <= n <= 16, but got n = %d.", hotkeyNumber);
return 0;
}
else
{
const char* key = luaCallIDStrings[LUACALL_SCRIPT_HOTKEY_1 + hotkeyNumber-1];
lua_getfield(L, LUA_REGISTRYINDEX, key);
lua_replace(L,1);
if (!lua_isnil(L,2))
luaL_checktype(L, 2, LUA_TFUNCTION);
lua_settop(L,2);
lua_setfield(L, LUA_REGISTRYINDEX, key);
StopScriptIfFinished(luaStateToUIDMap[L]);
return 1;
}
}
static int doPopup(lua_State* L, const char* deftype, const char* deficon)
{
const char* str = toCString(L,1);
const char* type = lua_type(L,2) == LUA_TSTRING ? lua_tostring(L,2) : deftype;
const char* icon = lua_type(L,3) == LUA_TSTRING ? lua_tostring(L,3) : deficon;
int itype = -1, iters = 0;
while(itype == -1 && iters++ < 2)
{
if(!stricmp(type, "ok")) itype = 0;
else if(!stricmp(type, "yesno")) itype = 1;
else if(!stricmp(type, "yesnocancel")) itype = 2;
else if(!stricmp(type, "okcancel")) itype = 3;
else if(!stricmp(type, "abortretryignore")) itype = 4;
else type = deftype;
}
assert(itype >= 0 && itype <= 4);
if(!(itype >= 0 && itype <= 4)) itype = 0;
int iicon = -1; iters = 0;
while(iicon == -1 && iters++ < 2)
{
if(!stricmp(icon, "message") || !stricmp(icon, "notice")) iicon = 0;
else if(!stricmp(icon, "question")) iicon = 1;
else if(!stricmp(icon, "warning")) iicon = 2;
else if(!stricmp(icon, "error")) iicon = 3;
else icon = deficon;
}
assert(iicon >= 0 && iicon <= 3);
if(!(iicon >= 0 && iicon <= 3)) iicon = 0;
static const char * const titles [] = {"Notice", "Question", "Warning", "Error"};
const char* answer = "ok";
#ifdef __WIN32__
static const int etypes [] = {MB_OK, MB_YESNO, MB_YESNOCANCEL, MB_OKCANCEL, MB_ABORTRETRYIGNORE};
static const int eicons [] = {MB_ICONINFORMATION, MB_ICONQUESTION, MB_ICONWARNING, MB_ICONERROR};
int uid = luaStateToUIDMap[L];
EnableWindow(g_hWnd, false);
// if (Full_Screen)
// {
// while (ShowCursor(false) >= 0);
// while (ShowCursor(true) < 0);
// }
int ianswer = MessageBoxA((HWND)uid, str, titles[iicon], etypes[itype] | eicons[iicon]);
EnableWindow(g_hWnd, true);
switch(ianswer)
{
case IDOK: answer = "ok"; break;
case IDCANCEL: answer = "cancel"; break;
case IDABORT: answer = "abort"; break;
case IDRETRY: answer = "retry"; break;
case IDIGNORE: answer = "ignore"; break;
case IDYES: answer = "yes"; break;
case IDNO: answer = "no"; break;
}
#else
// NYI (assume first answer for now)
switch(itype)
{
case 0: case 3: answer = "ok"; break;
case 1: case 2: answer = "yes"; break;
case 4: answer = "abort"; break;
}
#endif
lua_pushstring(L, answer);
return 1;
}
// string gui.popup(string message, string type = "ok", string icon = "message")
// string input.popup(string message, string type = "yesno", string icon = "question")
DEFINE_LUA_FUNCTION(gui_popup, "message[,type=\"ok\"[,icon=\"message\"]]")
{
return doPopup(L, "ok", "message");
}
DEFINE_LUA_FUNCTION(input_popup, "message[,type=\"yesno\"[,icon=\"question\"]]")
{
return doPopup(L, "yesno", "question");
}
static const char* FilenameFromPath(const char* path)
{
const char* slash1 = strrchr(path, '\\');
const char* slash2 = strrchr(path, '/');
if(slash1) slash1++;
if(slash2) slash2++;
const char* rv = path;
rv = std::max(rv, slash1);
rv = std::max(rv, slash2);
if(!rv) rv = "";
return rv;
}
void TrimFilenameFromPath(char* path)
{
char* slash1 = strrchr(path, '\\');
char* slash2 = strrchr(path, '/');
char* slash = slash1;
if (slash == NULL || slash2 > slash) {
slash = slash2;
}
if (slash != NULL) {
*(slash + 1) = '\0';
}
}
static void toCStringConverter(lua_State* L, int i, char*& ptr, int& remaining);
// compare the contents of two items on the Lua stack to determine if they differ
// only works for relatively simple, saveable items (numbers, strings, bools, nil, and possibly-nested tables of those, up to a certain max length)
// not the best implementation, but good enough for what it's currently used for
static bool luaValueContentsDiffer(lua_State* L, int idx1, int idx2)
{
static const int maxLen = 8192;
static char str1[maxLen];
static char str2[maxLen];
str1[0] = 0;
str2[0] = 0;
char* ptr1 = str1;
char* ptr2 = str2;
int remaining1 = maxLen;
int remaining2 = maxLen;
toCStringConverter(L, idx1, ptr1, remaining1);
toCStringConverter(L, idx2, ptr2, remaining2);
return (remaining1 != remaining2) || (strcmp(str1,str2) != 0);
}
void Get_State_File_Name(char *name, int stateNumber = 0)
{
char drive[_MAX_DRIVE + 1], dir[_MAX_DIR + 1], def[_MAX_FNAME + 1], ext[_MAX_EXT + 1];
_splitpath(Memory.ROMFilename, drive, dir, def, ext);
sprintf(name, "%s%s%s.%03d", S9xGetDirectory(SNAPSHOT_DIR), SLASH_STR, def, stateNumber);
}
// fills output with the path
// also returns a pointer to the first character in the filename (non-directory) part of the path
static char* ConstructScriptSaveDataPath(char* output, int bufferSize, LuaContextInfo& info)
{
Get_State_File_Name(output);
char* slash1 = strrchr(output, '\\');
char* slash2 = strrchr(output, '/');
if(slash1) slash1[1] = '\0';
if(slash2) slash2[1] = '\0';
char* rv = output + strlen(output);
strncat(output, "u.", bufferSize-(strlen(output)+1));
if(!info.dataSaveLoadKeySet)
strncat(output, FilenameFromPath(info.lastFilename.c_str()), bufferSize-(strlen(output)+1));
else
snprintf(output+strlen(output), bufferSize-(strlen(output)+1), "%X", info.dataSaveKey);
strncat(output, ".luasav", bufferSize-(strlen(output)+1));
return rv;
}
// emu.persistglobalvariables({
// variable1 = defaultvalue1,
// variable2 = defaultvalue2,
// etc
// })
// takes a table with variable names as the keys and default values as the values,
// and defines each of those variables names as a global variable,
// setting them equal to the values they had the last time the script exited,
// or (if that isn't available) setting them equal to the provided default values.
// as a special case, if you want the default value for a variable to be nil,
// then put the variable name alone in quotes as an entry in the table without saying "= nil".
// this special case is because tables in lua don't store nil valued entries.
// also, if you change the default value that will reset the variable to the new default.
DEFINE_LUA_FUNCTION(emu_persistglobalvariables, "variabletable")
{
int uid = luaStateToUIDMap[L];
LuaContextInfo& info = GetCurrentInfo();
// construct a path we can load the persistent variables from
char path [1024] = {0};
char* pathTypeChrPtr = ConstructScriptSaveDataPath(path, 1024, info);
// load the previously-saved final variable values from file
LuaSaveData exitData;
{
*pathTypeChrPtr = 'e';
FILE* persistFile = fopen(path, "rb");
if(persistFile)
{
exitData.ImportRecords(persistFile);
fclose(persistFile);
}
}
// load the previously-saved default variable values from file
LuaSaveData defaultData;
{
*pathTypeChrPtr = 'd';
FILE* defaultsFile = fopen(path, "rb");
if(defaultsFile)
{
defaultData.ImportRecords(defaultsFile);
fclose(defaultsFile);
}
}
// loop through the passed-in variables,
// exposing a global variable to the script for each one
// while also keeping a record of their names
// so we can save them (to the persistFile) later when the script exits
int numTables = lua_gettop(L);
for(int i = 1; i <= numTables; i++)
{
luaL_checktype(L, i, LUA_TTABLE);
lua_pushnil(L); // before first key
int keyIndex = lua_gettop(L);
int valueIndex = keyIndex + 1;
while(lua_next(L, i))
{
int keyType = lua_type(L, keyIndex);
int valueType = lua_type(L, valueIndex);
if(keyType == LUA_TSTRING && valueType <= LUA_TTABLE && valueType != LUA_TLIGHTUSERDATA)
{
// variablename = defaultvalue,
// duplicate the key first because lua_next() needs to eat that
lua_pushvalue(L, keyIndex);
lua_insert(L, keyIndex);
}
else if(keyType == LUA_TNUMBER && valueType == LUA_TSTRING)
{
// "variablename",
// or [index] = "variablename",
// defaultvalue is assumed to be nil
lua_pushnil(L);
}
else
{
luaL_error(L, "'%s' = '%s' entries are not allowed in the table passed to emu.persistglobalvariables()", lua_typename(L,keyType), lua_typename(L,valueType));
}
int varNameIndex = valueIndex;
int defaultIndex = valueIndex+1;
// keep track of the variable name for later
const char* varName = lua_tostring(L, varNameIndex);
info.persistVars.push_back(varName);
unsigned int varNameCRC = crc32(0, (const unsigned char*)varName, strlen(varName));
info.newDefaultData.SaveRecordPartial(uid, varNameCRC, defaultIndex);
// load the previous default value for this variable if it exists.
// if the new default is different than the old one,
// assume the user wants to set the value to the new default value
// instead of the previously-saved exit value.
bool attemptPersist = true;
defaultData.LoadRecord(uid, varNameCRC, 1);
lua_pushnil(L);
if(luaValueContentsDiffer(L, defaultIndex, defaultIndex+1))
attemptPersist = false;
lua_settop(L, defaultIndex);
if(attemptPersist)
{
// load the previous saved value for this variable if it exists
exitData.LoadRecord(uid, varNameCRC, 1);
if(lua_gettop(L) > defaultIndex)
lua_remove(L, defaultIndex); // replace value with loaded record
lua_settop(L, defaultIndex);
}
// set the global variable
lua_settable(L, LUA_GLOBALSINDEX);
assert(lua_gettop(L) == keyIndex);
}
}
return 0;
}
static const char* deferredGUIIDString = "lazygui";
static const char* deferredJoySetIDString = "lazyjoy";
#define MAX_DEFERRED_COUNT 16384
// store the most recent C function call from Lua (and all its arguments)
// for later evaluation
void DeferFunctionCall(lua_State* L, const char* idstring)
{
// there might be a cleaner way of doing this using lua_pushcclosure and lua_getref
int num = lua_gettop(L);
// get the C function pointer
//lua_CFunction cf = lua_tocfunction(L, -(num+1));
lua_CFunction cf = (L->ci->func)->value.gc->cl.c.f;
assert(cf);
lua_pushcfunction(L,cf);
// make a list of the function and its arguments (and also pop those arguments from the stack)
lua_createtable(L, num+1, 0);
lua_insert(L, 1);
for(int n = num+1; n > 0; n--)
lua_rawseti(L, 1, n);
// put the list into a global array
lua_getfield(L, LUA_REGISTRYINDEX, idstring);
lua_insert(L, 1);
int curSize = lua_objlen(L, 1);
lua_rawseti(L, 1, curSize+1);
// clean the stack
lua_settop(L, 0);
}
void CallDeferredFunctions(lua_State* L, const char* idstring)
{
lua_settop(L, 0);
lua_getfield(L, LUA_REGISTRYINDEX, idstring);
int numCalls = lua_objlen(L, 1);
for(int i = 1; i <= numCalls; i++)
{
lua_rawgeti(L, 1, i); // get the function+arguments list
int listSize = lua_objlen(L, 2);
// push the arguments and the function
for(int j = 1; j <= listSize; j++)
lua_rawgeti(L, 2, j);
// get and pop the function
lua_CFunction cf = lua_tocfunction(L, -1);
lua_pop(L, 1);
// shift first argument to slot 1 and call the function
lua_remove(L, 2);
lua_remove(L, 1);
cf(L);
// prepare for next iteration
lua_settop(L, 0);
lua_getfield(L, LUA_REGISTRYINDEX, idstring);
}
// clear the list of deferred functions
lua_newtable(L);
lua_setfield(L, LUA_REGISTRYINDEX, idstring);
LuaContextInfo& info = GetCurrentInfo();
// clean the stack
lua_settop(L, 0);
}
bool DeferGUIFuncIfNeeded(lua_State* L)
{
LuaContextInfo& info = GetCurrentInfo();
if(info.speedMode == SPEEDMODE_MAXIMUM)
{
// if the mode is "maximum" then discard all GUI function calls
// and pretend it was because we deferred them
return true;
}
if(info.guiFuncsNeedDeferring)
{
// defer whatever function called this one until later
DeferFunctionCall(L, deferredGUIIDString);
return true;
}
// ok to run the function right now
return false;
}
void worry(lua_State* L, int intensity)
{
LuaContextInfo& info = GetCurrentInfo();
info.worryCount += intensity;
}
static inline bool isalphaorunderscore(char c)
{
return isalpha(c) || c == '_';
}
static std::vector<const void*> s_tableAddressStack; // prevents infinite recursion of a table within a table (when cycle is found, print something like table:parent)
static std::vector<const void*> s_metacallStack; // prevents infinite recursion if something's __tostring returns another table that contains that something (when cycle is found, print the inner result without using __tostring)
#define APPENDPRINT { int _n = snprintf(ptr, remaining,
#define END ); if(_n >= 0) { ptr += _n; remaining -= _n; } else { remaining = 0; } }
static void toCStringConverter(lua_State* L, int i, char*& ptr, int& remaining)
{
if(remaining <= 0)
return;
const char* str = ptr; // for debugging
// if there is a __tostring metamethod then call it
int usedMeta = luaL_callmeta(L, i, "__tostring");
if(usedMeta)
{
std::vector<const void*>::const_iterator foundCycleIter = std::find(s_metacallStack.begin(), s_metacallStack.end(), lua_topointer(L,i));
if(foundCycleIter != s_metacallStack.end())
{
lua_pop(L, 1);
usedMeta = false;
}
else
{
s_metacallStack.push_back(lua_topointer(L,i));
i = lua_gettop(L);
}
}
switch(lua_type(L, i))
{
case LUA_TNONE: break;
case LUA_TNIL: APPENDPRINT "nil" END break;
case LUA_TBOOLEAN: APPENDPRINT lua_toboolean(L,i) ? "true" : "false" END break;
case LUA_TSTRING: APPENDPRINT "%s",lua_tostring(L,i) END break;
case LUA_TNUMBER: APPENDPRINT "%.12Lg",lua_tonumber(L,i) END break;
case LUA_TFUNCTION:
if((L->base + i-1)->value.gc->cl.c.isC)
{
lua_CFunction func = lua_tocfunction(L, i);
std::map<lua_CFunction, const char*>::iterator iter = s_cFuncInfoMap.find(func);
if(iter == s_cFuncInfoMap.end())
goto defcase;
APPENDPRINT "function(%s)", iter->second END
}
else
{
APPENDPRINT "function(" END
Proto* p = (L->base + i-1)->value.gc->cl.l.p;
int numParams = p->numparams + (p->is_vararg?1:0);
for (int n=0; n<p->numparams; n++)
{
APPENDPRINT "%s", getstr(p->locvars[n].varname) END
if(n != numParams-1)
APPENDPRINT "," END
}
if(p->is_vararg)
APPENDPRINT "..." END
APPENDPRINT ")" END
}
break;
defcase:default: APPENDPRINT "%s:%p",luaL_typename(L,i),lua_topointer(L,i) END break;
case LUA_TTABLE:
{
// first make sure there's enough stack space
if(!lua_checkstack(L, 4))
{
// note that even if lua_checkstack never returns false,
// that doesn't mean we didn't need to call it,
// because calling it retrieves stack space past LUA_MINSTACK
goto defcase;
}
std::vector<const void*>::const_iterator foundCycleIter = std::find(s_tableAddressStack.begin(), s_tableAddressStack.end(), lua_topointer(L,i));
if(foundCycleIter != s_tableAddressStack.end())
{
int parentNum = s_tableAddressStack.end() - foundCycleIter;
if(parentNum > 1)
APPENDPRINT "%s:parent^%d",luaL_typename(L,i),parentNum END
else
APPENDPRINT "%s:parent",luaL_typename(L,i) END
}
else
{
s_tableAddressStack.push_back(lua_topointer(L,i));
struct Scope { ~Scope(){ s_tableAddressStack.pop_back(); } } scope;
APPENDPRINT "{" END
lua_pushnil(L); // first key
int keyIndex = lua_gettop(L);
int valueIndex = keyIndex + 1;
bool first = true;
bool skipKey = true; // true if we're still in the "array part" of the table
lua_Number arrayIndex = (lua_Number)0;
while(lua_next(L, i))
{
if(first)
first = false;
else
APPENDPRINT ", " END
if(skipKey)
{
arrayIndex += (lua_Number)1;
bool keyIsNumber = (lua_type(L, keyIndex) == LUA_TNUMBER);
skipKey = keyIsNumber && (lua_tonumber(L, keyIndex) == arrayIndex);
}
if(!skipKey)
{
bool keyIsString = (lua_type(L, keyIndex) == LUA_TSTRING);
bool invalidLuaIdentifier = (!keyIsString || !isalphaorunderscore(*lua_tostring(L, keyIndex)));
if(invalidLuaIdentifier)
if(keyIsString)
APPENDPRINT "['" END
else
APPENDPRINT "[" END
toCStringConverter(L, keyIndex, ptr, remaining); // key
if(invalidLuaIdentifier)
if(keyIsString)
APPENDPRINT "']=" END
else
APPENDPRINT "]=" END
else
APPENDPRINT "=" END
}
bool valueIsString = (lua_type(L, valueIndex) == LUA_TSTRING);
if(valueIsString)
APPENDPRINT "'" END
toCStringConverter(L, valueIndex, ptr, remaining); // value
if(valueIsString)
APPENDPRINT "'" END
lua_pop(L, 1);
if(remaining <= 0)
{
lua_settop(L, keyIndex-1); // stack might not be clean yet if we're breaking early
break;
}
}
APPENDPRINT "}" END
}
} break;
}
if(usedMeta)
{
s_metacallStack.pop_back();
lua_pop(L, 1);
}
}
static const int s_tempStrMaxLen = 64 * 1024;
static char s_tempStr [s_tempStrMaxLen];
static char* rawToCString(lua_State* L, int idx)
{
int a = idx>0 ? idx : 1;
int n = idx>0 ? idx : lua_gettop(L);
char* ptr = s_tempStr;
*ptr = 0;
int remaining = s_tempStrMaxLen;
for(int i = a; i <= n; i++)
{
toCStringConverter(L, i, ptr, remaining);
if(i != n)
APPENDPRINT " " END
}
if(remaining < 3)
{
while(remaining < 6)
remaining++, ptr--;
APPENDPRINT "..." END
}
APPENDPRINT "\r\n" END
// the trailing newline is so print() can avoid having to do wasteful things to print its newline
// (string copying would be wasteful and calling info.print() twice can be extremely slow)
// at the cost of functions that don't want the newline needing to trim off the last two characters
// (which is a very fast operation and thus acceptable in this case)
return s_tempStr;
}
#undef APPENDPRINT
#undef END
// replacement for luaB_tostring() that is able to show the contents of tables (and formats numbers better, and show function prototypes)
// can be called directly from lua via tostring(), assuming tostring hasn't been reassigned
DEFINE_LUA_FUNCTION(tostring, "...")
{
char* str = rawToCString(L);
str[strlen(str)-2] = 0; // hack: trim off the \r\n (which is there to simplify the print function's task)
lua_pushstring(L, str);
return 1;
}
// like rawToCString, but will check if the global Lua function tostring()
// has been replaced with a custom function, and call that instead if so
static const char* toCString(lua_State* L, int idx)
{
int a = idx>0 ? idx : 1;
int n = idx>0 ? idx : lua_gettop(L);
lua_getglobal(L, "tostring");