-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGear.cs
5261 lines (4975 loc) · 175 KB
/
Gear.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
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Text;
using System.Diagnostics;
using NetCoreServer;
using TcpClient = NetCoreServer.TcpClient;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using Mono.Nat;
using System.Threading.Tasks;
using System.Globalization;
using System.Collections;
using System.Runtime.CompilerServices;
using System.ComponentModel;
public static class Gear
{
///<summary>
///text, <paramref name="param"/>, <see cref="char"/>, <typeparamref name="Type"/>
///</summary>
private static void SummaryExample() { }
#region Sleep Prevention
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);
[Flags]
private enum EXECUTION_STATE : uint
{
ES_AWAYMODE_REQUIRED = 0x00000040,
ES_CONTINUOUS = 0x80000000,
ES_DISPLAY_REQUIRED = 0x00000002,
ES_SYSTEM_REQUIRED = 0x00000001
// Legacy flag, should not be used.
// ES_USER_PRESENT = 0x00000004
}
#endregion
#region Window Maximization
[DllImport("SDL2.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern void SDL_MaximizeWindow(IntPtr window);
#endregion
#region Show Console
private static void Form1_Load(object sender, EventArgs e)
{
AllocConsole();
}
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AllocConsole();
#endregion
#region Data
private static Game game;
private static Program program;
private static GraphicsDeviceManager graphics;
private static SpriteBatch spriteBatch;
private static RenderTarget2D renderTarget;
private static SamplerState renderSamplerState;
private static CanvasPixelFilter renderPixelFilter;
private static Server server;
private static Client client;
private enum MessageType
{
Connection, UniqueNameChange, ClientConnected, ClientDisconnected, ClientOnline, ClientMessageToAll, ClientMessageToClient, ClientMessageToServer, ServerMessageToAll, ServerMessageToClient, ClientMessageToAllAndServer
}
public enum RotationSamples
{
Left, Right, Up, Down, UpLeft, UpRight, DownLeft, DownRight
}
public enum CanvasPixelFilter
{
Lowest, Medium, Highest
}
public enum Key
{
None = 0, BackSpace = 8, Tab = 9, Enter = 13, Pause = 19, CapsLock = 20, Kana = 21, Kanji = 25, Escape = 27, ImeConvert = 28, ImeNoConvert = 29, Space = 32, PageUp = 33, PageDown = 34, End = 35, Home = 36, LeftArrow = 37, UpArrow = 38, RightArrow = 39, DownArrow = 40, Select = 41, Print = 42, Execute = 43, PrintScreen = 44, Insert = 45, Delete = 46, Help = 47, _0 = 48, _1 = 49, _2 = 50, _3 = 51, _4 = 52, _5 = 53, _6 = 54, _7 = 55, _8 = 56, _9 = 57, A = 65, B = 66, C = 67, D = 68, E = 69, F = 70, G = 71, H = 72, I = 73, J = 74, K = 75, L = 76, M = 77, N = 78, O = 79, P = 80, Q = 81, R = 82, S = 83, T = 84, U = 85, V = 86, W = 87, X = 88, Y = 89, Z = 90, LeftWindows = 91, RightWindows = 92, Apps = 93, Sleep = 95, Num0 = 96, Num1 = 97, Num2 = 98, Num3 = 99, Num4 = 100, Num5 = 101, Num6 = 102, Num7 = 103, Num8 = 104, Num9 = 105, NumMultiply = 106, NumAdd = 107, Separator = 108, NumSubtract = 109, NumDecimal = 110, NumDivide = 111, F1 = 112, F2 = 113, F3 = 114, F4 = 115, F5 = 116, F6 = 117, F7 = 118, F8 = 119, F9 = 120, F10 = 121, F11 = 122, F12 = 123, F13 = 124, F14 = 125, F15 = 126, F16 = 127, F17 = 128, F18 = 129, F19 = 130, F20 = 131, F21 = 132, F22 = 133, F23 = 134, F24 = 135, NumLock = 144, Scroll = 145, ShiftLeft = 160, ShiftRight = 161, ControlLeft = 162, ControlRight = 163, AltLeft = 164, AltRight = 165, BrowserBack = 166, BrowserForward = 167, BrowserRefresh = 168, BrowserStop = 169, BrowserSearch = 170, BrowserFavorites = 171, BrowserHome = 172, VolumeMute = 173, VolumeDown = 174, VolumeUp = 175, MediaNextTrack = 176, MediaPreviousTrack = 177, MediaStop = 178, MediaPlayPause = 179, LaunchMail = 180, SelectMedia = 181, LaunchApplication1 = 182, LaunchApplication2 = 183, Semicolon = 186, Equals = 187, Comma = 188, MinusDash = 189, Dot = 190, Slash = 191, GraveAccent = 192, ChatPadGreen = 202, ChatPadOrange = 203, SquareBracketOpen = 219, Backslash = 220, SquareBracketClose = 221, Quote = 222, Oem8 = 223, OemBackslash = 226, ProcessKey = 229, OemCopy = 242, OemAuto = 243, OemEnlW = 244, Attn = 246, Crsel = 247, Exsel = 248, EraseEof = 249, Play = 250, Zoom = 251, Pa1 = 253, OemClear = 254
}
public enum RoundNumberToward
{
Closest, Up, Down
}
public enum RoundNumberPrio
{
TowardEven, AwayFromZero, TowardZero, TowardNegativeInfinity, TowardPositiveInfinity
}
public enum NumberTimeConvertType
{
MillisecondsToSeconds,
SecondsToMilliseconds, SecondsToMinutes, SecondsToHours,
MinutesToMilliseconds, MinutesToSeconds, MinutesToHours, MinutesToDays,
HoursToSeconds, HoursToMinutes, HoursToDays, HoursToWeeks,
DaysToMinutes, DaysToHours, DaysToWeeks,
WeeksToHours, WeeksToDays
}
public enum PopUpIcon
{
None, Info, Error, Warning
}
public enum Motion
{
PerSecond, PerTick
}
public enum MouseHitboxInteraction
{
Hovered, Unhovered, Clicked, ClickReleased, Released
}
public enum Interaction
{
Pressed, Released
}
public enum MouseButton
{
Left, Middle, Right
}
private static PerformanceCounter ramAvailable = new PerformanceCounter("Memory", "Available MBytes");
private static PerformanceCounter ramUsedPercent = new PerformanceCounter("Memory", "% Committed Bytes In Use");
private static Dictionary<string, SpriteFont> fonts = new Dictionary<string, SpriteFont>();
private static Dictionary<string, Texture2D> sprites = new Dictionary<string, Texture2D>();//, spriteOutlines = new Dictionary<string, Texture2D>(), spriteFills = new Dictionary<string, Texture2D>();
private static Dictionary<string, SoundEffectInstance> sounds = new Dictionary<string, SoundEffectInstance>();
private static Dictionary<string, SoundEffect> soundsRaw = new Dictionary<string, SoundEffect>();
private static Dictionary<string, Song> melodies = new Dictionary<string, Song>();
private static Dictionary<Song, string> melodyUniqueNames = new Dictionary<Song, string>();
private static Dictionary<string, bool> gates = new Dictionary<string, bool>();
private static Dictionary<string, int> gateEntriesCount = new Dictionary<string, int>(), timerRepeats = new Dictionary<string, int>();
private static Dictionary<string, string> clientIDs = new Dictionary<string, string>();
private static Dictionary<string, List<Body>> tagBodies = new Dictionary<string, List<Body>>();
private static Dictionary<string, float> signalEndTimes = new Dictionary<string, float>(), signalStartTimes = new Dictionary<string, float>(), signalDelays = new Dictionary<string, float>(), timerTickSeconds = new Dictionary<string, float>();
private static Dictionary<string, Timer> timers = new Dictionary<string, Timer>();
private static Dictionary<string, Signal> signals = new Dictionary<string, Signal>();
private static Dictionary<Body, float> bodyCameraDistances = new Dictionary<Body, float>(), bodyCameraAngle = new Dictionary<Body, float>(), bodyCameraAngleDifferences = new Dictionary<Body, float>();
private static Dictionary<string, List<string>> soundCollections = new Dictionary<string, List<string>>();
private static Dictionary<Body, bool> bodiesLastTickHovered = new Dictionary<Body, bool>(), bodiesClicked = new Dictionary<Body, bool>();
private static bool[] mouseButtonsLastFramePressed = new bool[3];
private static List<Key> keysPressed = new List<Key>(), lastFrameKeysPressed = new List<Key>();
private static List<Body> bodiesAll = new List<Body>();
private static List<float> tpsAverages = new List<float>(), fpsAverages = new List<float>();
private static List<string> clientUniqueNames = new List<string>();
private static int tick, frame, frameRendered, tpsAverageIndex, fpsAverageIndex, loadingPercent, loadingScreenUpdatePerFiles = 10, loadedFiles, contentFileCount, serverPort = 1234, eachTickLineCall;
private static bool textDisplayDraw, loading = true, pauseUnfocus, render, sleepPrevented, consoleShown, clientIsConnected, serverIsRunning, networkLogMessagesToConsole, windowIsDisplayed = true, muteMelody, muteSound;
private static float textDisplayScale, tps, tpsAverage, fps, fpsAverage, ticksDeltaTime, framesDeltaTime, time, cameraAngle;
private static string textDisplayFont, textDisplayMessage, mainDir = AppDomain.CurrentDomain.BaseDirectory, consoleLog, connectToServerInfo, clientUniqueName, userErrorMessage, melodyOverKey = ";;'gosak";
private static string contentLoadingInfo =
"1. In File Explorer: Add it to the 'Content' folder/sub-folder inside it.\n" +
"2. In Visual Studio's Solution Explorer: Add it to the according folder chosen above.\n" +
"3. In Visual Studio's Solution Explorer: Right click file -> Properties -> Copy to Output Directory='CopyAlways'.\n" +
"4. Open 'Content.mgcb' with the MonoGame Content Pipeline Tool.\n" +
"5. In MonoGame Content Pipeline Tool: Add the file/folder and build/rebuild it.\n\n" +
"Notes:\n" +
"The .mgcb project has to look like the 'Content' folder.";
private static DateTime lastTickTime, lastFrameTime;
private static Color backgroundColor = new Color(0, 0, 0);
private static Size canvasSize = new Size(1920, 1080), screenSize = new Size(GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width, GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height), pixelSize;
private static Point cameraPosition;
#endregion
public abstract class Instance : Game
{
[STAThread]
public static void Main()
{
using (var game = new Program())
{
program = game;
game.Run();
}
}
public Instance()
{
graphics = new GraphicsDeviceManager(this)
{
PreferredBackBufferWidth = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width,
PreferredBackBufferHeight = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height
};
Content.RootDirectory = "Content";
game = Create();
}
/// <summary>
/// - Example code setup:<br></br>
/// <paramref name="public"/> <paramref name="override"/> <see cref="Program"/> <typeparamref name="Create"/>() => <paramref name="this"/>;<br></br>
/// </summary>
public abstract Program Create();
/// <summary>
/// - Has to return a <see cref="string"/>[] containing <paramref name="folder"/>/<paramref name="name"/>.<paramref name="extension"/> for the small amount of content files that need to be loaded before the <typeparamref name="Loading"/> <typeparamref name="Screen"/> so they can be used during <see cref="EachLoadingScreenUpdate"/> while the rest of the content files are being loaded.<br></br>
/// - The <paramref name="folder"/> part of the path is skipped if the file is directly inside the Content folder.<br></br><br></br>
/// - Example code setup:<br></br>
/// // the following code pre-loads two files<br></br>
/// // the first with path: Content/folder/name.extension<br></br>
/// // the second with path: Content/name.extension<br></br>
/// <paramref name="public"/> <paramref name="override"/> <see cref="string"/>[] <typeparamref name="LoadingScreenPrepare"/>() => <paramref name="new"/> <see cref="string"/>[] { "<typeparamref name="folder"/>/<typeparamref name="name"/>.<typeparamref name="extension"/>", "<typeparamref name="name"/>.<typeparamref name="extension"/>" };<br></br>
/// </summary>
public virtual string[] LoadingScreenPrepare() => new string[0];
/// <summary>
/// - The place for the code that displays and updates the visuals of the <typeparamref name="Loading"/> <typeparamref name="Screen"/> with the small amount of content files loaded through <see cref="LoadingScreenPrepare"/>. The pre-loaded files can be used by each <see cref="Body"/>.<br></br>
/// - The <see cref="int"/> <paramref name="parameter"/> contains the loading %.
/// </summary>
public virtual void EachLoadingScreenUpdate(int percentLoaded) { }
/// <summary>
/// - The place for all program code.<br></br>
/// - The <see cref="int"/> <paramref name="parameter"/> contains the tick count.<br></br><br></br>
/// - The tick count and information about ticks/frames can be checked through <see cref="Performance.GetTickCount"/>.
/// </summary>
public abstract void EachTick(int tickCount);
public virtual void NetworkMessageJustReceived(string sender, string message) { }
public virtual void MouseJustInteractedWithHitbox(Body body, MouseHitboxInteraction interaction) { }
public virtual void UserJustInteractedWithKey(Key key, Interaction interaction) { }
public virtual void UserJustInteractedWithMouseButton(MouseButton button, Interaction interaction) { }
public virtual void BodyJustCollidedWithBody(Body bodyA, Body bodyB) { }
public virtual void MelodyJustEnded(string uniqueName) { }
public virtual void SignalJustOccurred(Signal signal) { }
public virtual void TimerTickJustOccurred(Timer timer) { }
protected override void Initialize()
{
spriteBatch = new SpriteBatch(game.GraphicsDevice);
graphics.PreferredBackBufferWidth = (int)screenSize.GetW();
graphics.PreferredBackBufferHeight = (int)screenSize.GetH();
graphics.HardwareModeSwitch = false;
graphics.IsFullScreen = true;
game.Window.Position = new Microsoft.Xna.Framework.Point(0, 0);
renderSamplerState = SamplerState.PointWrap;
renderTarget = new RenderTarget2D(game.GraphicsDevice, (int)screenSize.GetW(), (int)screenSize.GetH(), false, game.GraphicsDevice.PresentationParameters.BackBufferFormat, DepthFormat.Depth24);
Canvas.SetPixelSizeWH(1, 1);
graphics.ApplyChanges();
game.Window.Title = "Gear";
game.IsMouseVisible = true;
Debug.SetUserErrorMessage($"{Gear.Window.GetTitle()} encountered an error and will now exit. Please contact the developer to get the issue fixed.");
// start maximized
//var form = (Form)Control.FromHandle(Window.Handle);
//form.WindowState = FormWindowState.Maximized;
//anti pc sleep
SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS | EXECUTION_STATE.ES_DISPLAY_REQUIRED | EXECUTION_STATE.ES_SYSTEM_REQUIRED);
var content = program.LoadingScreenPrepare();
foreach (var file in content)
{
LoadFile(file);
}
CountContentFiles();
LoadAllContent();
base.Initialize();
}
protected override void Update(GameTime gameTime)
{
if (pauseUnfocus && game.IsActive == false)
{
return;
}
if (loading)
{
LoadAllContent();
program.EachLoadingScreenUpdate(loadingPercent);
}
else
{
tick++;
AdvanceTickTime();
UpdateKeys();
UpdateMouseButtons();
UpdateBodies();
UpdateSignalsAndTimers();
eachTickLineCall = Debug.GetCodeLine() + 1;
program.EachTick(tick);
}
base.Update(gameTime);
}
private static void AdvanceTickTime()
{
var delta = lastTickTime == default ? default : DateTime.Now - lastTickTime;
ticksDeltaTime = (float)delta.TotalSeconds;
tps = 60 / ((float)delta.TotalSeconds * 60);
tps = double.IsInfinity(tps) ? tpsAverage : tps;
AdvanceTPSAverage();
time += ticksDeltaTime;
lastTickTime = DateTime.Now;
}
private static void AdvanceTPSAverage()
{
if (tpsAverageIndex == 60)
{
tpsAverageIndex = 0;
}
if (tpsAverages.Contains(tps))
{
return;
}
if (tpsAverageIndex == tpsAverages.Count)
{
tpsAverages.Add(tps);
}
tpsAverages[tpsAverageIndex] = tps;
tpsAverage = tpsAverages.Average();
tpsAverageIndex++;
}
private static void UpdateKeys()
{
keysPressed.Clear();
var keyPresses = Keyboard.GetState().GetPressedKeys();
foreach (var key in keyPresses)
{
var gearKey = (Key)(int)key;
keysPressed.Add(gearKey);
if (lastFrameKeysPressed.Contains(gearKey) == false)
{
program.UserJustInteractedWithKey(gearKey, Interaction.Pressed);
}
}
foreach (var key in lastFrameKeysPressed)
{
if (keysPressed.Contains(key) == false)
{
program.UserJustInteractedWithKey(key, Interaction.Released);
}
}
lastFrameKeysPressed = new List<Key>(keysPressed);
}
private static void UpdateMouseButtons()
{
var pressed = new bool[3]
{
Input.LeftMouseButtonIsPressed(),
Input.MiddleMouseButtonIsPressed(),
Input.RightMouseButtonIsPressed()
};
for (int i = 0; i < 3; i++)
{
if (mouseButtonsLastFramePressed[i] == false && pressed[i])
{
program.UserJustInteractedWithMouseButton((MouseButton)i, Interaction.Pressed);
}
if (mouseButtonsLastFramePressed[i] && pressed[i] == false)
{
program.UserJustInteractedWithMouseButton((MouseButton)i, Interaction.Released);
}
}
for (int i = 0; i < 3; i++)
{
mouseButtonsLastFramePressed[i] = false;
}
mouseButtonsLastFramePressed = pressed;
}
private static void UpdateBodies()
{
var leftClick = Input.LeftMouseButtonIsPressed();
var justLeftClick = Gate.IsOpened("just-left-click", leftClick);
foreach (var body in bodiesAll)
{
var isHovered = body.IsIgnoringAllObstacles() == false && body.GetAllHitboxLines().Length > 2 &&
body.HitboxOverlapsPoint(Input.GetMouseCursorPosition());
var obstacles = body.GetObstacles();
foreach (var obstacle in obstacles)
{
if (Gate.IsOpened($"{body}-{obstacle}-collision", body.HitboxOverlapsObstacle(obstacle)))
{
program.BodyJustCollidedWithBody(body, obstacle);
}
}
if (bodiesLastTickHovered.ContainsKey(body) == false)
{
bodiesLastTickHovered.Add(body, false);
}
if (bodiesClicked.ContainsKey(body) == false)
{
bodiesClicked.Add(body, false);
}
if (Gate.IsOpened($"{body}-hover", isHovered))
{
program.MouseJustInteractedWithHitbox(body, MouseHitboxInteraction.Hovered);
}
if (Gate.IsOpened($"{body}-unhover", isHovered == false && bodiesLastTickHovered[body]))
{
program.MouseJustInteractedWithHitbox(body, MouseHitboxInteraction.Unhovered);
}
if (Gate.IsOpened($"{body}-click", isHovered && justLeftClick))
{
bodiesClicked[body] = true;
program.MouseJustInteractedWithHitbox(body, MouseHitboxInteraction.Clicked);
}
if (Gate.IsOpened($"{body}-click-released", isHovered && leftClick == false && bodiesClicked[body]))
{
program.MouseJustInteractedWithHitbox(body, MouseHitboxInteraction.ClickReleased);
}
bodiesLastTickHovered[body] = false;
if (isHovered)
{
bodiesLastTickHovered[body] = true;
}
}
if (leftClick == false)
{
bodiesClicked.Clear();
}
}
private static void UpdateSignalsAndTimers()
{
foreach (var kvp in signals)
{
var key = kvp.Key;
var signal = kvp.Value;
if (timerRepeats.ContainsKey(key)) continue;
if (SignalIsOccurring(key, true))
{
if (key == melodyOverKey)
{
program.MelodyJustEnded(melodyUniqueNames[MediaPlayer.Queue.ActiveSong]);
}
else
{
program.SignalJustOccurred(signal);
}
}
}
foreach (var kvp in timers)
{
var key = kvp.Key;
var timer = kvp.Value;
if (TimerTickIsOccurring(key, timerTickSeconds[key], timerRepeats[key]))
{
program.TimerTickJustOccurred(timer);
}
}
}
protected override void Draw(GameTime gameTime)
{
if (Gear.Window.IsDisplayed() == false) return;
frame++;
if (render == false) return;
frameRendered++;
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.NonPremultiplied, renderSamplerState, DepthStencilState.Default, RasterizerState.CullNone);
GraphicsDevice.SetRenderTarget(renderTarget);
GraphicsDevice.DepthStencilState = new DepthStencilState() { DepthBufferEnable = true };
GraphicsDevice.Clear(new Microsoft.Xna.Framework.Color((int)backgroundColor.GetR(), (int)backgroundColor.GetG(), (int)backgroundColor.GetB(), 255));
// draw =======================================================
AdvanceFrameTime();
DrawAllBodies();
DrawTextDisplay();
// draw =======================================================
GraphicsDevice.SetRenderTarget(null);
var scale = new Vector2(pixelSize.GetW(), pixelSize.GetH());
spriteBatch.Draw(renderTarget, Vector2.Zero, null, Microsoft.Xna.Framework.Color.White, 0, Vector2.Zero, scale, SpriteEffects.None, 0);
render = false;
spriteBatch.End();
base.Draw(gameTime);
}
private static void AdvanceFrameTime()
{
var delta = lastFrameTime == default ? default : DateTime.Now - lastFrameTime;
framesDeltaTime = (float)delta.TotalSeconds;
fps = 60 / ((float)delta.TotalSeconds * 60);
fps = double.IsInfinity(fps) ? fpsAverage : fps;
AdvanceFPSAverage();
lastFrameTime = DateTime.Now;
}
private static void AdvanceFPSAverage()
{
if (fpsAverageIndex == 60)
{
fpsAverageIndex = 0;
}
if (fpsAverages.Contains(fps))
{
return;
}
if (fpsAverageIndex == fpsAverages.Count)
{
fpsAverages.Add(fps);
}
fpsAverages[fpsAverageIndex] = fps;
fpsAverage = fpsAverages.Average();
fpsAverageIndex++;
}
private static void DrawAllBodies()
{
foreach (var body in bodiesAll)
{
var sprite = body.GetSpriteName();
var spriteShown = body.SpriteIsDisplayed();
var tileIndex = body.GetSpriteGridIndexes();
var cameraOffset = new Point(canvasSize.GetW() / 2, canvasSize.GetH() / 2);
var pos = GetCameraBodyPosition(body) + cameraOffset - Camera.GetPosition();
var size = body.GetSize();
var spritesize = body.GetSpriteSize();
var angle = Camera.GetAngle().GetA() + body.GetAngle().GetA();
var scale = size / spritesize;
var origin = body.GetSpriteOrigin();
var color = body.GetSpriteColor();
var boundariesSprite = new Texture2D(graphics.GraphicsDevice, 1, 1);
var originSprite = new Texture2D(graphics.GraphicsDevice, 1, 1);
var angleSprite = new Texture2D(graphics.GraphicsDevice, 1, 1);
var hitboxSprite = new Texture2D(graphics.GraphicsDevice, 1, 1);
var hitboxCrossPointsSprite = new Texture2D(graphics.GraphicsDevice, 1, 1);
var hitboxMiddlePointSprite = new Texture2D(graphics.GraphicsDevice, 1, 1);
var data = new Microsoft.Xna.Framework.Color[1] { Microsoft.Xna.Framework.Color.White };
boundariesSprite.SetData(data);
originSprite.SetData(data);
angleSprite.SetData(data);
hitboxSprite.SetData(data);
hitboxCrossPointsSprite.SetData(data);
hitboxMiddlePointSprite.SetData(data);
if (sprite != null && spriteShown)
{
DrawTile(sprites[sprite], pos, tileIndex, body.GetSpriteGridSize(), size / scale, origin, scale, color, angle, SpriteEffects.None);
}
var boundariesColor = body.GetSizeColor();
if (boundariesSprite != null && body.SizeIsDisplayed())
{
DrawTile(boundariesSprite, pos - origin, new Point(), 0, new Size(size.GetW(), 1), new Point(), new Size(), boundariesColor, angle, SpriteEffects.None);
DrawTile(boundariesSprite, pos - origin, new Point(), 0, new Size(1, size.GetH()), new Point(), new Size(), boundariesColor, angle, SpriteEffects.None);
}
var angleColor = body.GetAngleColor();
var angleWidth = body.GetAngleW();
if (angleSprite != null && body.AngleIsDisplayed())
{
DrawTile(angleSprite, pos, new Point(), 0, new Size(size.GetW() * 1.1f, angleWidth), new Point(), new Size(1, 1), angleColor, angle, SpriteEffects.None);
}
var originColor = body.GetOriginColor();
var originSize = body.GetOriginSize();
if (originSprite != null && body.OriginIsDisplayed())
{
DrawTile(originSprite, pos - new Point(originSize.GetW() / 2, originSize.GetH() / 2), new Point(), 0, originSize, new Point(), new Size(1, 1), originColor, 0, SpriteEffects.None);
}
var hitboxColor = body.GetHitboxColor();
var hitboxWidth = body.GetHitboxW();
var hitboxLinesCamera = new List<Line>();
if (hitboxSprite != null && body.HitboxIsDisplayed())
{
var lines = body.GetAllHitboxLines();
foreach (var line in lines)
{
var lineAngle = new Angle();
var dist = body.GetPosition().GetDistanceToPoint(line.GetStartPoint());
var dir = new Direction();
var camAng = Camera.GetAngle();
var ang = new Angle();
ang.SetFromBetweenPoints(body.GetPosition(), line.GetStartPoint());
ang += camAng;
dir.SetFromAngle(ang);
var linePos = GetCameraBodyPosition(body) + cameraOffset + dir.GetEndPoint() * dist - Camera.GetPosition();
lineAngle.SetFromBetweenPoints(line.GetStartPoint(), line.GetEndPoint());
var lineDir = new Direction();
lineDir.SetFromAngle(camAng + lineAngle);
var endPos = linePos + lineDir.GetEndPoint() * line.GetLength() - Camera.GetPosition();
hitboxLinesCamera.Add(new Line(linePos, endPos));
DrawTile(hitboxSprite, linePos - new Point(0, hitboxWidth / 2), new Point(), 0, new Size(1, 1), new Point(), new Size(line.GetLength(), hitboxWidth), hitboxColor, camAng.GetA() + lineAngle.GetA(), SpriteEffects.None);
}
}
var hitboxCrossPointsColor = body.GetHitboxCrossPointsColor();
var hitboxCrossPointsSize = body.GetHitboxCrossPointsSize();
if (hitboxCrossPointsSprite != null && body.HitboxCrossPointsAreDisplayed())
{
var crossPoints = body.GetAllHitboxCrossPoints();
foreach (var point in crossPoints)
{
DrawTile(hitboxCrossPointsSprite, point + cameraOffset - new Point(hitboxCrossPointsSize.GetW() / 2, hitboxCrossPointsSize.GetH() / 2), new Point(), 0, hitboxCrossPointsSize, new Point(), new Size(1, 1), hitboxCrossPointsColor, 0, SpriteEffects.None);
}
}
var hitboxMiddlePointColor = body.GetHitboxMiddlePointColor();
var hitboxMiddlePointSize = body.GetHitboxMiddlePointSize();
if (hitboxMiddlePointSprite != null && body.HitboxMiddlePointIsDisplayed())
{
var cameraMiddlePoint = new Point();
var middleDir = new Direction();
var middleAng = new Angle();
var middlePoint = body.GetHitboxMiddlePoint() + cameraOffset;
var bodyPos = body.GetPosition() + cameraOffset;
var dist = bodyPos.GetDistanceToPoint(middlePoint);
middleAng.SetFromBetweenPoints(bodyPos, middlePoint);
middleDir.SetFromAngle(middleAng + Camera.GetAngle());
cameraMiddlePoint = GetCameraBodyPosition(body) + cameraOffset + middleDir.GetEndPoint() * dist - Camera.GetPosition();
DrawTile(hitboxMiddlePointSprite, cameraMiddlePoint - new Point(hitboxMiddlePointSize.GetW() / 2, hitboxMiddlePointSize.GetH() / 2), new Point(), 0, hitboxMiddlePointSize, new Point(), new Size(1, 1), hitboxMiddlePointColor, 0, SpriteEffects.None);
}
boundariesSprite.Dispose();
angleSprite.Dispose();
originSprite.Dispose();
hitboxSprite.Dispose();
hitboxCrossPointsSprite.Dispose();
}
}
private static void DrawTextDisplay()
{
if (textDisplayFont != null && textDisplayDraw && fonts.ContainsKey(textDisplayFont) && string.IsNullOrWhiteSpace(textDisplayMessage) == false)
{
var fontsize = fonts[textDisplayFont].MeasureString("a") / 18 * textDisplayScale;
spriteBatch.DrawString(fonts[textDisplayFont], textDisplayMessage, new Vector2(fontsize.Y, fontsize.Y), Microsoft.Xna.Framework.Color.Black, 0, Vector2.Zero, textDisplayScale, SpriteEffects.None, 0);
spriteBatch.DrawString(fonts[textDisplayFont], textDisplayMessage, new Vector2(0, 0), Microsoft.Xna.Framework.Color.White, 0, Vector2.Zero, textDisplayScale, SpriteEffects.None, 0);
}
}
private static void CountContentFiles()
{
var directories = Directory.GetDirectories($"{mainDir}\\Content").ToList();
for (int i = 0; i < directories.Count; i++)
{
CountFolder(directories[i]);
}
if (CountFolder($"{mainDir}\\Content")) return;
loadingScreenUpdatePerFiles = (int)Math.Ceiling(contentFileCount / 10d);
}
private static bool CountFolder(string folder)
{
if (Directory.Exists(folder) == false)
{
return true;
}
var files = Directory.GetFiles(folder);
var datafiles = new List<string>();
var names = new List<string>();
for (int i = 0; i < files.Length; i++)
{
var path = files[i].Split('\\');
var name = path[path.Length - 1];
var pathIndex = path.Length - 1;
var directory = "";
while (true)
{
pathIndex--;
directory = $"{directory}{path[pathIndex]}";
if (path[pathIndex] == "Content") break;
directory = $"{directory}/";
}
name = name.Replace(".png", "");
name = name.Replace(".spritefont", "");
name = name.Replace(".wav", "");
name = name.Replace(".mp3", "");
if (names.Contains(name))
{
Error($"Description:\nAnother content file with the name '{name}' already exists in the '{directory}' directory.\n\n" +
$"Tip:\nMake sure that each file in the same directory has a unique name.", 5);
return true;
}
names.Add(name);
if (files[i].Contains(".png") || files[i].Contains(".spritefont") || files[i].Contains(".wav") || files[i].Contains(".mp3"))
{
datafiles.Add(files[i]);
}
}
contentFileCount += datafiles.Count;
var currentDirectories = Directory.GetDirectories(folder).ToList();
while (currentDirectories.Count > 0)
{
CountFolder(currentDirectories[0]);
currentDirectories.RemoveAt(0);
}
return false;
}
private static void LoadAllContent()
{
var directories = Directory.GetDirectories($"{mainDir}\\Content").ToList();
for (int i = 0; i < directories.Count; i++)
{
LoadFolder(directories[i]);
}
LoadFolder($"{mainDir}\\Content");
if (loadedFiles >= contentFileCount)
{
loading = false;
}
}
private static void LoadFolder(string folder)
{
if (Directory.Exists(folder) == false)
{
return;
}
var result = "";
var path = folder.Split('\\');
var adding = false;
for (int i = 0; i < path.Length; i++)
{
if (adding)
{
result = result.Insert(result.Length, path[i]);
if (i != path.Length - 1)
{
result = result.Insert(result.Length, "\\");
}
}
if (path[i] == "Content")
{
adding = true;
}
}
var files = Directory.GetFiles(folder);
for (int i = 0; i < files.Length; i++)
{
var split = files[i].Split('\\');
try
{
var loaded = LoadFile($"{result}\\{split[split.Length - 1]}");
if (loaded == false)
{
continue;
}
}
catch (Exception)
{
continue;
}
if (loadedFiles % loadingScreenUpdatePerFiles == 0)
{
goto end;
}
}
var currentDirectories = Directory.GetDirectories(folder).ToList();
while (currentDirectories.Count > 0)
{
LoadFolder(currentDirectories[0]);
currentDirectories.RemoveAt(0);
}
end:;
}
private static bool LoadFile(string name)
{
var split = name.Split('.');
var key = split[0];
key = key.Replace('\\', '/');
if (key[0] == '/')
{
key = key.Remove(0, 1);
}
if (sprites.ContainsKey(key) || fonts.ContainsKey(key) || sounds.ContainsKey(key) || melodies.ContainsKey(key))
{
return false;
}
switch (split[1])
{
case "png":
{
var sprite = game.Content.Load<Texture2D>(key);
sprites[key] = sprite;
/*
var filled = new Texture2D(graphics.GraphicsDevice, sprites[key].Width, sprites[key].Height);
var outline = new Texture2D(graphics.GraphicsDevice, sprites[key].Width, sprites[key].Height);
var outlineData = new Color[sprite.Width * sprite.Height];
var filledData = new Color[sprite.Width * sprite.Height];
var pixels = new Color[sprite.Width * sprite.Height];
sprite.GetData(pixels, 0, sprite.Width * sprite.Height);
for (int i = 0; i < sprite.Height * sprite.Width; i++)
{
if (TransparentPixelHasNeighbourOpaquePixel(pixels, i, sprite.Width, sprite.Height))
{
outlineData[i] = Color.White;
}
if (pixels[i] != Color.Transparent)
{
filledData[i] = Color.White;
}
}
outline.SetData(outlineData);
filled.SetData(filledData);
spriteOutlines[key] = outline;
spriteFills[key] = filled;
*/
break;
}
case "spritefont": fonts[key] = game.Content.Load<SpriteFont>(key); break;
case "wav":
{
soundsRaw[key] = game.Content.Load<SoundEffect>(key);
sounds[key] = soundsRaw[key].CreateInstance();
break;
}
case "mp3":
{
melodies[key] = game.Content.Load<Song>(key);
melodyUniqueNames[melodies[key]] = key;
break;
}
default: return false;
}
loadedFiles++;
loadingPercent = (int)((float)loadedFiles / contentFileCount * 100);
loadingPercent = loadingPercent > 100 ? 100 : loadingPercent;
return true;
/*
bool TransparentPixelHasNeighbourOpaquePixel(Color[] pixels, int i, int width, int height)
{
var y = i / height;
var x = i % width;
var xLeft = i - 1;
var xRight = i + 1;
var yUp = i - height;
var yDown = i + height;
if (pixels[i] == Color.Transparent)
{
if ((IndexIsOutOfBounds(x + 1, y - 1) == false && (pixels[xRight] != Color.Transparent || pixels[yUp] != Color.Transparent)) ||
(IndexIsOutOfBounds(x - 1, y + 1) == false && (pixels[xLeft] != Color.Transparent || pixels[yDown] != Color.Transparent)) ||
(IndexIsOutOfBounds(x + 1, y + 1) == false && (pixels[xRight] != Color.Transparent || pixels[yDown] != Color.Transparent)) ||
(IndexIsOutOfBounds(x - 1, y - 1) == false && (pixels[xLeft] != Color.Transparent || pixels[yUp] != Color.Transparent)))
{
return true;
}
}
return false;
bool IndexIsOutOfBounds(int k, int l)
{
if (k < 0 || k > width - 1 || l < 0 || l > height - 1)
{
return true;
}
return false;
}
}
*/
}
}
public static class Canvas
{
/// <summary>
/// - Smooths out the edges of the pixels according to the <paramref name="pixelfilter"/>. Higher filters apply better image quality but cost more performance.<br></br><br></br>- Pixel art projects go best with <see cref="PixelFilter.Lowest"/>.<br></br>- High resolution projects go best with the rest. <br></br><br></br>
/// - The current filter can be checked with <see cref="CanvasPixelFilterGet"/>.
/// </summary>
/// <param name="pixelfilter"></param>
public static void SetPixelFilter(CanvasPixelFilter pixelFilter)
{
renderPixelFilter = pixelFilter;
switch (renderPixelFilter)
{
case CanvasPixelFilter.Lowest: renderSamplerState = SamplerState.PointWrap; break;
case CanvasPixelFilter.Medium: renderSamplerState = SamplerState.LinearWrap; break;
case CanvasPixelFilter.Highest: renderSamplerState = SamplerState.AnisotropicWrap; break;
}
}
/// <summary>
/// - Gets the current pixel filter and returns it.<br></br><br></br>
/// - Pixel filters can be changed and researched through <see cref="CanvasPixelFilterGet"/>.
/// </summary>
public static CanvasPixelFilter GetPixelFilter()
{
return renderPixelFilter;
}
/// <summary>
/// - Sets the size of the displayed pixel relative to the user's monitor resolution. Each displayed pixel is equal to <paramref name="width"/> and <paramref name="height"/> of screen pixels.<br></br><br></br> - The canvas size can be checked with <see cref="SizeGetW"/> and <see cref="SizeGetH"/>.<br></br> - The user's screen size can be checked with <see cref="User.ScreenSizeGetW"/> and <see cref="User.ScreenSizeGetW"/>.
/// </summary>
private static void _SetPixelSize(Size size, int index, bool invalidSizeError = true)
{
var parameters = $"Parameters:\n" +
$"{nameof(size)} = {size}\n" +
$"{nameof(invalidSizeError)} = {invalidSizeError.ToString().ToLower()}";
if (size.GetW() < 1 || size.GetW() > screenSize.GetW() ||
size.GetH() < 1 || size.GetH() > screenSize.GetH())
{
if (invalidSizeError)
{
Error($"{parameters}\n\n{GetInvalidValueError("pixel size", $"{size}")}\n\nTip: Make sure the pixel size is between '{new Size(1, 1)}' and '{screenSize}'.", index + 1);
}
return;
}
size.SetWH(Number.GetLimited(size.GetW(), 1, screenSize.GetW()),
Number.GetLimited(size.GetH(), 1, (int)screenSize.GetH()));
pixelSize = size;
canvasSize = screenSize / size;
var gd = game.GraphicsDevice;
renderTarget = new RenderTarget2D(gd, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight, false, gd.PresentationParameters.BackBufferFormat, DepthFormat.Depth24);
graphics.ApplyChanges();
}
public static void SetPixelSize(Size size, bool invalidSizeError = true)
{
_SetPixelSize(size, 1, invalidSizeError);
}
public static void SetPixelSizeWH(float w, float h, bool invalidSizeError = true)
{
_SetPixelSize(new Size(w, h), 1, invalidSizeError);
}
public static void SetPixelSizeW(float w, bool invalidSizeError = true)
{
_SetPixelSize(new Size(w, pixelSize.GetH()), 1, invalidSizeError);
}
public static void SetPixelSizeH(float h, bool invalidSizeError = true)
{
_SetPixelSize(new Size(pixelSize.GetW(), h), 1, invalidSizeError);
}
public static Size GetPixelSize()
{
return pixelSize;
}
public static Size GetSize()
{
return canvasSize;
}
/// <summary>
/// - Sets the background color's hues to <paramref name="r"/>, <paramref name="g"/>, <paramref name="b"/>.<br></br><br></br>
/// - Those values must be between 0 and 255 inclusively.<br></br><br></br>
/// - Those hues can be checked through<br></br>
/// <see cref="BackgroundColorGetRed"/><br></br>
/// <see cref="BackgroundColorGetGren"/><br></br>
/// <see cref="BackgroundColorGetBlue"/><br></br>
/// </summary>
public static void SetBackgroundColor(float r, float g, float b)
{
backgroundColor = new Color(r, g, b);
}
public static Color GetBackgroundColor()
{
return backgroundColor;
}
}
public static class Window
{
/// <summary>
/// - Checks wether the window is currently focused by the user and returns the result.
/// </summary>
public static bool IsFocused()
{
return game.IsActive;
}
/// <summary>
/// - Pause is <paramref name="activated"/> when the user has the window unfocused or minimized.<br></br><br></br>
/// - A check wether this pause is activated can be done through <see cref="WindowUnfocusedPauseIsActivatedCheck"/>.<br></br><br></br>
/// - A check wether the user has focused the window can be done through <see cref="WindowIsFocusedCheck"/>.
/// </summary>
public static void PauseWhenUnfocused(bool pause)
{
pauseUnfocus = pause;
}
/// <summary>
/// - Checks if the window pause when unfocusing or minimizing the window is activated and returns the result.<br></br><br></br>
/// - The window pause can be activated or deactivated through <see cref="WindowUnfocusedPauseActivate"/>.<br></br><br></br>
/// - A check wether the user has focused the window can be done through <see cref="WindowIsFocusedCheck"/>.
/// </summary>
public static bool IsPausingWhenUnfocused()
{
return pauseUnfocus;
}
public static void Display(bool displayed)
{