-
-
Notifications
You must be signed in to change notification settings - Fork 280
/
Copy pathSDL2_FNAPlatform.cs
2903 lines (2670 loc) · 90.5 KB
/
SDL2_FNAPlatform.cs
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
#region License
/* FNA - XNA4 Reimplementation for Desktop Platforms
* Copyright 2009-2024 Ethan Lee and the MonoGame Team
*
* Released under the Microsoft Public License.
* See LICENSE for details.
*/
#endregion
#region Using Statements
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using SDL2;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
#endregion
namespace Microsoft.Xna.Framework
{
internal static class SDL2_FNAPlatform
{
#region Static Constants
private static string OSVersion;
private static readonly bool UseScancodes = Environment.GetEnvironmentVariable(
"FNA_KEYBOARD_USE_SCANCODES"
) == "1";
private static bool SupportsGlobalMouse;
private static bool SupportsOrientations;
#endregion
#region Game Objects
/* This is needed for asynchronous window events */
private static List<Game> activeGames = new List<Game>();
#endregion
#region Init/Exit Methods
public static string ProgramInit(LaunchParameters args)
{
// This is how we can weed out cases where fnalibs is missing
try
{
OSVersion = SDL.SDL_GetPlatform();
}
catch(DllNotFoundException)
{
FNALoggerEXT.LogError(
"SDL2 was not found! Do you have fnalibs?"
);
throw;
}
catch(BadImageFormatException e)
{
string error = string.Format(
"This process is {0}-bit, the DLL is {1}-bit!",
(IntPtr.Size == 4) ? "32" : "64",
(IntPtr.Size == 4) ? "64" : "32"
);
FNALoggerEXT.LogError(error);
throw new BadImageFormatException(error, e);
}
/* SDL2 might complain if an OS that uses SDL_main has not actually
* used SDL_main by the time you initialize SDL2.
* The only platform that is affected is Windows, but we can skip
* their WinMain. This was only added to prevent iOS from exploding.
* -flibit
*/
SDL.SDL_SetMainReady();
// Also, Windows is an idiot. -flibit
if (OSVersion.Equals("Windows"))
{
// Visual Studio is an idiot.
if (System.Diagnostics.Debugger.IsAttached)
{
SDL.SDL_SetHint(
SDL.SDL_HINT_WINDOWS_DISABLE_THREAD_NAMING,
"1"
);
}
}
/* Mount TitleLocation.Path */
string titleLocation = GetBaseDirectory();
// If available, load the SDL_GameControllerDB
string mappingsDB = Path.Combine(
titleLocation,
"gamecontrollerdb.txt"
);
if (File.Exists(mappingsDB))
{
SDL.SDL_SetHint(
SDL.SDL_HINT_GAMECONTROLLERCONFIG_FILE,
mappingsDB
);
}
/* By default, assume physical layout, since XNA games mostly assume XInput.
* This used to be more flexible until Steam decided to enforce the variable
* that already had their desired value as the default (big surprise).
*
* TL;DR: Suck my ass, Steam
*
* -flibit
*/
string useLabels = (Environment.GetEnvironmentVariable(
"FNA_GAMEPAD_IGNORE_PHYSICAL_LAYOUT"
) == "1") ? "1" : "0";
SDL.SDL_SetHintWithPriority(
SDL.SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS,
useLabels,
SDL.SDL_HintPriority.SDL_HINT_OVERRIDE
);
// Are you even surprised this is necessary?
if (Environment.GetEnvironmentVariable("FNA_NUKE_STEAM_INPUT") == "1")
{
SDL.SDL_SetHintWithPriority(
"SDL_GAMECONTROLLER_IGNORE_DEVICES",
"0x28DE/0x11FF",
SDL.SDL_HintPriority.SDL_HINT_OVERRIDE
);
SDL.SDL_SetHintWithPriority(
"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT",
"",
SDL.SDL_HintPriority.SDL_HINT_OVERRIDE
);
// This should be redundant, but who knows...
SDL.SDL_SetHintWithPriority(
"SDL_GAMECONTROLLER_ALLOW_STEAM_VIRTUAL_GAMEPAD",
"0",
SDL.SDL_HintPriority.SDL_HINT_OVERRIDE
);
}
// Built-in SDL2 command line arguments
string arg;
if (args.TryGetValue("glprofile", out arg))
{
if (arg == "es3")
{
SDL.SDL_SetHintWithPriority(
"FNA3D_OPENGL_FORCE_ES3",
"1",
SDL.SDL_HintPriority.SDL_HINT_OVERRIDE
);
}
else if (arg == "core")
{
SDL.SDL_SetHintWithPriority(
"FNA3D_OPENGL_FORCE_CORE_PROFILE",
"1",
SDL.SDL_HintPriority.SDL_HINT_OVERRIDE
);
}
else if (arg == "compatibility")
{
SDL.SDL_SetHintWithPriority(
"FNA3D_OPENGL_FORCE_COMPATIBILITY_PROFILE",
"1",
SDL.SDL_HintPriority.SDL_HINT_OVERRIDE
);
}
}
if (args.TryGetValue("angle", out arg) && arg == "1")
{
SDL.SDL_SetHintWithPriority(
"FNA3D_OPENGL_FORCE_ES3",
"1",
SDL.SDL_HintPriority.SDL_HINT_OVERRIDE
);
SDL.SDL_SetHintWithPriority(
"SDL_OPENGL_ES_DRIVER",
"1",
SDL.SDL_HintPriority.SDL_HINT_OVERRIDE
);
}
if (args.TryGetValue("forcemailboxvsync", out arg) && arg == "1")
{
SDL.SDL_SetHintWithPriority(
"FNA3D_VULKAN_FORCE_MAILBOX_VSYNC",
"1",
SDL.SDL_HintPriority.SDL_HINT_OVERRIDE
);
}
/* FIXME: SDL bug!
* Well, really it's a Windows bug - for some reason the
* Windows audio team has lost it and now you can't just
* pick between directsound/wasapi, we have to go back
* and forth constantly, so for convenience we're adding
* this check. This shouldn't be necessary anywhere else
* as far as I know, treat it like an OS bug otherwise!
* -flibit
*/
if (args.TryGetValue("audiodriver", out arg))
{
SDL.SDL_SetHintWithPriority(
"SDL_AUDIODRIVER",
arg,
SDL.SDL_HintPriority.SDL_HINT_OVERRIDE
);
}
// This _should_ be the first real SDL call we make...
if (SDL.SDL_Init(
SDL.SDL_INIT_VIDEO |
SDL.SDL_INIT_GAMECONTROLLER
) != 0)
{
throw new Exception("SDL_Init failed: " + SDL.SDL_GetError());
}
string videoDriver = SDL.SDL_GetCurrentVideoDriver();
/* A number of platforms don't support global mouse, but
* this really only matters on desktop where the game
* screen may not be covering the whole display.
*/
SupportsGlobalMouse = ( OSVersion.Equals("Windows") ||
OSVersion.Equals("Mac OS X") ||
videoDriver.Equals("x11") );
// Only iOS and Android care about device orientation.
SupportsOrientations = ( OSVersion.Equals("iOS") ||
OSVersion.Equals("Android") );
/* High-DPI is really annoying and only some platforms
* actually let you control the drawable surface.
*/
if ( !videoDriver.Equals("wayland") &&
!videoDriver.Equals("cocoa") &&
!videoDriver.Equals("uikit") )
{
/* Note that this is NOT an override.
* We can be overruled, just in case.
*/
SDL.SDL_SetHintWithPriority(
SDL.SDL_HINT_VIDEO_HIGHDPI_DISABLED,
"1",
SDL.SDL_HintPriority.SDL_HINT_NORMAL
);
}
/* We need to change the Windows default here, as the
* display server does not seem to handle focus changes
* gracefully like Wayland (and even X11) do. If for
* _any_ reason focus changes we need to minimize,
* because the alternative is having a window up front
* that has no focus and therefore gets no events, and
* the user (rightfully) will have no idea why.
* -flibit
*/
if (OSVersion.Equals("Windows"))
{
SDL.SDL_SetHint(
SDL.SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS,
"1"
);
}
// Set any hints to match XNA4 behavior...
string hint = SDL.SDL_GetHint(SDL.SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS);
if (String.IsNullOrEmpty(hint))
{
SDL.SDL_SetHint(
SDL.SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS,
"1"
);
}
SDL.SDL_SetHint(
SDL.SDL_HINT_ORIENTATIONS,
"LandscapeLeft LandscapeRight Portrait"
);
// We want to initialize the controllers ASAP!
SDL.SDL_Event[] evt = new SDL.SDL_Event[1];
SDL.SDL_PumpEvents();
while (SDL.SDL_PeepEvents(
evt,
1,
SDL.SDL_eventaction.SDL_GETEVENT,
SDL.SDL_EventType.SDL_CONTROLLERDEVICEADDED,
SDL.SDL_EventType.SDL_CONTROLLERDEVICEADDED
) == 1) {
INTERNAL_AddInstance(evt[0].cdevice.which);
}
if (OSVersion.Equals("Windows"))
{
/* Windows has terrible event pumping and doesn't give us
* WM_PAINT events correctly. So we get to do this!
* -flibit
*/
IntPtr prevUserData;
SDL.SDL_GetEventFilter(
out prevEventFilter,
out prevUserData
);
SDL.SDL_SetEventFilter(
win32OnPaint,
prevUserData
);
}
/* Minimal, Portable, SDL-based Tesla Splash.
* Copyright (c) 2022-2024 Ethan Lee
* Released under the zlib license:
* https://www.zlib.net/zlib_license.html
*
* FIXME: SteamTesla is a guess based on SteamTenfoot/SteamDeck!
*
* Image: https://flibitijibibo.com/tesla.bmp
* As you can see, this only works if the image is in
* the title root, so this isn't being forced on anyone.
*
* Elon: I'll delete this code for $10M USD after taxes!
* Love, flibit
*/
if (SDL.SDL_GetHint("SteamTesla") == "1")
{
IntPtr bmp = SDL.SDL_LoadBMP("tesla.bmp");
if (bmp != IntPtr.Zero)
{
int width, height;
unsafe
{
SDL.SDL_Surface *surface = (SDL.SDL_Surface*) bmp;
width = surface->w;
height = surface->h;
}
IntPtr window = SDL.SDL_CreateWindow(null, 0, 0, width, height, 0);
if (window != IntPtr.Zero)
{
ulong target = SDL.SDL_GetTicks64() + 2000;
do
{
/* Note that we're not polling events here, we would prefer
* that these events go to the actual game instead!
*
* Also note that we're getting/blitting each frame, since
* certain OS events can invalidate it (usually resizes?).
*/
IntPtr windowSurface = SDL.SDL_GetWindowSurface(window);
SDL.SDL_BlitSurface(bmp, IntPtr.Zero, windowSurface, IntPtr.Zero);
SDL.SDL_UpdateWindowSurface(window);
} while ((long) (SDL.SDL_GetTicks64() - target) <= 0);
SDL.SDL_DestroyWindow(window);
}
SDL.SDL_FreeSurface(bmp);
}
}
return titleLocation;
}
public static void ProgramExit(object sender, EventArgs e)
{
// This _should_ be the last SDL call we make...
SDL.SDL_QuitSubSystem(
SDL.SDL_INIT_VIDEO |
SDL.SDL_INIT_GAMECONTROLLER
);
}
#endregion
#region Allocator
public static IntPtr Malloc(int size)
{
return SDL.SDL_malloc((IntPtr) size);
}
#endregion
#region Environment
public static void SetEnv(string name, string value)
{
SDL.SDL_SetHintWithPriority(name, value, SDL.SDL_HintPriority.SDL_HINT_OVERRIDE);
}
#endregion
#region Window Methods
public static GameWindow CreateWindow()
{
// Set and initialize the SDL2 window
SDL.SDL_WindowFlags initFlags = (
SDL.SDL_WindowFlags.SDL_WINDOW_HIDDEN |
SDL.SDL_WindowFlags.SDL_WINDOW_INPUT_FOCUS |
SDL.SDL_WindowFlags.SDL_WINDOW_MOUSE_FOCUS
) | (SDL.SDL_WindowFlags) FNA3D.FNA3D_PrepareWindowAttributes();
if ((initFlags & SDL.SDL_WindowFlags.SDL_WINDOW_VULKAN) == SDL.SDL_WindowFlags.SDL_WINDOW_VULKAN)
{
string cachePath = SDL.SDL_GetHint(
"FNA3D_VULKAN_PIPELINE_CACHE_FILE_NAME"
);
if (cachePath == null) // Empty is a valid value
{
if ( OSVersion.Equals("Windows") ||
OSVersion.Equals("Mac OS X") ||
OSVersion.Equals("Linux") ||
OSVersion.Equals("FreeBSD") ||
OSVersion.Equals("OpenBSD") ||
OSVersion.Equals("NetBSD") )
{
#if DEBUG // Save pipeline cache files to the base directory for debug builds
cachePath = "FNA3D_Vulkan_PipelineCache.blob";
#else
string exeName = Path.GetFileNameWithoutExtension(
AppDomain.CurrentDomain.FriendlyName
).Replace(".vshost", "");
cachePath = Path.Combine(
SDL.SDL_GetPrefPath(null, "FNA3D"),
exeName + "_Vulkan_PipelineCache.blob"
);
#endif
}
else
{
/* For all non-desktop targets, disable
* the pipeline cache. There is usually
* some specialized path you have to
* take to use pipeline cache files, so
* developers will have to do things the
* hard way over there.
*/
cachePath = string.Empty;
}
SDL.SDL_SetHint(
"FNA3D_VULKAN_PIPELINE_CACHE_FILE_NAME",
cachePath
);
}
}
if (Environment.GetEnvironmentVariable("FNA_GRAPHICS_ENABLE_HIGHDPI") == "1")
{
initFlags |= SDL.SDL_WindowFlags.SDL_WINDOW_ALLOW_HIGHDPI;
}
string title = MonoGame.Utilities.AssemblyHelper.GetDefaultWindowTitle();
IntPtr window = SDL.SDL_CreateWindow(
title,
SDL.SDL_WINDOWPOS_CENTERED,
SDL.SDL_WINDOWPOS_CENTERED,
GraphicsDeviceManager.DefaultBackBufferWidth,
GraphicsDeviceManager.DefaultBackBufferHeight,
initFlags
);
if (window == IntPtr.Zero)
{
/* If this happens, the GL attributes were
* rejected by the platform. This is EXTREMELY
* rare (unless you're on Android, of course).
*/
throw new NoSuitableGraphicsDeviceException(
SDL.SDL_GetError()
);
}
INTERNAL_SetIcon(window, title);
// Disable the screensaver.
SDL.SDL_DisableScreenSaver();
// We hide the mouse cursor by default.
OnIsMouseVisibleChanged(false);
/* If high DPI is not found, unset the HIGHDPI var.
* This is our way to communicate that it failed...
* -flibit
*/
initFlags = (SDL.SDL_WindowFlags) SDL.SDL_GetWindowFlags(window);
if ((initFlags & SDL.SDL_WindowFlags.SDL_WINDOW_ALLOW_HIGHDPI) == 0)
{
Environment.SetEnvironmentVariable("FNA_GRAPHICS_ENABLE_HIGHDPI", "0");
}
return new FNAWindow(
window,
@"\\.\DISPLAY" + (
SDL.SDL_GetWindowDisplayIndex(window) + 1
).ToString()
);
}
public static void DisposeWindow(GameWindow window)
{
/* Some window managers might try to minimize the window as we're
* destroying it. This looks pretty stupid and could cause problems,
* so set this hint right before we destroy everything.
* -flibit
*/
SDL.SDL_SetHintWithPriority(
SDL.SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS,
"0",
SDL.SDL_HintPriority.SDL_HINT_OVERRIDE
);
if (Mouse.WindowHandle == window.Handle)
{
Mouse.WindowHandle = IntPtr.Zero;
}
if (TouchPanel.WindowHandle == window.Handle)
{
TouchPanel.WindowHandle = IntPtr.Zero;
}
if (TextInputEXT.WindowHandle == window.Handle)
{
TextInputEXT.WindowHandle = IntPtr.Zero;
}
SDL.SDL_DestroyWindow(window.Handle);
}
public static void ApplyWindowChanges(
IntPtr window,
int clientWidth,
int clientHeight,
bool wantsFullscreen,
string screenDeviceName,
ref string resultDeviceName
) {
bool center = false;
/* The drawable size is now the primary width/height, so
* the window needs to accommodate the GL viewport.
* -flibit
*/
ScaleForWindow(window, false, ref clientWidth, ref clientHeight);
// When windowed, set the size before moving
if (!wantsFullscreen)
{
bool resize = false;
if ((SDL.SDL_GetWindowFlags(window) & (uint) SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN) != 0)
{
SDL.SDL_SetWindowFullscreen(window, 0);
resize = true;
}
else
{
int w, h;
SDL.SDL_GetWindowSize(
window,
out w,
out h
);
resize = (clientWidth != w || clientHeight != h);
}
if (resize)
{
SDL.SDL_RestoreWindow(window);
SDL.SDL_SetWindowSize(window, clientWidth, clientHeight);
center = true;
}
}
// Get on the right display!
int displayIndex = 0;
for (int i = 0; i < GraphicsAdapter.Adapters.Count; i += 1)
{
if (screenDeviceName == GraphicsAdapter.Adapters[i].DeviceName)
{
displayIndex = i;
break;
}
}
// Just to be sure, become a window first before changing displays
if (resultDeviceName != screenDeviceName)
{
SDL.SDL_SetWindowFullscreen(window, 0);
resultDeviceName = screenDeviceName;
center = true;
}
// Window always gets centered on changes, per XNA behavior
if (center)
{
int pos = SDL.SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex);
SDL.SDL_SetWindowPosition(
window,
pos,
pos
);
}
// Set fullscreen after we've done all the ugly stuff.
if (wantsFullscreen)
{
if ((SDL.SDL_GetWindowFlags(window) & (uint) SDL.SDL_WindowFlags.SDL_WINDOW_SHOWN) == 0)
{
/* If we're still hidden, we can't actually go fullscreen yet.
* But, we can at least set the hidden window size to match
* what the window/drawable sizes will eventually be later.
* -flibit
*/
SDL.SDL_DisplayMode mode;
SDL.SDL_GetCurrentDisplayMode(
displayIndex,
out mode
);
SDL.SDL_SetWindowSize(window, mode.w, mode.h);
}
SDL.SDL_SetWindowFullscreen(
window,
(uint) SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN_DESKTOP
);
}
// Update the mouse window bounds
if (Mouse.WindowHandle == window)
{
Rectangle b = GetWindowBounds(window);
Mouse.INTERNAL_WindowWidth = b.Width;
Mouse.INTERNAL_WindowHeight = b.Height;
}
}
public static void ScaleForWindow(IntPtr window, bool invert, ref int w, ref int h)
{
int ww, wh, dw, dh;
SDL.SDL_GetWindowSize(window, out ww, out wh);
FNA3D.FNA3D_GetDrawableSize(window, out dw, out dh);
if ( ww != 0 &&
wh != 0 &&
dw != 0 &&
dh != 0 &&
(ww != dw || wh != dh) )
{
if (invert)
{
w = (int) (w * ((float) dw / (float) ww));
h = (int) (h * ((float) dh / (float) wh));
}
else
{
w = (int) (w / ((float) dw / (float) ww));
h = (int) (h / ((float) dh / (float) wh));
}
}
}
public static Rectangle GetWindowBounds(IntPtr window)
{
Rectangle result;
if ((SDL.SDL_GetWindowFlags(window) & (uint) SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN) != 0)
{
/* It's easier/safer to just use the display mode here */
SDL.SDL_DisplayMode mode;
SDL.SDL_GetCurrentDisplayMode(
SDL.SDL_GetWindowDisplayIndex(
window
),
out mode
);
result.X = 0;
result.Y = 0;
result.Width = mode.w;
result.Height = mode.h;
}
else
{
SDL.SDL_GetWindowPosition(
window,
out result.X,
out result.Y
);
SDL.SDL_GetWindowSize(
window,
out result.Width,
out result.Height
);
}
return result;
}
public static bool GetWindowResizable(IntPtr window)
{
return ((SDL.SDL_GetWindowFlags(window) & (uint) SDL.SDL_WindowFlags.SDL_WINDOW_RESIZABLE) != 0);
}
public static void SetWindowResizable(IntPtr window, bool resizable)
{
SDL.SDL_SetWindowResizable(
window,
resizable ?
SDL.SDL_bool.SDL_TRUE :
SDL.SDL_bool.SDL_FALSE
);
}
public static bool GetWindowBorderless(IntPtr window)
{
return ((SDL.SDL_GetWindowFlags(window) & (uint) SDL.SDL_WindowFlags.SDL_WINDOW_BORDERLESS) != 0);
}
public static void SetWindowBorderless(IntPtr window, bool borderless)
{
SDL.SDL_SetWindowBordered(
window,
borderless ?
SDL.SDL_bool.SDL_FALSE :
SDL.SDL_bool.SDL_TRUE
);
}
public static void SetWindowTitle(IntPtr window, string title)
{
SDL.SDL_SetWindowTitle(
window,
title
);
}
public static bool IsScreenKeyboardShown(IntPtr window)
{
return SDL.SDL_IsScreenKeyboardShown(window) == SDL.SDL_bool.SDL_TRUE;
}
private static void INTERNAL_SetIcon(IntPtr window, string title)
{
string fileIn = String.Empty;
/* If the game's using SDL2_image, provide the option to use a PNG
* instead of a BMP. Nice for anyone who cares about transparency.
* -flibit
*/
try
{
fileIn = INTERNAL_GetIconName(title + ".png");
if (!String.IsNullOrEmpty(fileIn))
{
int w, h, len;
IntPtr pixels, icon;
using (Stream stream = TitleContainer.OpenStream(fileIn))
{
pixels = FNA3D.ReadImageStream(
stream,
out w,
out h,
out len
);
icon = SDL.SDL_CreateRGBSurfaceFrom(
pixels,
w,
h,
8 * 4,
w * 4,
0x000000FF,
0x0000FF00,
0x00FF0000,
0xFF000000
);
}
SDL.SDL_SetWindowIcon(window, icon);
SDL.SDL_FreeSurface(icon);
FNA3D.FNA3D_Image_Free(pixels);
return;
}
}
catch(DllNotFoundException)
{
// Not that big a deal guys.
}
fileIn = INTERNAL_GetIconName(title + ".bmp");
if (!String.IsNullOrEmpty(fileIn))
{
IntPtr icon = SDL.SDL_LoadBMP(fileIn);
SDL.SDL_SetWindowIcon(window, icon);
SDL.SDL_FreeSurface(icon);
}
}
private static string INTERNAL_GetIconName(string title)
{
string fileIn = Path.Combine(TitleLocation.Path, title);
if (File.Exists(fileIn))
{
// If the title and filename work, it just works. Fine.
return fileIn;
}
else
{
// But sometimes the title has invalid characters inside.
fileIn = Path.Combine(
TitleLocation.Path,
INTERNAL_StripBadChars(title)
);
if (File.Exists(fileIn))
{
return fileIn;
}
}
return String.Empty;
}
private static string INTERNAL_StripBadChars(string path)
{
/* In addition to the filesystem's invalid charset, we need to
* blacklist the Windows standard set too, no matter what.
* -flibit
*/
char[] hardCodeBadChars = new char[]
{
'<',
'>',
':',
'"',
'/',
'\\',
'|',
'?',
'*'
};
List<char> badChars = new List<char>();
badChars.AddRange(Path.GetInvalidFileNameChars());
badChars.AddRange(hardCodeBadChars);
string stripChars = path;
foreach (char c in badChars)
{
stripChars = stripChars.Replace(c.ToString(), "");
}
return stripChars;
}
public static void SetTextInputRectangle(IntPtr window, Rectangle rectangle)
{
SDL.SDL_Rect rect = new SDL.SDL_Rect();
rect.x = rectangle.X;
rect.y = rectangle.Y;
rect.w = rectangle.Width;
rect.h = rectangle.Height;
SDL.SDL_SetTextInputRect(ref rect);
}
#endregion
#region Display Methods
private static DisplayOrientation INTERNAL_ConvertOrientation(SDL.SDL_DisplayOrientation orientation)
{
switch (orientation)
{
case SDL.SDL_DisplayOrientation.SDL_ORIENTATION_LANDSCAPE:
return DisplayOrientation.LandscapeLeft;
case SDL.SDL_DisplayOrientation.SDL_ORIENTATION_LANDSCAPE_FLIPPED:
return DisplayOrientation.LandscapeRight;
case SDL.SDL_DisplayOrientation.SDL_ORIENTATION_PORTRAIT:
case SDL.SDL_DisplayOrientation.SDL_ORIENTATION_PORTRAIT_FLIPPED:
return DisplayOrientation.Portrait;
default:
throw new NotSupportedException("FNA does not support this device orientation.");
}
}
private static void INTERNAL_HandleOrientationChange(
DisplayOrientation orientation,
GraphicsDevice graphicsDevice,
GraphicsAdapter graphicsAdapter,
FNAWindow window
) {
// Flip the backbuffer dimensions if needed
int width = graphicsDevice.PresentationParameters.BackBufferWidth;
int height = graphicsDevice.PresentationParameters.BackBufferHeight;
int min = Math.Min(width, height);
int max = Math.Max(width, height);
if (orientation == DisplayOrientation.Portrait)
{
graphicsDevice.PresentationParameters.BackBufferWidth = min;
graphicsDevice.PresentationParameters.BackBufferHeight = max;
}
else
{
graphicsDevice.PresentationParameters.BackBufferWidth = max;
graphicsDevice.PresentationParameters.BackBufferHeight = min;
}
// Update the graphics device and window
graphicsDevice.PresentationParameters.DisplayOrientation = orientation;
window.CurrentOrientation = orientation;
graphicsDevice.Reset(
graphicsDevice.PresentationParameters,
graphicsAdapter
);
window.INTERNAL_OnOrientationChanged();
}
public static bool SupportsOrientationChanges()
{
return SupportsOrientations;
}
#endregion
#region Event Loop
public static GraphicsAdapter RegisterGame(Game game)
{
SDL.SDL_ShowWindow(game.Window.Handle);
// Store this for internal event filter work
activeGames.Add(game);
// Which display did we end up on?
int displayIndex = SDL.SDL_GetWindowDisplayIndex(
game.Window.Handle
);
return GraphicsAdapter.Adapters[displayIndex];
}
public static void UnregisterGame(Game game)
{
activeGames.Remove(game);
}
public static unsafe void PollEvents(
Game game,
ref GraphicsAdapter currentAdapter,
bool[] textInputControlDown,
ref bool textInputSuppress
) {
SDL.SDL_Event evt;
char* charsBuffer = stackalloc char[32]; // SDL_TEXTINPUTEVENT_TEXT_SIZE
while (SDL.SDL_PollEvent(out evt) == 1)
{
// Keyboard
if (evt.type == SDL.SDL_EventType.SDL_KEYDOWN)
{
Keys key = ToXNAKey(ref evt.key.keysym);
if (!Keyboard.keys.Contains(key))
{
Keyboard.keys.Add(key);
int textIndex;
if (FNAPlatform.TextInputBindings.TryGetValue(key, out textIndex))
{
textInputControlDown[textIndex] = true;
TextInputEXT.OnTextInput(FNAPlatform.TextInputCharacters[textIndex]);
}
else if ((Keyboard.keys.Contains(Keys.LeftControl) || Keyboard.keys.Contains(Keys.RightControl))
&& key == Keys.V)
{
textInputControlDown[6] = true;
TextInputEXT.OnTextInput(FNAPlatform.TextInputCharacters[6]);
textInputSuppress = true;
}
}
else if (evt.key.repeat > 0)
{
int textIndex;
if (FNAPlatform.TextInputBindings.TryGetValue(key, out textIndex))
{
TextInputEXT.OnTextInput(FNAPlatform.TextInputCharacters[textIndex]);
}
else if ((Keyboard.keys.Contains(Keys.LeftControl) || Keyboard.keys.Contains(Keys.RightControl))
&& key == Keys.V)
{
TextInputEXT.OnTextInput(FNAPlatform.TextInputCharacters[6]);
}
}
}
else if (evt.type == SDL.SDL_EventType.SDL_KEYUP)
{
Keys key = ToXNAKey(ref evt.key.keysym);
if (Keyboard.keys.Remove(key))
{
int value;