forked from floft/sprouts
-
Notifications
You must be signed in to change notification settings - Fork 3
/
platform.cpp
1076 lines (995 loc) · 26 KB
/
platform.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
#include "platform.h"
#include <SDL2/SDL.h>
#include <GL/gl.h>
#include "matrix.h"
#include "vector.h"
#include <cwchar>
#include <string>
#include <iostream>
#include <cstdlib>
#include <chrono>
#include <atomic>
#include <thread>
#include <mutex>
#ifndef SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK
#define SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK "SDL_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK"
#endif // SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK
using namespace std;
/**************
*Description:
*Input:
*Output:
**************/
double Display::realtimeTimer()
{
return static_cast<double>(chrono::duration_cast<chrono::nanoseconds>(chrono::system_clock::now().time_since_epoch()).count()) * 1e-9;
}
namespace
{
class RWOpsReader final : public Reader
{
private:
SDL_RWops * rw;
public:
RWOpsReader(SDL_RWops * rw)
: rw(rw)
{
}
virtual uint8_t readByte() override
{
SDL_ClearError(); // for error detection
uint8_t retval;
if(0 == SDL_RWread(rw, &retval, sizeof(retval), 1))
{
const char * str = SDL_GetError();
if(str[0]) // non-empty string : error
throw IOException(str);
throw EOFException();
}
return retval;
}
~RWOpsReader()
{
SDL_RWclose(rw);
}
};
}
static void startSDL();
#ifdef _WIN64
#error implement getResourceReader for Win64
#elif _WIN32
#include <cstring>
#include <cwchar>
#include <windows.h>
static wchar_t * ResourcePrefix = nullptr;
static wstring getExecutablePath();
static void initfn();
static wstring getResourceFileName(wstring resource)
{
initfn();
return wstring(ResourcePrefix) + resource;
}
static wstring getExecutablePath()
{
wchar_t buf[PATH_MAX + 1];
DWORD rv = GetModuleFileNameW(NULL, &buf[0], PATH_MAX + 1);
if(rv >= PATH_MAX + 1)
{
throw runtime_error(string("can't get executable path"));
}
buf[rv] = '\0';
return wstring(&buf[0]);
}
static void initfn()
{
static bool ran = false;
if(ran)
return;
ran = true;
wstring p = getExecutablePath();
size_t pos = p.find_last_of(L"/\\");
if(pos == wstring::npos)
p = L"";
else
p = p.substr(0, pos + 1);
p = p + wstring(L"res/");
ResourcePrefix = new wchar_t[p.size() + 1];
for(size_t i = 0; i < p.size(); i++)
ResourcePrefix[i] = p[i];
ResourcePrefix[p.size()] = L'\0';
}
initializer initializer1([]()
{
initfn();
});
shared_ptr<Reader> getResourceReader(wstring resource)
{
startSDL();
string fname = wstringToString(getResourceFileName(resource));
return make_shared<RWOpsReader>(SDL_RWFromFile(fname.c_str(), "rb"));
}
#elif __ANDROID
#error implement getResourceReader for Android
#elif __APPLE__
#include "TargetConditionals.h"
#if TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR
#error implement getResourceReader for iPhone simulator
#elif TARGET_OS_IPHONE
#error implement getResourceReader for iPhone
#else
#error implement getResourceReader for OS X
#endif
#elif __linux
#include <unistd.h>
#include <climits>
#include <cerrno>
#include <cstring>
#include <cwchar>
static wstring ResourcePrefix;
static wstring getExecutablePath();
static wstring getResourceFileName(wstring resource)
{
return ResourcePrefix + resource;
}
static wstring getExecutablePath()
{
char buf[PATH_MAX + 1];
ssize_t rv = readlink("/proc/self/exe", &buf[0], PATH_MAX);
if(rv == -1)
{
throw runtime_error(string("can't get executable path : ") + strerror(errno));
}
buf[rv] = '\0';
return stringToWString(&buf[0]);
}
initializer initializer1([]()
{
wstring p = getExecutablePath();
size_t pos = p.find_last_of(L"/\\");
if(pos == wstring::npos)
p = L"";
else
p = p.substr(0, pos + 1);
ResourcePrefix = p + L"res/";
});
shared_ptr<Reader> getResourceReader(wstring resource)
{
startSDL();
string fname = wstringToString(getResourceFileName(resource));
return make_shared<RWOpsReader>(SDL_RWFromFile(fname.c_str(), "rb"));
}
#elif __unix
#error implement getResourceReader for other unix
#elif __posix
#error implement getResourceReader for other posix
#else
#error unknown platform in getResourceReader
#endif
static int xResInternal, yResInternal;
static SDL_Window *window = nullptr;
static SDL_GLContext glcontext = nullptr;
static atomic_bool runningGraphics(false), runningSDL(false);
static size_t currentGraphics_ = 0;
size_t currentGraphicsNumber()
{
if(runningGraphics)
return currentGraphics_;
return (size_t)-1;
}
static void startSDL()
{
if(runningSDL.exchange(true))
return;
if(0 != SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_AUDIO))
{
cerr << "error : can't start SDL : " << SDL_GetError() << endl;
exit(1);
}
atexit(endGraphics);
}
void endGraphics()
{
if(runningGraphics.exchange(false))
{
SDL_GL_DeleteContext(glcontext);
glcontext = nullptr;
SDL_DestroyWindow(window);
window = nullptr;
currentGraphics_++;
}
if(runningSDL.exchange(false))
SDL_Quit();
}
static int preferredXRes = -1, preferredYRes = -1;
static bool isFullScreen = false;
void setPreferredMode(int xRes, int yRes)
{
preferredXRes = xRes;
preferredYRes = yRes;
}
static void makeScreenResolution()
{
if(preferredXRes > 0 && preferredYRes > 0)
{
xResInternal = preferredXRes;
yResInternal = preferredYRes;
}
else
{
#if 0
const SDL_VideoInfo * vidInfo = SDL_GetVideoInfo();
if(vidInfo == nullptr)
{
xResInternal = 800;
yResInternal = 600;
}
else
{
xResInternal = vidInfo->current_w;
yResInternal = vidInfo->current_h;
if(xResInternal == 32 * yResInternal / 9)
xResInternal /= 2;
else if(xResInternal == 32 * yResInternal / 10)
xResInternal /= 2;
}
#else
xResInternal = 1024;
yResInternal = 768;
#endif
}
}
void startGraphics()
{
startSDL();
if(runningGraphics.exchange(true))
return;
isFullScreen = false;
makeScreenResolution();
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
window = SDL_CreateWindow("Sprouts", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, xResInternal, yResInternal, SDL_WINDOW_OPENGL);
if(window == nullptr)
{
cerr << "error : can't create window : " << SDL_GetError();
exit(1);
}
glcontext = SDL_GL_CreateContext(window);
if(glcontext == nullptr)
{
cerr << "error : can't create OpenGL context : " << SDL_GetError();
exit(1);
}
SDL_SetHint(SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK, "1");
}
void Display::fullScreen(bool fs)
{
assert(runningGraphics);
if(fs && isFullScreen)
return;
if(!fs && !isFullScreen)
return;
isFullScreen = fs;
#if 1
SDL_SetWindowFullscreen(window, isFullScreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0);
SDL_Rect rect;
if(isFullScreen)
{
SDL_GetWindowSize(window, &rect.w, &rect.h);
xResInternal = rect.w;
yResInternal = rect.h;
}
else
{
makeScreenResolution();
SDL_SetWindowSize(window, xResInternal, yResInternal);
}
#else
int displayIndex = SDL_GetWindowDisplayIndex(window);
SDL_Rect rect;
SDL_GetDisplayBounds(displayIndex, &rect);
SDL_SetWindowBordered(window, isFullScreen ? SDL_FALSE : SDL_TRUE);
if(isFullScreen)
{
SDL_SetWindowPosition(window, rect.x, rect.y);
SDL_SetWindowSize(window, rect.w, rect.h);
SDL_RaiseWindow(window);
xResInternal = rect.w;
yResInternal = rect.h;
}
else
{
makeScreenResolution();
SDL_SetWindowSize(window, xResInternal, yResInternal);
SDL_SetWindowPosition(window, 0, 0);
}
#endif
}
bool Display::fullScreen()
{
return isFullScreen;
}
void Display::setSize(int width, int height)
{
assert(width > 0 && height > 0 && runningGraphics);
if(!isFullScreen)
{
SDL_SetWindowSize(window, width, height);
xResInternal = width;
yResInternal = height;
}
}
static volatile double lastFlipTime = 0;
static volatile double oldLastFlipTime = 0;
static recursive_mutex flipTimeLock;
static void lockFlipTime()
{
flipTimeLock.lock();
}
static void unlockFlipTime()
{
flipTimeLock.unlock();
}
struct FlipTimeLocker
{
FlipTimeLocker()
{
lockFlipTime();
}
~FlipTimeLocker()
{
unlockFlipTime();
}
};
initializer initializer3([]()
{
lastFlipTime = Display::realtimeTimer();
const float fps = defaultFPS;
oldLastFlipTime = lastFlipTime - static_cast<double>(1) / fps;
});
static volatile float averageFPSInternal = defaultFPS;
static double instantaneousFPS()
{
FlipTimeLocker lock;
double delta = lastFlipTime - oldLastFlipTime;
if(delta <= eps || delta > 0.25)
{
return averageFPSInternal;
}
return 1 / delta;
}
static double frameDeltaTime()
{
FlipTimeLocker lock;
double delta = lastFlipTime - oldLastFlipTime;
if(delta <= eps || delta > 0.25)
{
return 1 / averageFPSInternal;
}
return delta;
}
const float FPSUpdateFactor = 0.1f;
static float averageFPS()
{
FlipTimeLocker lock;
return averageFPSInternal;
}
static void flipDisplay(float fps = defaultFPS)
{
double sleepTime;
{
FlipTimeLocker lock;
double curTime = Display::realtimeTimer();
sleepTime = 1 / fps - (curTime - lastFlipTime);
if(sleepTime <= eps)
{
oldLastFlipTime = lastFlipTime;
lastFlipTime = curTime;
averageFPSInternal *= 1 - FPSUpdateFactor;
averageFPSInternal += FPSUpdateFactor * instantaneousFPS();
}
}
if(sleepTime > eps)
{
this_thread::sleep_for(chrono::nanoseconds(static_cast<int64_t>(sleepTime * 1e9)));
{
FlipTimeLocker lock;
oldLastFlipTime = lastFlipTime;
lastFlipTime = Display::realtimeTimer();
averageFPSInternal *= 1 - FPSUpdateFactor;
averageFPSInternal += FPSUpdateFactor * instantaneousFPS();
}
}
SDL_GL_SwapWindow(window);
}
static KeyboardKey translateKey(SDL_Scancode input)
{
switch(input)
{
case SDL_SCANCODE_BACKSPACE:
return KeyboardKey_Backspace;
case SDL_SCANCODE_TAB:
return KeyboardKey_Tab;
case SDL_SCANCODE_CLEAR:
return KeyboardKey_Clear;
case SDL_SCANCODE_RETURN:
return KeyboardKey_Return;
case SDL_SCANCODE_PAUSE:
return KeyboardKey_Pause;
case SDL_SCANCODE_ESCAPE:
return KeyboardKey_Escape;
case SDL_SCANCODE_SPACE:
return KeyboardKey_Space;
case SDL_SCANCODE_APOSTROPHE:
return KeyboardKey_SQuote;
case SDL_SCANCODE_COMMA:
return KeyboardKey_Comma;
case SDL_SCANCODE_MINUS:
return KeyboardKey_Dash;
case SDL_SCANCODE_PERIOD:
return KeyboardKey_Period;
case SDL_SCANCODE_SLASH:
return KeyboardKey_FSlash;
case SDL_SCANCODE_0:
return KeyboardKey_Num0;
case SDL_SCANCODE_1:
return KeyboardKey_Num1;
case SDL_SCANCODE_2:
return KeyboardKey_Num2;
case SDL_SCANCODE_3:
return KeyboardKey_Num3;
case SDL_SCANCODE_4:
return KeyboardKey_Num4;
case SDL_SCANCODE_5:
return KeyboardKey_Num5;
case SDL_SCANCODE_6:
return KeyboardKey_Num6;
case SDL_SCANCODE_7:
return KeyboardKey_Num7;
case SDL_SCANCODE_8:
return KeyboardKey_Num8;
case SDL_SCANCODE_9:
return KeyboardKey_Num9;
case SDL_SCANCODE_SEMICOLON:
return KeyboardKey_Semicolon;
case SDL_SCANCODE_EQUALS:
return KeyboardKey_Equals;
case SDL_SCANCODE_LEFTBRACKET:
return KeyboardKey_LBracket;
case SDL_SCANCODE_BACKSLASH:
return KeyboardKey_BSlash;
case SDL_SCANCODE_RIGHTBRACKET:
return KeyboardKey_RBracket;
case SDL_SCANCODE_A:
return KeyboardKey_A;
case SDL_SCANCODE_B:
return KeyboardKey_B;
case SDL_SCANCODE_C:
return KeyboardKey_C;
case SDL_SCANCODE_D:
return KeyboardKey_D;
case SDL_SCANCODE_E:
return KeyboardKey_E;
case SDL_SCANCODE_F:
return KeyboardKey_F;
case SDL_SCANCODE_G:
return KeyboardKey_G;
case SDL_SCANCODE_H:
return KeyboardKey_H;
case SDL_SCANCODE_I:
return KeyboardKey_I;
case SDL_SCANCODE_J:
return KeyboardKey_J;
case SDL_SCANCODE_K:
return KeyboardKey_K;
case SDL_SCANCODE_L:
return KeyboardKey_L;
case SDL_SCANCODE_M:
return KeyboardKey_M;
case SDL_SCANCODE_N:
return KeyboardKey_N;
case SDL_SCANCODE_O:
return KeyboardKey_O;
case SDL_SCANCODE_P:
return KeyboardKey_P;
case SDL_SCANCODE_Q:
return KeyboardKey_Q;
case SDL_SCANCODE_R:
return KeyboardKey_R;
case SDL_SCANCODE_S:
return KeyboardKey_S;
case SDL_SCANCODE_T:
return KeyboardKey_T;
case SDL_SCANCODE_U:
return KeyboardKey_U;
case SDL_SCANCODE_V:
return KeyboardKey_V;
case SDL_SCANCODE_W:
return KeyboardKey_W;
case SDL_SCANCODE_X:
return KeyboardKey_X;
case SDL_SCANCODE_Y:
return KeyboardKey_Y;
case SDL_SCANCODE_Z:
return KeyboardKey_Z;
case SDL_SCANCODE_DELETE:
return KeyboardKey_Delete;
case SDL_SCANCODE_KP_0:
return KeyboardKey_KPad0;
case SDL_SCANCODE_KP_1:
return KeyboardKey_KPad1;
case SDL_SCANCODE_KP_2:
return KeyboardKey_KPad2;
case SDL_SCANCODE_KP_3:
return KeyboardKey_KPad3;
case SDL_SCANCODE_KP_4:
return KeyboardKey_KPad4;
case SDL_SCANCODE_KP_5:
return KeyboardKey_KPad5;
case SDL_SCANCODE_KP_6:
return KeyboardKey_KPad6;
case SDL_SCANCODE_KP_7:
return KeyboardKey_KPad7;
case SDL_SCANCODE_KP_8:
return KeyboardKey_KPad8;
case SDL_SCANCODE_KP_9:
return KeyboardKey_KPad8;
case SDL_SCANCODE_KP_PERIOD:
return KeyboardKey_KPadPeriod;
case SDL_SCANCODE_KP_DIVIDE:
return KeyboardKey_KPadFSlash;
case SDL_SCANCODE_KP_MULTIPLY:
return KeyboardKey_KPadStar;
case SDL_SCANCODE_KP_MINUS:
return KeyboardKey_KPadDash;
case SDL_SCANCODE_KP_PLUS:
return KeyboardKey_KPadPlus;
case SDL_SCANCODE_KP_ENTER:
return KeyboardKey_KPadReturn;
case SDL_SCANCODE_KP_EQUALS:
return KeyboardKey_KPadEquals;
case SDL_SCANCODE_UP:
return KeyboardKey_Up;
case SDL_SCANCODE_DOWN:
return KeyboardKey_Down;
case SDL_SCANCODE_RIGHT:
return KeyboardKey_Right;
case SDL_SCANCODE_LEFT:
return KeyboardKey_Left;
case SDL_SCANCODE_INSERT:
return KeyboardKey_Insert;
case SDL_SCANCODE_HOME:
return KeyboardKey_Home;
case SDL_SCANCODE_END:
return KeyboardKey_End;
case SDL_SCANCODE_PAGEUP:
return KeyboardKey_PageUp;
case SDL_SCANCODE_PAGEDOWN:
return KeyboardKey_PageDown;
case SDL_SCANCODE_F1:
return KeyboardKey_F1;
case SDL_SCANCODE_F2:
return KeyboardKey_F2;
case SDL_SCANCODE_F3:
return KeyboardKey_F3;
case SDL_SCANCODE_F4:
return KeyboardKey_F4;
case SDL_SCANCODE_F5:
return KeyboardKey_F5;
case SDL_SCANCODE_F6:
return KeyboardKey_F6;
case SDL_SCANCODE_F7:
return KeyboardKey_F7;
case SDL_SCANCODE_F8:
return KeyboardKey_F8;
case SDL_SCANCODE_F9:
return KeyboardKey_F9;
case SDL_SCANCODE_F10:
return KeyboardKey_F10;
case SDL_SCANCODE_F11:
return KeyboardKey_F11;
case SDL_SCANCODE_F12:
return KeyboardKey_F12;
case SDL_SCANCODE_F13:
case SDL_SCANCODE_F14:
case SDL_SCANCODE_F15:
// TODO (jacob#): implement keys
return KeyboardKey_Unknown;
case SDL_SCANCODE_NUMLOCKCLEAR:
return KeyboardKey_NumLock;
case SDL_SCANCODE_CAPSLOCK:
return KeyboardKey_CapsLock;
case SDL_SCANCODE_SCROLLLOCK:
return KeyboardKey_ScrollLock;
case SDL_SCANCODE_RSHIFT:
return KeyboardKey_RShift;
case SDL_SCANCODE_LSHIFT:
return KeyboardKey_LShift;
case SDL_SCANCODE_RCTRL:
return KeyboardKey_RCtrl;
case SDL_SCANCODE_LCTRL:
return KeyboardKey_LCtrl;
case SDL_SCANCODE_RALT:
return KeyboardKey_RAlt;
case SDL_SCANCODE_LALT:
return KeyboardKey_LAlt;
case SDL_SCANCODE_RGUI:
return KeyboardKey_RMeta;
case SDL_SCANCODE_LGUI:
return KeyboardKey_LMeta;
case SDL_SCANCODE_MODE:
return KeyboardKey_Mode;
case SDL_SCANCODE_HELP:
// TODO (jacob#): implement keys
return KeyboardKey_Unknown;
case SDL_SCANCODE_PRINTSCREEN:
return KeyboardKey_PrintScreen;
case SDL_SCANCODE_SYSREQ:
return KeyboardKey_SysRequest;
case SDL_SCANCODE_MENU:
return KeyboardKey_Menu;
case SDL_SCANCODE_POWER:
case SDL_SCANCODE_UNDO:
// TODO (jacob#): implement keys
return KeyboardKey_Unknown;
default:
return KeyboardKey_Unknown;
}
}
static KeyboardModifiers translateModifiers(SDL_Keymod input)
{
int retval = KeyboardModifiers_None;
if(input & KMOD_LSHIFT)
{
retval |= KeyboardModifiers_LShift;
}
if(input & KMOD_RSHIFT)
{
retval |= KeyboardModifiers_RShift;
}
if(input & KMOD_LALT)
{
retval |= KeyboardModifiers_LAlt;
}
if(input & KMOD_RALT)
{
retval |= KeyboardModifiers_RAlt;
}
if(input & KMOD_LCTRL)
{
retval |= KeyboardModifiers_LCtrl;
}
if(input & KMOD_RCTRL)
{
retval |= KeyboardModifiers_RCtrl;
}
if(input & KMOD_LGUI)
{
retval |= KeyboardModifiers_LMeta;
}
if(input & KMOD_RGUI)
{
retval |= KeyboardModifiers_RMeta;
}
if(input & KMOD_NUM)
{
retval |= KeyboardModifiers_NumLock;
}
if(input & KMOD_CAPS)
{
retval |= KeyboardModifiers_CapsLock;
}
if(input & KMOD_MODE)
{
retval |= KeyboardModifiers_Mode;
}
return static_cast<KeyboardModifiers>(retval);
}
static MouseButton translateButton(Uint8 button)
{
switch(button)
{
case SDL_BUTTON_LEFT:
return MouseButton_Left;
case SDL_BUTTON_MIDDLE:
return MouseButton_Middle;
case SDL_BUTTON_RIGHT:
return MouseButton_Right;
case SDL_BUTTON_X1:
return MouseButton_X1;
case SDL_BUTTON_X2:
return MouseButton_X2;
default:
return MouseButton_None;
}
}
static bool &keyState(KeyboardKey key)
{
static bool state[KeyboardKey_max + 1 - KeyboardKey_min];
return state[static_cast<int>(key) + KeyboardKey_min];
}
static MouseButton buttonState = MouseButton_None;
static Event *makeEvent()
{
static bool needCharEvent = false;
static wstring characters;
if(needCharEvent)
{
needCharEvent = false;
wchar_t character = characters[0];
characters.erase(0, 1);
return new KeyPressEvent(character);
}
while(true)
{
SDL_Event SDLEvent;
if(SDL_PollEvent(&SDLEvent) == 0)
{
return nullptr;
}
switch(SDLEvent.type)
{
case SDL_KEYDOWN:
{
KeyboardKey key = translateKey(SDLEvent.key.keysym.scancode);
Event *retval = new KeyDownEvent(key, translateModifiers((SDL_Keymod)SDLEvent.key.keysym.mod), keyState(key));
keyState(key) = true;
return retval;
}
case SDL_KEYUP:
{
KeyboardKey key = translateKey(SDLEvent.key.keysym.scancode);
Event *retval = new KeyUpEvent(key, translateModifiers((SDL_Keymod)SDLEvent.key.keysym.mod));
keyState(key) = false;
return retval;
}
case SDL_MOUSEMOTION:
return new MouseMoveEvent(SDLEvent.motion.x, SDLEvent.motion.y, SDLEvent.motion.xrel, SDLEvent.motion.yrel);
case SDL_MOUSEBUTTONDOWN:
{
MouseButton button = translateButton(SDLEvent.button.button);
buttonState = static_cast<MouseButton>(buttonState | button); // set bit
return new MouseDownEvent(SDLEvent.button.x, SDLEvent.button.y, 0, 0, button);
}
case SDL_MOUSEBUTTONUP:
{
MouseButton button = translateButton(SDLEvent.button.button);
buttonState = static_cast<MouseButton>(buttonState & ~button); // clear bit
return new MouseUpEvent(SDLEvent.button.x, SDLEvent.button.y, 0, 0, button);
}
case SDL_JOYAXISMOTION:
case SDL_JOYBALLMOTION:
case SDL_JOYHATMOTION:
case SDL_JOYBUTTONDOWN:
case SDL_JOYBUTTONUP:
//TODO (jacob#): handle joysticks
break;
case SDL_QUIT:
return new QuitEvent();
case SDL_SYSWMEVENT:
//TODO (jacob#): handle SDL_SYSWMEVENT
break;
}
}
}
namespace
{
struct DefaultEventHandler : public EventHandler
{
virtual bool handleMouseUp(MouseUpEvent &) override
{
return true;
}
virtual bool handleMouseDown(MouseDownEvent &) override
{
return true;
}
virtual bool handleMouseMove(MouseMoveEvent &) override
{
return true;
}
virtual bool handleMouseScroll(MouseScrollEvent &) override
{
return true;
}
virtual bool handleKeyUp(KeyUpEvent &) override
{
return true;
}
virtual bool handleKeyDown(KeyDownEvent &event) override
{
if(event.key == KeyboardKey_F4 && (event.mods & KeyboardModifiers_Alt) != 0)
{
exit(0);
return true;
}
return true;
}
virtual bool handleKeyPress(KeyPressEvent &) override
{
return true;
}
virtual bool handleQuit(QuitEvent &) override
{
exit(0);
return true;
}
};
shared_ptr<EventHandler> DefaultEventHandler_handler(new DefaultEventHandler);
}
static void handleEvents(shared_ptr<EventHandler> eventHandler)
{
for(Event *e = makeEvent(); e != nullptr; e = makeEvent())
{
if(eventHandler == nullptr || !e->dispatch(eventHandler))
{
e->dispatch(DefaultEventHandler_handler);
}
}
}
void glLoadMatrix(Matrix mat)
{
float matArray[16] =
{
mat.x00,
mat.x01,
mat.x02,
0,
mat.x10,
mat.x11,
mat.x12,
0,
mat.x20,
mat.x21,
mat.x22,
0,
mat.x30,
mat.x31,
mat.x32,
1,
};
glLoadMatrixf(static_cast<const float *>(matArray));
}
wstring Display::title()
{
return stringToWString(SDL_GetWindowTitle(window));
}
void Display::title(wstring newTitle)
{
string s = wstringToString(newTitle);
SDL_SetWindowTitle(window, s.c_str());
}
void Display::handleEvents(shared_ptr<EventHandler> eventHandler)
{
::handleEvents(eventHandler);
}
static double timer_;
static void updateTimer()
{
timer_ = Display::realtimeTimer();
}
initializer initializer4([]()
{
updateTimer();
});
void Display::flip(float fps)
{
flipDisplay(fps);
updateTimer();
}
double Display::instantaneousFPS()
{
return ::instantaneousFPS();
}
double Display::frameDeltaTime()
{
return ::frameDeltaTime();
}
float Display::averageFPS()
{
return ::averageFPS();
}
double Display::timer()
{
return timer_;
}
static float scaleXInternal = 1.0, scaleYInternal = 1.0;
int Display::width()
{
return xResInternal;
}
int Display::height()
{
return yResInternal;
}
float Display::scaleX()
{
return scaleXInternal;
}
float Display::scaleY()
{
return scaleYInternal;
}
void Display::initFrame()
{
if(width() < height())
{
scaleXInternal = 1.0;
scaleYInternal = static_cast<float>(height()) / width();
}
else
{
scaleXInternal = static_cast<float>(width()) / height();
scaleYInternal = 1.0;
}
glEnable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_2D);
glEnable(GL_ALPHA_TEST);