-
-
Notifications
You must be signed in to change notification settings - Fork 102
Expand file tree
/
Copy pathmain.cpp
More file actions
1440 lines (1240 loc) · 41.7 KB
/
main.cpp
File metadata and controls
1440 lines (1240 loc) · 41.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
// main.cpp: initialisation & main loop
#include "engine.h"
#include "controller.h"
#include <signal.h>
#ifdef SDL_VIDEO_DRIVER_X11
#include "SDL_syswm.h"
#endif
void getsdlversion_compiled()
{
SDL_version compiled;
SDL_VERSION(&compiled);
defformatstring(str, "%u.%u.%u", compiled.major, compiled.minor, compiled.patch);
result(str);
}
COMMAND(0, getsdlversion_compiled, "");
void getsdlversion_linked()
{
SDL_version linked;
SDL_GetVersion(&linked);
defformatstring(str, "%u.%u.%u", linked.major, linked.minor, linked.patch);
result(str);
}
COMMAND(0, getsdlversion_linked, "");
#ifndef STANDALONE
#include "SDL_image.h"
void getsdlimgversion_compiled()
{
SDL_version compiled;
SDL_IMAGE_VERSION(&compiled);
defformatstring(str, "%u.%u.%u", compiled.major, compiled.minor, compiled.patch);
result(str);
}
COMMAND(0, getsdlimgversion_compiled, "");
void getsdlimgversion_linked()
{
SDL_version linked;
const SDL_version *version = IMG_Linked_Version();
SDL_VERSION(&linked);
defformatstring(str, "%u.%u.%u", version->major, version->minor, version->patch);
result(str);
}
COMMAND(0, getsdlimgversion_linked, "");
#endif // STANDALONE
string caption = "";
void setcaption(const char *text, const char *text2)
{
static string prevtext = "", prevtext2 = "";
if(strcmp(text, prevtext) || strcmp(text2, prevtext2))
{
copystring(prevtext, text);
copystring(prevtext2, text2);
formatstring(caption, "%s%s%s%s%s", getverstr(), text[0] ? ": " : "", text, text2[0] ? " - " : "", text2);
if(screen) SDL_SetWindowTitle(screen, caption);
}
}
#ifdef DEBUG_UTILS
void writetofile(const char *filename, const char *buf)
{
stream *f = openutf8file(filename, "w");
if(!f)
{
intret(0);
return;
}
f->write(buf, strlen(buf));
delete f;
intret(1);
}
COMMAND(0, writetofile, "ss");
#endif
int keyrepeatmask = 0, textinputmask = 0;
Uint32 textinputtime = 0;
VAR(0, textinputfilter, 0, 5, 1000);
void keyrepeat(bool on, int mask)
{
if(on) keyrepeatmask |= mask;
else keyrepeatmask &= ~mask;
}
void textinput(bool on, int mask)
{
if(on)
{
if(!textinputmask)
{
SDL_StartTextInput();
textinputtime = getclockticks();
}
textinputmask |= mask;
}
else if(textinputmask)
{
textinputmask &= ~mask;
if(!textinputmask) SDL_StopTextInput();
}
}
#ifdef WIN32
// SDL_WarpMouseInWindow behaves erratically on Windows, so force relative mouse instead.
VARN(IDF_READONLY, relativemouse, userelativemouse, 1, 1, 0);
#else
VARN(IDF_PERSIST, relativemouse, userelativemouse, 0, 1, 1);
#endif
bool windowfocus = true, shouldgrab = false, grabinput = false, canrelativemouse = true, relativemouse = false;
#ifdef SDL_VIDEO_DRIVER_X11
VAR(0, sdl_xgrab_bug, 0, 0, 1);
#endif
void inputgrab(bool on, bool delay = false)
{
#ifdef SDL_VIDEO_DRIVER_X11
bool wasrelativemouse = relativemouse;
#endif
if(on)
{
SDL_ShowCursor(SDL_FALSE);
if(canrelativemouse && userelativemouse)
{
if(SDL_SetRelativeMouseMode(SDL_TRUE) >= 0)
{
SDL_SetWindowGrab(screen, SDL_TRUE);
relativemouse = true;
}
else
{
SDL_SetWindowGrab(screen, SDL_FALSE);
canrelativemouse = false;
relativemouse = false;
}
}
}
else
{
SDL_ShowCursor(SDL_TRUE);
if(relativemouse)
{
SDL_SetWindowGrab(screen, SDL_FALSE);
SDL_SetRelativeMouseMode(SDL_FALSE);
relativemouse = false;
}
}
shouldgrab = false;
#ifdef SDL_VIDEO_DRIVER_X11
if((relativemouse || wasrelativemouse) && sdl_xgrab_bug)
{
// Workaround for buggy SDL X11 pointer grabbing
union { SDL_SysWMinfo info; uchar buf[sizeof(SDL_SysWMinfo) + 128]; };
SDL_GetVersion(&info.version);
if(SDL_GetWindowWMInfo(screen, &info) && info.subsystem == SDL_SYSWM_X11)
{
if(relativemouse)
{
uint mask = ButtonPressMask | ButtonReleaseMask | PointerMotionMask | FocusChangeMask;
XGrabPointer(info.info.x11.display, info.info.x11.window, True, mask, GrabModeAsync, GrabModeAsync, info.info.x11.window, None, CurrentTime);
}
else XUngrabPointer(info.info.x11.display, CurrentTime);
}
}
#endif
}
extern void cleargamma();
bool engineready = false, inbetweenframes = false, renderedframe = false;
void cleanup()
{
engineready = false;
cleanupserver();
SDL_ShowCursor(SDL_TRUE);
SDL_SetRelativeMouseMode(SDL_FALSE);
if(screen) SDL_SetWindowGrab(screen, SDL_FALSE);
cleargamma();
freeocta(worldroot);
UI::cleanup();
fx::cleanup();
cleanupwind();
extern void clear_command(); clear_command();
extern void clear_binds(); clear_binds();
extern void clear_models(); clear_models();
stopsound();
SDL_Quit();
}
void quit() // normal exit
{
inbetweenframes = engineready = false;
initing = INIT_QUIT;
writecfg("init.cfg", IDF_INIT);
writeservercfg();
if(!noconfigfile) writecfg("config.cfg", IDF_PERSIST);
writehistory();
client::writecfg();
abortconnect();
disconnect(true);
cleanup();
exit(EXIT_SUCCESS);
}
volatile int errors = 0;
void fatal(const char *s, ...) // failure exit
{
engineready = false;
if(!errors) initing = INIT_QUIT;
if(++errors <= 2) // print up to one extra recursive error
{
defvformatbigstring(msg, s, s);
if(logfile) logoutf("%s", msg);
#ifndef WIN32
fprintf(stderr, "Fatal error: %s\n", msg);
#endif
if(errors <= 1) // avoid recursion
{
if(SDL_WasInit(SDL_INIT_VIDEO))
{
SDL_ShowCursor(SDL_TRUE);
SDL_SetRelativeMouseMode(SDL_FALSE);
if(screen) SDL_SetWindowGrab(screen, SDL_FALSE);
cleargamma();
}
SDL_Quit();
defformatstring(cap, "%s: Fatal error", versionfname);
#ifdef WIN32 // bug: https://github.com/libsdl-org/SDL/issues/1380
MessageBox(NULL, msg, cap, MB_OK|MB_SYSTEMMODAL);
#else
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, cap, msg, screen);
#endif
}
}
exit(EXIT_FAILURE);
}
int screenw = 0, screenh = 0;
VARR(desktopw, 0);
VARR(desktoph, 0);
VARR(refreshrate, 0);
SDL_Window *screen = NULL;
SDL_GLContext glcontext = NULL;
SDL_DisplayMode display;
int initing = NOT_INITING;
bool initwarning(const char *desc, int level, int type)
{
if(initing < level)
{
addchange(desc, type);
return true;
}
return false;
}
VAR(IDF_PERSIST, compresslevel, 0, 9, 9);
VAR(IDF_PERSIST, imageformat, IFMT_NONE+1, IFMT_PNG, IFMT_MAX-1);
void screenshot(char *sname)
{
ImageData image(renderw, renderh, 3);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glReadPixels(0, 0, renderw, renderh, GL_RGB, GL_UNSIGNED_BYTE, image.data);
string fname;
if(sname && *sname) copystring(fname, sname);
else formatstring(fname, "screenshots/%s", *filetimeformat ? gettime(filetimelocal ? currenttime : clocktime, filetimeformat) : (*mapname ? mapname : "screen"));
saveimage(fname, image, imageformat, compresslevel, true);
}
ICOMMAND(0, screenshot, "s", (char *s), if(!(identflags&IDF_MAP)) screenshot(s));
ICOMMAND(IDF_NOECHO, quit, "", (void), if(!(identflags&IDF_MAP)) quit());
#define SCR_MINW 320
#define SCR_MINH 200
#define SCR_MAXW 10000
#define SCR_MAXH 10000
#define SCR_DEFAULTW 1024
#define SCR_DEFAULTH 768
VARFN(IDF_INIT, screenw, scr_w, SCR_MINW, -1, SCR_MAXW, initwarning("screen resolution"));
VARFN(IDF_INIT, screenh, scr_h, SCR_MINH, -1, SCR_MAXH, initwarning("screen resolution"));
bool wantdisplaysetup = false;
void resetfullscreen();
int getdisplaymode()
{
int index = SDL_GetWindowDisplayIndex(screen);
if(SDL_GetCurrentDisplayMode(index, &display) < 0) fatal("Failed querying monitor %d display mode: %s", index, SDL_GetError());
desktopw = display.w;
desktoph = display.h;
refreshrate = display.refresh_rate;
return index;
}
void setupdisplay(bool dogl = true, bool msg = true)
{
SDL_GetWindowSize(screen, &screenw, &screenh);
SDL_GL_GetDrawableSize(screen, &renderw, &renderh);
int index = getdisplaymode();
if(windowfocus && SDL_GetWindowFlags(screen)&SDL_WINDOW_FULLSCREEN && (display.w != screenw || display.h != screenh))
{
scr_w = clamp(display.w, SCR_MINW, SCR_MAXW);
scr_h = clamp(display.h, SCR_MINH, SCR_MAXH);
resetfullscreen();
SDL_GetWindowSize(screen, &screenw, &screenh);
SDL_GL_GetDrawableSize(screen, &renderw, &renderh);
}
scr_w = screenw;
scr_h = screenh;
hudw = renderw;
hudh = renderh;
if(dogl) gl_resize();
if(msg) conoutf(colourwhite, "Display [%d]: %dx%d [%d Hz] %s: %dx%d [%dx%d]", index, display.w, display.h, display.refresh_rate, SDL_GetWindowFlags(screen)&SDL_WINDOW_FULLSCREEN ? (fullscreendesktop ? "Fullscreen" : "Exclusive") : "Windowed", screenw, screenh, renderw, renderh);
wantdisplaysetup = false;
triggereventcallbacks(CMD_EVENT_SETUPDISPLAY);
}
void setfullscreen(bool enable)
{
if(!screen) return;
SDL_SetWindowFullscreen(screen, enable ? (fullscreendesktop ? SDL_WINDOW_FULLSCREEN_DESKTOP : SDL_WINDOW_FULLSCREEN) : 0);
if(!enable)
{
SDL_SetWindowSize(screen, scr_w, scr_h);
SDL_SetWindowPosition(screen, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
}
wantdisplaysetup = true;
}
VARF(IDF_INIT, fullscreen, 0, 1, 1, if(!(identflags&IDF_MAP)) setfullscreen(fullscreen!=0));
void resetfullscreen()
{
setfullscreen(false);
setfullscreen(true);
}
VARF(IDF_INIT, fullscreendesktop, 0, 1, 1, if(!(identflags&IDF_MAP) && fullscreen) resetfullscreen());
void screenres(int w, int h)
{
scr_w = clamp(w, SCR_MINW, SCR_MAXW);
scr_h = clamp(h, SCR_MINH, SCR_MAXH);
if(screen)
{
if(fullscreendesktop)
{
getdisplaymode();
scr_w = min(scr_w, desktopw);
scr_h = min(scr_h, desktoph);
}
if(SDL_GetWindowFlags(screen)&SDL_WINDOW_FULLSCREEN) resetfullscreen();
else
{
SDL_SetWindowSize(screen, scr_w, scr_h);
SDL_SetWindowPosition(screen, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
}
wantdisplaysetup = true;
}
else initwarning("screen resolution");
}
ICOMMAND(0, screenres, "ii", (int *w, int *h), screenres(*w, *h));
static void setgamma(int val)
{
if(screen && SDL_SetWindowBrightness(screen, val/100.0f) < 0) conoutf(colourred, "Could not set gamma: %s", SDL_GetError());
}
ICOMMAND(0, enumresolutions, "", (),
{
if(!screen) return;
int index = SDL_GetWindowDisplayIndex(screen);
int modes = SDL_GetNumDisplayModes(index);
if(modes <= 0) return;
vector<int> resolutions;
// Fill list with unique resolutions
loopi(modes)
{
SDL_DisplayMode mode;
if(SDL_GetDisplayMode(index, i, &mode)) continue;
// Pack resolution into a single int
int res = mode.w | (mode.h << 16);
// Add to list if not already present
if(resolutions.find(res) < 0) resolutions.add(res);
}
// Make a list of resolutions
string reslist;
reslist[0] = 0;
loopvrev(resolutions)
{
int res = resolutions[i];
int w = res & 0xFFFF;
int h = res >> 16;
if(reslist[0]) concatstring(reslist, " ");
concatstring(reslist, intstr(w));
concatstring(reslist, "x");
concatstring(reslist, intstr(h));
}
result(reslist);
});
static int curgamma = 100;
VARFN(IDF_PERSIST, gamma, reqgamma, 30, 100, 300,
{
if(initing || reqgamma == curgamma) return;
curgamma = reqgamma;
setgamma(curgamma);
});
void restoregamma()
{
if(initing || reqgamma == 100) return;
curgamma = reqgamma;
setgamma(curgamma);
}
void cleargamma()
{
if(curgamma != 100 && screen) SDL_SetWindowBrightness(screen, 1.0f);
}
VARR(hasvsynctear, -1);
int curvsync = -1;
void restorevsync()
{
if(initing || !glcontext) return;
extern int vsync, vsynctear;
int err = 0;
if(hasvsynctear < 0 || (vsync && vsynctear))
{
err = SDL_GL_SetSwapInterval(-1);
hasvsynctear = err ? 0 : 1;
}
if(err || !vsynctear || !vsync)
{
err = SDL_GL_SetSwapInterval(vsync);
}
if(!err) curvsync = vsync;
}
VARF(IDF_PERSIST, vsync, 0, 0, 1, restorevsync());
VARF(IDF_PERSIST, vsynctear, 0, 1, 1, { if(vsync) restorevsync(); });
void setupscreen(bool dogl = true)
{
if(glcontext)
{
SDL_GL_DeleteContext(glcontext);
glcontext = NULL;
}
if(screen)
{
SDL_DestroyWindow(screen);
screen = NULL;
}
curvsync = -1;
SDL_Rect desktop;
if(SDL_GetDisplayBounds(0, &desktop) < 0) fatal("Failed querying desktop bounds: %s", SDL_GetError());
desktopw = desktop.w;
desktoph = desktop.h;
if(scr_h < 0) scr_h = fullscreen ? desktoph : SCR_DEFAULTH;
if(scr_w < 0) scr_w = (scr_h*desktopw)/desktoph;
scr_w = clamp(scr_w, SCR_MINW, SCR_MAXW);
scr_h = clamp(scr_h, SCR_MINH, SCR_MAXH);
if(fullscreendesktop)
{
scr_w = min(scr_w, desktopw);
scr_h = min(scr_h, desktoph);
}
int winx = SDL_WINDOWPOS_UNDEFINED, winy = SDL_WINDOWPOS_UNDEFINED, winw = scr_w, winh = scr_h,
flags = SDL_WINDOW_OPENGL|SDL_WINDOW_SHOWN|SDL_WINDOW_INPUT_FOCUS|SDL_WINDOW_MOUSE_FOCUS|SDL_WINDOW_RESIZABLE;//|SDL_WINDOW_ALLOW_HIGHDPI;
if(fullscreen)
{
if(fullscreendesktop)
{
winw = desktopw;
winh = desktoph;
flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
}
else flags |= SDL_WINDOW_FULLSCREEN;
}
SDL_GL_ResetAttributes();
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
#ifndef WIN32
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
#endif
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
screen = SDL_CreateWindow(caption, winx, winy, winw, winh, flags);
if(!screen) fatal("Failed to create OpenGL window: %s", SDL_GetError());
SDL_Surface *s = loadsurface("textures/icon");
if(s)
{
SDL_SetWindowIcon(screen, s);
SDL_FreeSurface(s);
}
SDL_SetWindowMinimumSize(screen, SCR_MINW, SCR_MINH);
SDL_SetWindowMaximumSize(screen, SCR_MAXW, SCR_MAXH);
static const int glversions[] = { 40, 33, 32, 31, 30, 20 };
loopi(sizeof(glversions)/sizeof(glversions[0]))
{
glcompat = glversions[i] <= 30 ? 1 : 0;
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, glversions[i] / 10);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, glversions[i] % 10);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, glversions[i] >= 32 ? SDL_GL_CONTEXT_PROFILE_CORE : 0);
glcontext = SDL_GL_CreateContext(screen);
if(glcontext) break;
}
if(!glcontext) fatal("Failed to create OpenGL context: %s", SDL_GetError());
setupdisplay(dogl, engineready);
}
void resetgl()
{
clearchanges(CHANGE_GFX|CHANGE_SHADERS);
progress(0, "Resetting OpenGL..");
bool oldengineready = engineready;
engineready = false;
UI::cleangl();
game::cleangl();
cleanupva();
cleanupparticles();
cleanupstains();
cleanupsky();
cleanupmodels();
cleanupprefabs();
cleanuptextures();
cleanupblendmap();
cleanuplights();
halosurf.destroy();
hazesurf.destroy();
cleanupshaders();
cleanupgl();
setupscreen(false);
inputgrab(grabinput);
gl_init();
inbetweenframes = false;
if(!reloadtexture(notexturetex) || !reloadtexture(blanktex) || !reloadtexture(logotex))
fatal("Failed to reload core textures");
reloadfonts();
inbetweenframes = true;
progress(0, "Initializing..");
restoregamma();
restorevsync();
initgbuffer();
reloadshaders();
reloadtextures();
allchanged(true);
engineready = oldengineready;
if(engineready) game::preload();
}
ICOMMAND(IDF_NOECHO, resetgl, "", (void), if(!(identflags&IDF_MAP)) resetgl());
bool warping = false, minimized = false;
VAR(IDF_PERSIST, renderunfocused, 0, 0, 1);
static queue<SDL_Event, 32> events;
static inline bool filterevent(const SDL_Event &event)
{
switch(event.type)
{
case SDL_MOUSEMOTION:
if(grabinput && !relativemouse && !(SDL_GetWindowFlags(screen) & SDL_WINDOW_FULLSCREEN))
{
if(warping && event.motion.x == screenw / 2 && event.motion.y == screenh / 2)
return false; // ignore any motion events generated by SDL_WarpMouse
}
break;
}
return true;
}
template <int SIZE> static inline bool pumpevents(queue<SDL_Event, SIZE> &events)
{
while(events.empty())
{
SDL_PumpEvents();
databuf<SDL_Event> buf = events.reserve(events.capacity());
int n = SDL_PeepEvents(buf.getbuf(), buf.remaining(), SDL_GETEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT);
if(n <= 0) return false;
loopi(n) if(filterevent(buf.buf[i])) buf.put(buf.buf[i]);
events.addbuf(buf);
}
return true;
}
static int interceptkeysym = 0;
static int interceptevents(void *data, SDL_Event *event)
{
switch(event->type)
{
case SDL_KEYDOWN:
if(event->key.keysym.sym == interceptkeysym)
{
interceptkeysym = -interceptkeysym;
return 0;
}
break;
}
return 1;
}
static void clearinterceptkey()
{
SDL_DelEventWatch(interceptevents, NULL);
interceptkeysym = 0;
}
bool interceptkey(int sym)
{
if(!interceptkeysym)
{
interceptkeysym = sym;
SDL_FilterEvents(interceptevents, NULL);
if(interceptkeysym < 0)
{
interceptkeysym = 0;
return true;
}
SDL_AddEventWatch(interceptevents, NULL);
}
else if(abs(interceptkeysym) != sym) interceptkeysym = sym;
SDL_PumpEvents();
if(interceptkeysym < 0)
{
clearinterceptkey();
interceptkeysym = sym;
SDL_FilterEvents(interceptevents, NULL);
interceptkeysym = 0;
return true;
}
return false;
}
static void ignoremousemotion()
{
SDL_PumpEvents();
SDL_FlushEvent(SDL_MOUSEMOTION);
}
void resetcursor(bool warp, bool reset)
{
if(warp && grabinput && !relativemouse && !(SDL_GetWindowFlags(screen) & SDL_WINDOW_FULLSCREEN))
{
SDL_WarpMouseInWindow(screen, screenw/2, screenh/2);
warping = true;
}
if(reset) cursorx = cursory = 0.5f;
}
static void checkmousemotion(int &dx, int &dy)
{
while(pumpevents(events))
{
SDL_Event &event = events.removing();
if(event.type != SDL_MOUSEMOTION) return;
dx += event.motion.xrel;
dy += event.motion.yrel;
events.remove();
}
}
void checkinput()
{
if(interceptkeysym) clearinterceptkey();
//int lasttype = 0, lastbut = 0;
bool mousemoved = false, shouldwarp = false;
int focused = 0;
while(pumpevents(events))
{
SDL_Event &event = events.remove();
if(focused && event.type!=SDL_WINDOWEVENT) { if(grabinput != (focused>0)) inputgrab(grabinput = focused>0, shouldgrab); focused = 0; }
switch(event.type)
{
case SDL_QUIT:
quit();
return;
case SDL_TEXTINPUT:
if(textinputmask && int(event.text.timestamp-textinputtime) >= textinputfilter)
{
uchar buf[SDL_TEXTINPUTEVENT_TEXT_SIZE+1];
size_t len = decodeutf8(buf, sizeof(buf)-1, (const uchar *)event.text.text, strlen(event.text.text));
if(len > 0) { buf[len] = '\0'; processtextinput((const char *)buf, len); }
}
break;
case SDL_KEYDOWN:
case SDL_KEYUP:
if(keyrepeatmask || !event.key.repeat)
{
controller::lastinputwassiapi = false;
processkey(event.key.keysym.sym, event.key.state==SDL_PRESSED);
}
break;
case SDL_WINDOWEVENT:
switch(event.window.event)
{
case SDL_WINDOWEVENT_CLOSE:
quit();
break;
case SDL_WINDOWEVENT_FOCUS_GAINED:
windowfocus = shouldgrab = true;
break;
case SDL_WINDOWEVENT_ENTER:
shouldgrab = false;
focused = 1;
break;
case SDL_WINDOWEVENT_FOCUS_LOST: windowfocus = false; // fall through
case SDL_WINDOWEVENT_LEAVE:
shouldgrab = false;
focused = -1;
break;
case SDL_WINDOWEVENT_MINIMIZED:
minimized = true;
break;
case SDL_WINDOWEVENT_MAXIMIZED:
case SDL_WINDOWEVENT_RESTORED:
minimized = false;
break;
case SDL_WINDOWEVENT_RESIZED:
break;
case SDL_WINDOWEVENT_SIZE_CHANGED:
wantdisplaysetup = true;
break;
}
break;
case SDL_MOUSEMOTION:
if(grabinput)
{
int dx = event.motion.xrel, dy = event.motion.yrel;
checkmousemotion(dx, dy);
shouldwarp = game::mousemove(dx, dy, event.motion.x, event.motion.y, screenw, screenh); // whether game controls engine cursor
mousemoved = true;
}
else if(shouldgrab) inputgrab(grabinput = true);
break;
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
{
//if(lasttype==event.type && lastbut==event.button.button) break; // why?? get event twice without it
//switch(event.button.button)
//{
// case SDL_BUTTON_LEFT: processkey(-1, event.button.state==SDL_PRESSED); break;
// case SDL_BUTTON_MIDDLE: processkey(-2, event.button.state==SDL_PRESSED); break;
// case SDL_BUTTON_RIGHT: processkey(-3, event.button.state==SDL_PRESSED); break;
// case SDL_BUTTON_X1: processkey(-6, event.button.state==SDL_PRESSED); break;
// case SDL_BUTTON_X2: processkey(-7, event.button.state==SDL_PRESSED); break;
//}
//lasttype = event.type;
//lastbut = event.button.button;
int button = event.button.button;
if(button >= 6) button += 4; // skip mousewheel X (-4,-5) & Y (-8, 9)
else if(button >= 4) button += 2; // skip mousewheel X (-4,-5)
controller::lastinputwassiapi = false;
processkey(-button, event.button.state==SDL_PRESSED);
break;
}
case SDL_MOUSEWHEEL:
controller::lastinputwassiapi = false;
if(event.wheel.y > 0) { processkey(-4, true); processkey(-4, false); }
else if(event.wheel.y < 0) { processkey(-5, true); processkey(-5, false); }
else if(event.wheel.x > 0) { processkey(-8, true); processkey(-8, false); }
else if(event.wheel.x < 0) { processkey(-9, true); processkey(-9, false); }
break;
}
}
if(focused) { if(grabinput != (focused>0)) inputgrab(grabinput = focused>0, shouldgrab); focused = 0; }
if(mousemoved)
{
warping = false;
if(grabinput && shouldwarp) resetcursor(true, false);
}
controller::update_from_controller();
}
void swapbuffers(bool overlay)
{
gle::disable();
SDL_GL_SwapWindow(screen);
}
int frameloops = 0;
VAR(IDF_PERSIST, menufps, -1, -1, VAR_MAX);
FVAR(IDF_PERSIST, menufpsrefresh, 0.1f, 1, 100);
VAR(IDF_PERSIST, menufpsrefreshoffset, 0, 1, VAR_MAX);
VAR(IDF_PERSIST, maxfps, -1, -1, VAR_MAX);
FVAR(IDF_PERSIST, maxfpsrefresh, 0.1f, 1, 100);
VAR(IDF_PERSIST, maxfpsrefreshoffset, 0, 1, VAR_MAX);
#define GETFPS(a) (a >= 0 ? a : int((refreshrate*a##refresh)+a##refreshoffset))
void limitfps(int &millis, int curmillis)
{
int curmax = GETFPS(maxfps), curmenu = GETFPS(menufps),
limit = (hasnoview() || (minimized && !renderunfocused)) && curmenu ? (curmax > 0 ? min(curmax, curmenu) : curmenu) : curmax;
if(!limit || (limit >= refreshrate && vsync)) return;
static int fpserror = 0;
int delay = 1000/limit - (millis-curmillis);
if(delay < 0) fpserror = 0;
else
{
fpserror += 1000%limit;
if(fpserror >= limit)
{
++delay;
fpserror -= limit;
}
if(delay > 0)
{
SDL_Delay(delay);
millis += delay;
}
}
}
#ifdef WIN32
// Force Optimus setups to use the NVIDIA GPU
extern "C"
{
#ifdef __GNUC__
__attribute__((dllexport))
#else
__declspec(dllexport)
#endif
DWORD NvOptimusEnablement = 1;
#ifdef __GNUC__
__attribute__((dllexport))
#else
__declspec(dllexport)
#endif
DWORD AmdPowerXpressRequestHighPerformance = 1;
}
#endif
#if defined(WIN32) && !defined(_DEBUG) && !defined(__GNUC__)
void stackdumper(unsigned int type, EXCEPTION_POINTERS *ep)
{
if(!ep) fatal("Unknown type");
EXCEPTION_RECORD *er = ep->ExceptionRecord;
CONTEXT *context = ep->ContextRecord;
bigstring out;
formatstring(out, "%s Win32 Exception: 0x%x [0x%x]\n\n", versionfname, er->ExceptionCode, er->ExceptionCode==EXCEPTION_ACCESS_VIOLATION ? er->ExceptionInformation[1] : -1);
SymInitialize(GetCurrentProcess(), NULL, TRUE);
#ifdef _AMD64_
STACKFRAME64 sf = {{context->Rip, 0, AddrModeFlat}, {}, {context->Rbp, 0, AddrModeFlat}, {context->Rsp, 0, AddrModeFlat}, 0};
while(::StackWalk64(IMAGE_FILE_MACHINE_AMD64, GetCurrentProcess(), GetCurrentThread(), &sf, context, NULL, ::SymFunctionTableAccess, ::SymGetModuleBase, NULL))
{
union { IMAGEHLP_SYMBOL64 sym; char symext[sizeof(IMAGEHLP_SYMBOL64) + sizeof(bigstring)]; };
sym.SizeOfStruct = sizeof(sym);
sym.MaxNameLength = sizeof(symext) - sizeof(sym);
IMAGEHLP_LINE64 line;
line.SizeOfStruct = sizeof(line);
DWORD64 symoff;
DWORD lineoff;
if(SymGetSymFromAddr64(GetCurrentProcess(), sf.AddrPC.Offset, &symoff, &sym) && SymGetLineFromAddr64(GetCurrentProcess(), sf.AddrPC.Offset, &lineoff, &line))
#else
STACKFRAME sf = {{context->Eip, 0, AddrModeFlat}, {}, {context->Ebp, 0, AddrModeFlat}, {context->Esp, 0, AddrModeFlat}, 0};
while(::StackWalk(IMAGE_FILE_MACHINE_I386, GetCurrentProcess(), GetCurrentThread(), &sf, context, NULL, ::SymFunctionTableAccess, ::SymGetModuleBase, NULL))
{
union { IMAGEHLP_SYMBOL sym; char symext[sizeof(IMAGEHLP_SYMBOL) + sizeof(bigstring)]; };
sym.SizeOfStruct = sizeof(sym);
sym.MaxNameLength = sizeof(symext) - sizeof(sym);
IMAGEHLP_LINE line;
line.SizeOfStruct = sizeof(line);
DWORD symoff, lineoff;
if(SymGetSymFromAddr(GetCurrentProcess(), sf.AddrPC.Offset, &symoff, &sym) && SymGetLineFromAddr(GetCurrentProcess(), sf.AddrPC.Offset, &lineoff, &line))
#endif
{
char *del = strrchr(line.FileName, '\\');
concformatstring(out, "%s - %s [%d]\n", sym.Name, del ? del + 1 : line.FileName, line.LineNumber);
}
}
fatal(out);
}
#endif
#define MAXFPSHISTORY 60
int fpspos = 0, fpshistory[MAXFPSHISTORY];
void getfps(int &fps, int &bestdiff, int &worstdiff)
{
int total = fpshistory[MAXFPSHISTORY-1], best = total, worst = total;
loopi(MAXFPSHISTORY-1)
{
int millis = fpshistory[i];
total += millis;
if(millis < best) best = millis;
if(millis > worst) worst = millis;
}
fps = (1000*MAXFPSHISTORY)/total;
bestdiff = 1000/best-fps;
worstdiff = fps-1000/worst;
}
void getfps_(int *raw)
{
int fps, bestdiff, worstdiff;
if(*raw) fps = 1000/fpshistory[(fpspos+MAXFPSHISTORY-1)%MAXFPSHISTORY];
else getfps(fps, bestdiff, worstdiff);
intret(fps);
}
COMMANDN(0, getfps, getfps_, "i");
VARR(curfps, 0);
VARR(bestfps, 0);
VARR(bestfpsdiff, 0);
VARR(worstfps, 0);
VARR(worstfpsdiff, 0);
void resetfps()
{
loopi(MAXFPSHISTORY) fpshistory[i] = 1;
fpspos = 0;
}
void updatefps(int frames, int millis)
{
fpshistory[fpspos++] = max(1, min(1000, millis));
if(fpspos >= MAXFPSHISTORY) fpspos = 0;
int fps, bestdiff, worstdiff;
getfps(fps, bestdiff, worstdiff);
curfps = fps;
bestfps = fps+bestdiff;
bestfpsdiff = bestdiff;
worstfps = fps-worstdiff;
worstfpsdiff = worstdiff;
}
ICOMMANDV(0, engineready, engineready ? 1 : 0);
ICOMMANDV(0, inbetweenframes, inbetweenframes ? 1 : 0);
ICOMMANDV(0, renderedframe, renderedframe ? 1 : 0);
static bool findarg(int argc, char **argv, const char *str)