/
main.cpp
executable file
·7651 lines (6582 loc) · 219 KB
/
main.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
/*
Copyright (C) 2006 Theo Berkau
Copyright (C) 2006-2018 DeSmuME team
This file is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This file is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with the this software. If not, see <http://www.gnu.org/licenses/>.
*/
// icon gradient: #f6f6fb to #8080c0
// RGB(246, 246, 251) to RGB(128, 128, 192)
#include "main.h"
#include "windriver.h"
#include <algorithm>
#include <string>
#include <vector>
#include <Winuser.h>
#include <Winnls.h>
#include <windowsx.h>
#include <mmsystem.h>
#include <shellapi.h>
#include <shlwapi.h>
#include <commctrl.h>
#include <commdlg.h>
#include <tchar.h>
#include <stdio.h>
#include <GL/gl.h>
#include <GL/glext.h>
#include <GL/wglext.h>
//emulator core
#include "MMU.h"
#include "armcpu.h"
#include "NDSSystem.h"
#include "driver.h"
#include "debug.h"
#include "saves.h"
#include "slot1.h"
#include "slot2.h"
#include "GPU.h"
#include "SPU.h"
#include "OGLRender.h"
#include "OGLRender_3_2.h"
#include "rasterize.h"
#include "gfx3d.h"
#include "render3D.h"
#include "gdbstub.h"
#include "wifi.h"
#include "cheatSystem.h"
#include "mic.h"
#include "movie.h"
#include "firmware.h"
#include "lua-engine.h"
#include "path.h"
#include "utils/advanscene.h"
//other random stuff
#include "rthreads/rthreads.h"
#include "recentroms.h"
#include "resource.h"
#include "CWindow.h"
#include "version.h"
#include "inputdx.h"
#include "console.h"
#include "throttle.h"
#include "hotkey.h"
#include "snddx.h"
#include "sndxa2.h"
#include "commandline.h"
#include "FEX_Interface.h"
#include "OpenArchive.h"
#include "utils/xstring.h"
#include "directx/ddraw.h"
#include "video.h"
#include "frontend/modules/osd/agg/agg_osd.h"
#include "frontend/modules/osd/agg/aggdraw.h"
#include "frontend/modules/osd/agg/agg2d.h"
#include "frontend/modules/ImageOut.h"
#include "winutil.h"
#include "ogl.h"
//tools and dialogs
#include "pathsettings.h"
#include "colorctrl.h"
#include "ginfo.h"
#include "IORegView.h"
#include "palView.h"
#include "tileView.h"
#include "oamView.h"
#include "mapview.h"
#include "matrixview.h"
#include "lightview.h"
#include "slot1_config.h"
#include "gbaslot_config.h"
#include "cheatsWin.h"
#include "memView.h"
#include "disView.h"
#include "FirmConfig.h"
#include "AboutBox.h"
#include "replay.h"
#include "ramwatch.h"
#include "ram_search.h"
#include "aviout.h"
#include "soundView.h"
#include "importSave.h"
#include "fsnitroView.h"
//
//static size_t heapram = 0;
//void* operator new[](size_t amt)
//{
// if(amt>5*1024*1024)
// {
// int zzz=9;
// }
// printf("Heap alloc up to %d bytes\n",heapram);
// heapram += amt;
// u32* buf = (u32*)malloc(amt+4);
// *buf = amt;
// return buf+1;
//}
//
//void operator delete[](void* ptr)
//{
// if(!ptr) return;
// u32* buf = (u32*)ptr;
// buf--;
// heapram -= *buf;
// free(buf);
//}
//
//void* operator new(size_t amt)
//{
// return operator new[](amt);
//}
//
//void operator delete(void* ptr)
//{
// return operator delete[](ptr);
//}
//#include <libelf/libelf.h>
//#include <libelf/gelf.h>
//#include <sys/types.h>
//#include <sys/stat.h>
//#include <fcntl.h>
//#include <io.h>
//void testelf()
//{
// //http://webcache.googleusercontent.com/search?q=cache:XeQF6AILcrkJ:chris.rohlf.googlepages.com/libelf-howto.c+libelf+example&cd=2&hl=en&ct=clnk&gl=us
//Elf32_Ehdr *elf_header; /* ELF header */
//Elf *elf; /* Our Elf pointer for libelf */
//Elf_Scn *scn; /* Section Descriptor */
//Elf_Data *edata; /* Data Descriptor */
//GElf_Sym sym; /* Symbol */
//GElf_Shdr shdr; /* Section Header */
//int fd; // File Descriptor
//const char* file = "d:\\devkitPro\\examples\\nds\\hello_world\\hello_world.elf";
//struct stat elf_stats; // fstat struct
//char *base_ptr; // ptr to our object in memory
//#define ERR -1
// if((fd = open(file, O_RDWR)) == ERR)
// {
// printf("couldnt open %s\n", file);
// return;
// }
// if((fstat(fd, &elf_stats)))
// {
// printf("could not fstat %s\n", file);
// close(fd);
// return ;
// }
// if((base_ptr = (char *) malloc(elf_stats.st_size)) == NULL)
// {
// printf("could not malloc\n");
// close(fd);
// return ;
// }
// if((read(fd, base_ptr, elf_stats.st_size)) < elf_stats.st_size)
// {
// printf("could not read %s\n", file);
// free(base_ptr);
// close(fd);
// return ;
// }
// /* Check libelf version first */
// if(elf_version(EV_CURRENT) == EV_NONE)
// {
// printf("WARNING Elf Library is out of date!\n");
// }
//elf_header = (Elf32_Ehdr *) base_ptr; // point elf_header at our object in memory
//elf = elf_begin(fd, ELF_C_READ, NULL); // Initialize 'elf' pointer to our file descriptor
///* Iterate through section headers */
//while((scn = elf_nextscn(elf, scn)) != 0)
//{
// gelf_getshdr(scn, &shdr);
// // print the section header type
// printf("Type: ");
// switch(shdr.sh_type)
// {
// case SHT_NULL: printf( "SHT_NULL\t"); break;
// case SHT_PROGBITS: printf( "SHT_PROGBITS"); break;
// case SHT_SYMTAB: printf( "SHT_SYMTAB"); break;
// case SHT_STRTAB: printf( "SHT_STRTAB"); break;
// case SHT_RELA: printf( "SHT_RELA\t"); break;
// case SHT_HASH: printf( "SHT_HASH\t"); break;
// case SHT_DYNAMIC: printf( "SHT_DYNAMIC"); break;
// case SHT_NOTE: printf( "SHT_NOTE\t"); break;
// case SHT_NOBITS: printf( "SHT_NOBITS"); break;
// case SHT_REL: printf( "SHT_REL\t"); break;
// case SHT_SHLIB: printf( "SHT_SHLIB"); break;
// case SHT_DYNSYM: printf( "SHT_DYNSYM"); break;
// case SHT_INIT_ARRAY: printf( "SHT_INIT_ARRAY"); break;
// case SHT_FINI_ARRAY: printf( "SHT_FINI_ARRAY"); break;
// case SHT_PREINIT_ARRAY: printf( "SHT_PREINIT_ARRAY"); break;
// case SHT_GROUP: printf( "SHT_GROUP"); break;
// case SHT_SYMTAB_SHNDX: printf( "SHT_SYMTAB_SHNDX"); break;
// case SHT_NUM: printf( "SHT_NUM\t"); break;
// case SHT_LOOS: printf( "SHT_LOOS\t"); break;
// case SHT_GNU_verdef: printf( "SHT_GNU_verdef"); break;
// case SHT_GNU_verneed: printf( "SHT_VERNEED"); break;
// case SHT_GNU_versym: printf( "SHT_GNU_versym"); break;
// default: printf( "(none) "); break;
// }
// // print the section header flags
// printf("\t(");
// if(shdr.sh_flags & SHF_WRITE) { printf("W"); }
// if(shdr.sh_flags & SHF_ALLOC) { printf("A"); }
// if(shdr.sh_flags & SHF_EXECINSTR) { printf("X"); }
// if(shdr.sh_flags & SHF_STRINGS) { printf("S"); }
// printf(")\t");
// // the shdr name is in a string table, libelf uses elf_strptr() to find it
// // using the e_shstrndx value from the elf_header
// printf("%s\n", elf_strptr(elf, elf_header->e_shstrndx, shdr.sh_name));
//}
//}
using namespace std;
//====================== Message box
#define MSG_ARG \
char msg_buf[1024] = {0}; \
{ \
va_list args; \
va_start (args, fmt); \
vsprintf (msg_buf, fmt, args); \
va_end (args); \
}
void msgWndInfo(const char *fmt, ...)
{
MSG_ARG;
printf("[INFO] %s\n", msg_buf);
MessageBox(MainWindow->getHWnd(), msg_buf, EMU_DESMUME_NAME_AND_VERSION(), MB_OK | MB_ICONINFORMATION);
}
bool msgWndConfirm(const char *fmt, ...)
{
MSG_ARG;
printf("[CONF] %s\n", msg_buf);
return (MessageBox(MainWindow->getHWnd(), msg_buf, EMU_DESMUME_NAME_AND_VERSION(), MB_YESNO | MB_ICONQUESTION) == IDYES);
}
void msgWndError(const char *fmt, ...)
{
MSG_ARG;
printf("[ERR] %s\n", msg_buf);
MessageBox(MainWindow->getHWnd(), msg_buf, EMU_DESMUME_NAME_AND_VERSION(), MB_OK | MB_ICONERROR);
}
void msgWndWarn(const char *fmt, ...)
{
MSG_ARG;
printf("[WARN] %s\n", msg_buf);
MessageBox(MainWindow->getHWnd(), msg_buf, EMU_DESMUME_NAME_AND_VERSION(), MB_OK | MB_ICONWARNING);
}
msgBoxInterface msgBoxWnd = {
msgWndInfo,
msgWndConfirm,
msgWndError,
msgWndWarn,
};
//====================== Dialogs end
#ifdef EXPERIMENTAL_WIFI_COMM
bool bSocketsAvailable = false;
#include "winpcap.h"
#endif
VideoInfo video;
#ifndef PUBLIC_RELEASE
#define DEVELOPER_MENU_ITEMS
#endif
const int kGapNone = 0;
const int kGapBorder = 5;
const int kGapNDS = 64; // extremely tilted (but some games seem to use this value)
const int kGapNDS2 = 90; // more normal viewing angle
const int kScale1point5x = 65535;
const int kScale2point5x = 65534;
static BOOL OpenCore(const char* filename);
BOOL Mic_DeInit_Physical();
BOOL Mic_Init_Physical();
void UpdateHotkeyAssignments(); //Appends hotkey mappings to corresponding menu items
DWORD dwMainThread;
HMENU mainMenu = NULL; //Holds handle to the main DeSmuME menu
CToolBar* MainWindowToolbar;
DWORD hKeyInputTimer;
bool start_paused;
extern bool killStylusTopScreen;
extern bool killStylusOffScreen;
int gpu_bpp = 18;
extern LRESULT CALLBACK RamSearchProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
void InitRamSearch();
void FilterUpdate(HWND hwnd, bool user=true);
CRITICAL_SECTION win_execute_sync;
volatile int win_sound_samplecounter = 0;
CRITICAL_SECTION win_backbuffer_sync;
volatile bool backbuffer_invalidate = false;
Lock::Lock() : m_cs(&win_execute_sync) { EnterCriticalSection(m_cs); }
Lock::Lock(CRITICAL_SECTION& cs) : m_cs(&cs) { EnterCriticalSection(m_cs); }
Lock::~Lock() { LeaveCriticalSection(m_cs); }
//====================== DirectDraw
const char *DDerrors[] = { "no errors",
"Unable to initialize DirectDraw",
"Unable to set DirectDraw Cooperative Level",
"Unable to create DirectDraw primary surface",
"Unable to set DirectDraw clipper"};
struct DDRAW
{
DDRAW():
handle(NULL), clip(NULL)
{
surface.primary = NULL;
surface.back = NULL;
memset(&surfDesc, 0, sizeof(surfDesc));
memset(&surfDescBack, 0, sizeof(surfDescBack));
}
u32 create(HWND hwnd);
bool release();
bool createSurfaces(HWND hwnd);
bool createBackSurface(int width, int height);
bool lock();
bool unlock();
bool blt(LPRECT dst, LPRECT src);
bool OK();
LPDIRECTDRAW7 handle;
struct
{
LPDIRECTDRAWSURFACE7 primary;
LPDIRECTDRAWSURFACE7 back;
} surface;
DDSURFACEDESC2 surfDesc;
DDSURFACEDESC2 surfDescBack;
LPDIRECTDRAWCLIPPER clip;
} ddraw;
//===================== Input vars
#define WM_CUSTKEYDOWN (WM_USER+50)
#define WM_CUSTKEYUP (WM_USER+51)
#define WM_CUSTINVOKE (WM_USER+52)
#ifndef __WISPSHRD_H
#define WM_TABLET_DEFBASE 0x02C0
#define WM_TABLET_MAXOFFSET 0x20
#define WM_TABLET_FLICK (WM_TABLET_DEFBASE + 11)
#define WM_TABLET_QUERYSYSTEMGESTURESTATUS (WM_TABLET_DEFBASE + 12)
#define MICROSOFT_TABLETPENSERVICE_PROPERTY _T("MicrosoftTabletPenServiceProperty")
#define TABLET_DISABLE_PRESSANDHOLD 0x00000001
#define TABLET_DISABLE_PENTAPFEEDBACK 0x00000008
#define TABLET_DISABLE_PENBARRELFEEDBACK 0x00000010
#define TABLET_DISABLE_TOUCHUIFORCEON 0x00000100
#define TABLET_DISABLE_TOUCHUIFORCEOFF 0x00000200
#define TABLET_DISABLE_TOUCHSWITCH 0x00008000
#define TABLET_DISABLE_FLICKS 0x00010000
#define TABLET_ENABLE_FLICKSONCONTEXT 0x00020000
#define TABLET_ENABLE_FLICKLEARNINGMODE 0x00040000
#define TABLET_DISABLE_SMOOTHSCROLLING 0x00080000
#define TABLET_DISABLE_FLICKFALLBACKKEYS 0x00100000
#endif
LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);
char SavName[MAX_PATH] = {0};
char ImportSavName[MAX_PATH] = {0};
char szClassName[ ] = "DeSmuME";
int romnum = 0;
DWORD threadID;
WINCLASS *MainWindow=NULL;
bool gShowConsole = false;
bool gConsoleTopmost = false;
//HWND hwnd;
//HDC hdc;
HACCEL hAccel;
HINSTANCE hAppInst = NULL;
RECT FullScreenRect, MainScreenRect, SubScreenRect, GapRect;
RECT MainScreenSrcRect, SubScreenSrcRect;
int WndX = 0;
int WndY = 0;
extern HWND RamSearchHWnd;
static bool lostFocusPause = true;
static bool lastPauseFromLostFocus = false;
bool FrameLimit = true;
extern bool allowBackgroundInput;
std::vector<HWND> LuaScriptHWnds;
LRESULT CALLBACK LuaScriptProc(HWND, UINT, WPARAM, LPARAM);
bool autoLoadLua;
#define MAX_RECENT_SCRIPTS 15 // must match value in luaconsole.cpp (belongs in a header, but I didn't want to create one just for this)
extern char Recent_Scripts[MAX_RECENT_SCRIPTS][1024];
//=========================== view tools
TOOLSCLASS *ViewDisasm_ARM7 = NULL;
TOOLSCLASS *ViewDisasm_ARM9 = NULL;
TOOLSCLASS *ViewPalette = NULL;
TOOLSCLASS *ViewTiles = NULL;
TOOLSCLASS *ViewMaps = NULL;
TOOLSCLASS *ViewOAM = NULL;
TOOLSCLASS *ViewMatrices = NULL;
TOOLSCLASS *ViewLights = NULL;
TOOLSCLASS *ViewFSNitro = NULL;
volatile bool execute = false;
volatile bool paused = true;
volatile BOOL pausedByMinimize = FALSE;
u32 glock = 0;
// Scanline filter parameters. The first set is from commandline.cpp, the second
// set is externed to scanline.cpp.
// TODO: When videofilter.cpp becomes Windows-friendly, remove the second set of
// variables, as they will no longer be necessary at that point.
extern int _scanline_filter_a;
extern int _scanline_filter_b;
extern int _scanline_filter_c;
extern int _scanline_filter_d;
int scanline_filter_a = 0;
int scanline_filter_b = 2;
int scanline_filter_c = 2;
int scanline_filter_d = 4;
BOOL finished = FALSE;
bool romloaded = false;
void SetScreenGap(int gap);
bool ForceRatio = true;
bool PadToInteger = false;
bool SeparationBorderDrag = true;
int ScreenGapColor = 0xFFFFFF;
float DefaultWidth;
float DefaultHeight;
float widthTradeOff;
float heightTradeOff;
extern bool StylusAutoHoldPressed;
extern POINT winLastTouch;
extern bool userTouchesScreen;
/*__declspec(thread)*/ bool inFrameBoundary = false;
static int sndcoretype=SNDCORE_DIRECTX;
static int sndbuffersize=DESMUME_SAMPLE_RATE*8/60;
int sndvolume=100;
SoundInterface_struct *SNDCoreList[] = {
&SNDDummy,
&SNDDIRECTX,
&SNDXAUDIO2,
NULL
};
GPU3DInterface *core3DList[] = {
&gpu3DNull,
&gpu3Dgl_3_2,
&gpu3DRasterize,
&gpu3DglOld,
NULL
};
bool autoframeskipenab=1;
int frameskiprate=0;
int lastskiprate=0;
int emu_paused = 0;
bool frameAdvance = false;
bool continuousframeAdvancing = false;
unsigned short windowSize = 0;
/*const u32 gapColors[16] = {
Color::Gray,
Color::Brown,
Color::Red,
Color::Pink,
Color::Orange,
Color::Yellow,
Color::LightGreen,
Color::Lime,
Color::Green,
Color::SeaGreen,
Color::SkyBlue,
Color::Blue,
Color::DarkBlue,
Color::DarkViolet,
Color::Purple,
Color::Fuchsia
};*/
class GPUEventHandlerWindows : public GPUEventHandlerDefault
{
public:
virtual void DidFrameEnd(bool isFrameSkipped, const NDSDisplayInfo &latestDisplayInfo)
{
if (isFrameSkipped)
{
return;
}
DRV_AviVideoUpdate(latestDisplayInfo);
}
};
GPUEventHandlerWindows *WinGPUEvent = NULL;
LRESULT CALLBACK HUDFontSettingsDlgProc(HWND hw, UINT msg, WPARAM wp, LPARAM lp);
LRESULT CALLBACK GFX3DSettingsDlgProc(HWND hw, UINT msg, WPARAM wp, LPARAM lp);
LRESULT CALLBACK SoundSettingsDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK EmulationSettingsDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK MicrophoneSettingsDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
#ifdef EXPERIMENTAL_WIFI_COMM
LRESULT CALLBACK WifiSettingsDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
#endif
//struct configured_features {
// u16 arm9_gdb_port;
// u16 arm7_gdb_port;
//
// const char *cflash_disk_image_file;
//};
static int KeyInDelayMSec = 0;
static int KeyInRepeatMSec = 8;
template<bool JOYSTICK>
static void InputTimer()
{
bool S9xGetState (WORD KeyIdent);
static DWORD lastTime = timeGetTime();
DWORD currentTime = timeGetTime();
static struct JoyState {
bool wasPressed;
DWORD firstPressedTime;
DWORD lastPressedTime;
WORD repeatCount;
} joyState [256*16];
static bool initialized = false;
if(!initialized) {
for(int i = 0; i < 256*16; i++) {
joyState[i].wasPressed = false;
joyState[i].repeatCount = 1;
}
initialized = true;
}
const int nloops = (JOYSTICK) ? 16 : 1;
const HWND mainWindow = MainWindow->getHWnd();
const bool willAcceptInput = ( allowBackgroundInput || (mainWindow == GetForegroundWindow()) );
for (int j = 0; j < nloops; j++)
{
for (int z = 0; z < 256; z++)
{
int i = z | (JOYSTICK?0x8000:0);
i |= (j<<8);
int n = i&0xFFF;
bool active = willAcceptInput && !S9xGetState(i);
if (active)
{
bool keyRepeat = (currentTime - joyState[n].firstPressedTime) >= (DWORD)KeyInDelayMSec;
if (!joyState[n].wasPressed || keyRepeat)
{
if (!joyState[n].wasPressed)
joyState[n].firstPressedTime = currentTime;
joyState[n].lastPressedTime = currentTime;
if (keyRepeat && joyState[n].repeatCount < 0xffff)
joyState[n].repeatCount++;
int mods = GetInitialModifiers(i);
WPARAM wparam = i | (mods << 16) | (j<<8);
PostMessage(mainWindow, WM_CUSTKEYDOWN, wparam,(LPARAM)(joyState[n].repeatCount | (joyState[n].wasPressed ? 0x40000000 : 0)));
}
}
else
{
joyState[n].repeatCount = 1;
if (joyState[n].wasPressed)
{
int mods = GetInitialModifiers(i);
WPARAM wparam = i | (mods << 16) | (j<<8);
PostMessage(mainWindow, WM_CUSTKEYUP, wparam,(LPARAM)(joyState[n].repeatCount | (joyState[n].wasPressed ? 0x40000000 : 0)));
}
}
joyState[n].wasPressed = active;
}
}
lastTime = currentTime;
}
VOID CALLBACK KeyInputTimer( UINT idEvent, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
{
InputTimer<false>();
InputTimer<true>();
}
void ScaleScreen(float factor, bool user)
{
if(user) // have to exit maximized mode if the user told us to set a specific window size
{
bool maximized = IsZoomed(MainWindow->getHWnd())==TRUE;
if(maximized) ShowWindow(MainWindow->getHWnd(),SW_NORMAL);
}
if(windowSize == 0)
{
int defw = GetPrivateProfileInt("Video", "Window width", GPU_FRAMEBUFFER_NATIVE_WIDTH, IniName);
int defh = GetPrivateProfileInt("Video", "Window height", GPU_FRAMEBUFFER_NATIVE_HEIGHT * 2, IniName);
// fix for wrong rotation
int w1x = 0;
int h1x = 0;
if (video.layout == 0)
{
w1x = video.rotatedwidthgap();
h1x = video.rotatedheightgap();
}
else
if (video.layout == 1)
{
w1x = video.rotatedwidthgap() * 2;
h1x = video.rotatedheightgap() / 2;
}
else
if (video.layout == 2)
{
w1x = video.rotatedwidthgap();
h1x = video.rotatedheightgap() / 2;
}
if((defw > defh) != (w1x > h1x))
{
int temp = defw;
defw = defh;
defh = temp;
}
// fix for wrong gap
//correct aspect ratio if that option's been turned on
if(ForceRatio)
{
if(defh*w1x < h1x*defw)
defh = defw*h1x/w1x;
else if(defw*h1x < w1x*defh)
defw = defh*w1x/h1x;
}
MainWindow->setClientSize(defw, defh);
}
else
{
if(factor==kScale1point5x)
factor = 1.5f;
else if(factor==kScale2point5x)
factor = 2.5f;
//don't incorporate prescale into these calculations
factor /= video.prescaleHD;
if (video.layout == 0)
MainWindow->setClientSize((int)(video.rotatedwidthgap() * factor), (int)(video.rotatedheightgap() * factor));
else
if (video.layout == 1)
MainWindow->setClientSize((int)(video.rotatedwidthgap() * factor * 2), (int)(video.rotatedheightgap() * factor / 2));
else
if (video.layout == 2)
MainWindow->setClientSize((int)(video.rotatedwidthgap() * factor), (int)(video.rotatedheightgap() * factor / 2));
}
}
void SetMinWindowSize()
{
if(ForceRatio)
MainWindow->setMinSize(video.rotatedwidth(), video.rotatedheight());
else
MainWindow->setMinSize(video.rotatedwidthgap(), video.rotatedheightgap());
}
static void GetNdsScreenRect(RECT* r)
{
RECT zero;
SetRect(&zero,0,0,0,0);
if(zero == MainScreenRect) *r = SubScreenRect;
else if(zero == SubScreenRect || video.layout == 2) *r = MainScreenRect;
else
{
RECT* dstRects [2] = {&MainScreenRect, &SubScreenRect};
int left = min(dstRects[0]->left,dstRects[1]->left);
int top = min(dstRects[0]->top,dstRects[1]->top);
int right = max(dstRects[0]->right,dstRects[1]->right);
int bottom = max(dstRects[0]->bottom,dstRects[1]->bottom);
SetRect(r,left,top,right,bottom);
}
}
void UnscaleScreenCoords(s32& x, s32& y)
{
HWND hwnd = MainWindow->getHWnd();
int defwidth = video.width;
int defheight = video.height;
POINT pt;
pt.x = x; pt.y = y;
ClientToScreen(hwnd,&pt);
x = pt.x; y = pt.y;
RECT r;
GetNdsScreenRect(&r);
int winwidth = (r.right-r.left), winheight = (r.bottom-r.top);
x -= r.left;
y -= r.top;
if(winwidth == 0 || winheight == 0)
{
x = 0;
y = 0;
return;
}
if (video.layout == 0)
{
defheight += video.scaledscreengap();
// translate from scaling (screen resolution to 256x384 or 512x192)
switch (video.rotation)
{
case 0:
case 180:
x = (x*defwidth) / winwidth;
y = (y*defheight) / winheight;
break ;
case 90:
case 270:
x = (x*defheight) / winwidth;
y = (y*defwidth) / winheight;
break ;
}
}
else
if (video.layout == 1)
{
//INFO("----- coords x = %i, y = %i\n", x, y);
x = (x*defwidth) / winwidth * 2;
y = (y*defheight) / winheight / 2;
}
else
if (video.layout == 2)
{
//INFO("----- coords x = %i, y = %i\n", x, y);
x = (x*defwidth) / winwidth;
y = (y*defheight) / winheight / 2;
}
x = video.dividebyratio(x);
y = video.dividebyratio(y);
}
// input x,y should be windows client-space coords already at 1x scaling.
// output is in pixels relative to the top-left of the chosen screen.
// (-1 == top screen, 1 == bottom screen, 0 == absolute vertically aligned)
// the gap between screens (if any) is subtracted away from the output y.
void ToDSScreenRelativeCoords(s32& x, s32& y, int whichScreen)
{
s32 tx=x, ty=y;
if (video.layout == 0)
{
int gapSize = video.dividebyratio(video.scaledscreengap());
// first deal with rotation
switch(video.rotation)
{
case 90:
x = ty;
y = (383+gapSize)-tx;
break;
case 180:
x = 255-tx;
y = (383+gapSize)-ty;
break;
case 270:
x = 255-ty;
y = tx;
break;
}
// then deal with screen gap
if(y > 191 + gapSize)
y -= gapSize;
else if(y > 191 + gapSize/2)
y = 192;
else if(y > 191)
y = 191;
}
// finally, make it relative to the correct screen
const bool isMainGPUFirst = (GPU->GetDisplayInfo().engineID[NDSDisplayID_Main] == GPUEngineID_Main);
if (video.layout == 0 || video.layout == 2)
{
if(whichScreen)
{
bool topOnTop = (video.swap == 0) || (video.swap == 2 && isMainGPUFirst) || (video.swap == 3 && !isMainGPUFirst);
bool bottom = (whichScreen > 0);
if(topOnTop)
y += bottom ? -GPU_FRAMEBUFFER_NATIVE_HEIGHT : 0;
else
y += (y < GPU_FRAMEBUFFER_NATIVE_HEIGHT) ? (bottom ? 0 : GPU_FRAMEBUFFER_NATIVE_HEIGHT) : (bottom ? 0 : -GPU_FRAMEBUFFER_NATIVE_HEIGHT);
}
}
else if (video.layout == 1) // side-by-side
{
if(whichScreen)
{
bool topOnTop = (video.swap == 0) || (video.swap == 2 && isMainGPUFirst) || (video.swap == 3 && !isMainGPUFirst);
bool bottom = (whichScreen > 0);
if(topOnTop)
x += bottom ? -GPU_FRAMEBUFFER_NATIVE_WIDTH : 0;
else
x += (x < GPU_FRAMEBUFFER_NATIVE_WIDTH) ? (bottom ? 0 : GPU_FRAMEBUFFER_NATIVE_WIDTH) : (bottom ? 0 : -GPU_FRAMEBUFFER_NATIVE_WIDTH);
}
else
{
if(x >= GPU_FRAMEBUFFER_NATIVE_WIDTH)
{
x -= GPU_FRAMEBUFFER_NATIVE_WIDTH;
y += GPU_FRAMEBUFFER_NATIVE_HEIGHT;
}
else if(x < 0)
{
x += GPU_FRAMEBUFFER_NATIVE_WIDTH;
y -= GPU_FRAMEBUFFER_NATIVE_HEIGHT;
}
}
}
}
// END Rotation definitions
//-----window style handling----
const u32 DISPMETHOD_DDRAW_HW = 1;
const u32 DISPMETHOD_DDRAW_SW = 2;
const u32 DISPMETHOD_OPENGL = 3;
const u32 DWS_NORMAL = 0;
const u32 DWS_ALWAYSONTOP = 1;
const u32 DWS_LOCKDOWN = 2;
const u32 DWS_FULLSCREEN = 4;
const u32 DWS_VSYNC = 8;
const u32 DWS_DDRAW_SW = 16;
const u32 DWS_DDRAW_HW = 32;
const u32 DWS_OPENGL = 64;
const u32 DWS_DISPMETHODS = (DWS_DDRAW_SW|DWS_DDRAW_HW|DWS_OPENGL);
const u32 DWS_FILTER = 128;
static u32 currWindowStyle = DWS_NORMAL;
void SetStyle(u32 dws);
static u32 GetStyle() { return currWindowStyle; }
static void ToggleFullscreen()
{
u32 style = GetStyle();
style ^= DWS_FULLSCREEN;
SetStyle(style);
if(style&DWS_FULLSCREEN)
ShowWindow(MainWindow->getHWnd(),SW_MAXIMIZE);
else ShowWindow(MainWindow->getHWnd(),SW_NORMAL);
}
//---------
static HMENU GetMenuItemParent(UINT itemId, HMENU hMenu = mainMenu)
{
MENUITEMINFO moo = {sizeof(MENUITEMINFO)};
if(!GetMenuItemInfo(hMenu, itemId, FALSE, &moo))
return NULL;
int nItems = GetMenuItemCount(hMenu);
for(int i = 0; i < nItems; i++)
{
MENUITEMINFO mii = {sizeof(MENUITEMINFO), MIIM_SUBMENU | MIIM_ID};
GetMenuItemInfo(hMenu, i, TRUE, &mii);
if(mii.wID == itemId)
return hMenu;
if(mii.hSubMenu)
if(HMENU innerResult = GetMenuItemParent(itemId, mii.hSubMenu))
return innerResult;
}
return NULL;
}
static void PopulateLuaSubmenu()
{
static HMENU luasubmenu = GetMenuItemParent(IDC_NEW_LUA_SCRIPT);
static int luasubmenuOriginalSize = GetMenuItemCount(luasubmenu);
// delete any previously-dynamically-added menu items
int i = luasubmenuOriginalSize;
while(GetMenuItemCount(luasubmenu) > i)
DeleteMenu(luasubmenu, i, MF_BYPOSITION);
// add menu items for currently-open scripts
char Str_Tmp [1024];
int Flags = MF_BYPOSITION | MF_STRING;
if(!LuaScriptHWnds.empty())
{
InsertMenu(luasubmenu, i++, MF_SEPARATOR, NULL, NULL);
for(unsigned int j = 0; j < LuaScriptHWnds.size(); j++)
{
GetWindowText(LuaScriptHWnds[j], Str_Tmp, 1024);
InsertMenu(luasubmenu, i++, MF_BYPOSITION | MF_STRING, IDC_LUASCRIPT_RESERVE_START+j, Str_Tmp);
}
}
// add menu items for recently-opened-but-not-currently-open scripts
int dividerI = i;
for(unsigned int j = 0; j < MAX_RECENT_SCRIPTS; j++)
{
const char* pathPtr = Recent_Scripts[j];
if(!*pathPtr)
continue;
HWND IsScriptFileOpen(const char* Path);
if(IsScriptFileOpen(pathPtr))
continue;
// only show some of the path
const char* pathPtrSearch;
int slashesLeft = 2;
for(pathPtrSearch = pathPtr + strlen(pathPtr) - 1;
pathPtrSearch != pathPtr && slashesLeft >= 0;
pathPtrSearch--)
{
char c = *pathPtrSearch;
if(c == '\\' || c == '/')
slashesLeft--;
}
if(slashesLeft < 0)
pathPtr = pathPtrSearch + 2;
strcpy(Str_Tmp, pathPtr);
if(i == dividerI)
InsertMenu(luasubmenu, i++, MF_SEPARATOR, NULL, NULL);
InsertMenu(luasubmenu, i++, MF_BYPOSITION | MF_STRING, IDD_LUARECENT_RESERVE_START+j, Str_Tmp);
}