-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Game.cs
967 lines (810 loc) · 29.3 KB
/
Game.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
#define DEBUG_LOGGING
using UnityEngine;
using System.Collections.Generic;
using Unity.Entities;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Experimental.Rendering.HDPipeline;
using System;
using System.Globalization;
using UnityEngine.Rendering.PostProcessing;
using SQP;
#if UNITY_EDITOR
using UnityEditor;
#endif
public struct GameTime
{
/// <summary>Number of ticks per second.</summary>
public int tickRate
{
get { return m_tickRate; }
set
{
m_tickRate = value;
tickInterval = 1.0f / m_tickRate;
}
}
/// <summary>Length of each world tick at current tickrate, e.g. 0.0166s if ticking at 60fps.</summary>
public float tickInterval { get; private set; } // Time between ticks
public int tick; // Current tick
public float tickDuration; // Duration of current tick
public GameTime(int tickRate)
{
this.m_tickRate = tickRate;
this.tickInterval = 1.0f / m_tickRate;
this.tick = 1;
this.tickDuration = 0;
}
public float TickDurationAsFraction
{
get { return tickDuration / tickInterval; }
}
public void SetTime(int tick, float tickDuration)
{
this.tick = tick;
this.tickDuration = tickDuration;
}
public float DurationSinceTick(int tick)
{
return (this.tick - tick) * tickInterval + tickDuration;
}
public void AddDuration(float duration)
{
tickDuration += duration;
int deltaTicks = Mathf.FloorToInt(tickDuration * (float)tickRate);
tick += deltaTicks;
tickDuration = tickDuration % tickInterval;
}
public static float GetDuration(GameTime start, GameTime end)
{
if(start.tickRate != end.tickRate)
{
GameDebug.LogError("Trying to compare time with different tick rates (" + start.tickRate + " and " + end.tickRate + ")");
return 0;
}
float result = (end.tick - start.tick) * start.tickInterval + end.tickDuration - start.tickDuration;
return result;
}
int m_tickRate;
}
public class EnumeratedArrayAttribute : PropertyAttribute
{
public readonly string[] names;
public EnumeratedArrayAttribute(Type enumtype)
{
names = Enum.GetNames(enumtype);
}
}
[DefaultExecutionOrder(-1000)]
public class Game : MonoBehaviour
{
public delegate void UpdateDelegate();
public WeakAssetReference movableBoxPrototype;
// Color scheme configurable? (cvars?)
public enum GameColor
{
Friend,
Enemy
}
[EnumeratedArray(typeof(GameColor))]
public Color[] gameColors;
public GameStatistics m_GameStatistics { get; private set; }
public static class Input
{
[Flags]
public enum Blocker
{
None = 0,
Console = 1,
Chat = 2,
Debug = 4,
}
static Blocker blocks;
public static void SetBlock(Blocker b, bool value)
{
if (value)
blocks |= b;
else
blocks &= ~b;
}
internal static float GetAxisRaw(string axis)
{
return blocks != Blocker.None ? 0.0f : UnityEngine.Input.GetAxisRaw(axis);
}
internal static bool GetKey(KeyCode key)
{
return blocks != Blocker.None ? false : UnityEngine.Input.GetKey(key);
}
internal static bool GetKeyDown(KeyCode key)
{
return blocks != Blocker.None ? false : UnityEngine.Input.GetKeyDown(key);
}
internal static bool GetMouseButton(int button)
{
return blocks != Blocker.None ? false : UnityEngine.Input.GetMouseButton(button);
}
internal static bool GetKeyUp(KeyCode key)
{
return blocks != Blocker.None ? false : UnityEngine.Input.GetKeyUp(key);
}
}
public interface IGameLoop
{
bool Init(string[] args);
void Shutdown();
void Update();
void FixedUpdate();
void LateUpdate();
}
public static Game game;
public event UpdateDelegate endUpdateEvent;
// Vars owned by server and replicated to clients
[ConfigVar(Name = "server.tickrate", DefaultValue = "60", Description = "Tickrate for server", Flags = ConfigVar.Flags.ServerInfo)]
public static ConfigVar serverTickRate;
[ConfigVar(Name = "config.fov", DefaultValue = "60", Description = "Field of view", Flags = ConfigVar.Flags.Save)]
public static ConfigVar configFov;
[ConfigVar(Name = "config.mousesensitivity", DefaultValue = "1.5", Description = "Mouse sensitivity", Flags = ConfigVar.Flags.Save)]
public static ConfigVar configMouseSensitivity;
[ConfigVar(Name = "config.inverty", DefaultValue = "0", Description = "Invert y mouse axis", Flags = ConfigVar.Flags.Save)]
public static ConfigVar configInvertY;
[ConfigVar(Name = "debug.catchloop", DefaultValue = "1", Description = "Catch exceptions in gameloop and pause game", Flags = ConfigVar.Flags.None)]
public static ConfigVar debugCatchLoop;
[ConfigVar(Name = "chartype", DefaultValue = "-1", Description = "Character to start with (-1 uses default character)")]
public static ConfigVar characterType;
[ConfigVar(Name = "allowcharchange", DefaultValue = "1", Description = "Is changing character allowed")]
public static ConfigVar allowCharChange;
[ConfigVar(Name = "debug.cpuprofile", DefaultValue = "0", Description = "Profile and dump cpu usage")]
public static ConfigVar debugCpuProfile;
[ConfigVar(Name = "net.dropevents", DefaultValue = "0", Description = "Drops a fraction of all packages containing events!!")]
public static ConfigVar netDropEvents;
static readonly string k_UserConfigFilename = "user.cfg";
public static readonly string k_BootConfigFilename = "boot.cfg";
public static GameConfiguration config;
public static InputSystem inputSystem;
public UnityEngine.Audio.AudioMixer audioMixer;
public SoundBank defaultBank;
public Camera bootCamera;
public LevelManager levelManager;
public SQPClient sqpClient;
public static double frameTime;
public static bool IsHeadless()
{
return game.m_isHeadless;
}
public static ISoundSystem SoundSystem
{
get { return game.m_SoundSystem; }
}
public static int GameLoopCount {
get { return game == null ? 0 : 1; }
}
public static T GetGameLoop<T>() where T : class
{
if (game == null)
return null;
foreach (var gameLoop in game.m_gameLoops)
{
T result = gameLoop as T;
if (result != null)
return result;
}
return null;
}
public static System.Diagnostics.Stopwatch Clock
{
get { return game.m_Clock; }
}
public string buildId
{
get { return _buildId; }
}
string _buildId = "NoBuild";
public void RequestGameLoop(System.Type type, string[] args)
{
GameDebug.Assert(typeof(IGameLoop).IsAssignableFrom(type));
m_RequestedGameLoopTypes.Add(type);
m_RequestedGameLoopArguments.Add(args);
GameDebug.Log("Game loop " + type + " requested");
}
// Pick argument for argument(!). Given list of args return null if option is
// not found. Return argument following option if found or empty string if none given.
// Options are expected to be prefixed with + or -
public static string ArgumentForOption(List<string> args, string option)
{
var idx = args.IndexOf(option);
if (idx < 0)
return null;
if (idx < args.Count - 1)
return args[idx + 1];
return "";
}
public void Awake()
{
GameDebug.Assert(game == null);
DontDestroyOnLoad(gameObject);
game = this;
m_StopwatchFrequency = System.Diagnostics.Stopwatch.Frequency;
m_Clock = new System.Diagnostics.Stopwatch();
m_Clock.Start();
var buildInfo = FindObjectOfType<BuildInfo>();
if (buildInfo != null)
_buildId = buildInfo.buildId;
var commandLineArgs = new List<string>(System.Environment.GetCommandLineArgs());
#if UNITY_STANDALONE_LINUX
m_isHeadless = true;
#else
m_isHeadless = commandLineArgs.Contains("-batchmode");
#endif
var consoleRestoreFocus = commandLineArgs.Contains("-consolerestorefocus");
if (m_isHeadless)
{
#if UNITY_STANDALONE_WIN
string consoleTitle;
var overrideTitle = ArgumentForOption(commandLineArgs, "-title");
if (overrideTitle != null)
consoleTitle = overrideTitle;
else
consoleTitle = Application.productName + " Console";
consoleTitle += " ["+System.Diagnostics.Process.GetCurrentProcess().Id+"]";
var consoleUI = new ConsoleTextWin(consoleTitle, consoleRestoreFocus);
#elif UNITY_STANDALONE_LINUX
var consoleUI = new ConsoleTextLinux();
#else
UnityEngine.Debug.Log("WARNING: starting without a console");
var consoleUI = new ConsoleNullUI();
#endif
Console.Init(consoleUI);
}
else
{
var consoleUI = Instantiate(Resources.Load<ConsoleGUI>("Prefabs/ConsoleGUI"));
DontDestroyOnLoad(consoleUI);
Console.Init(consoleUI);
m_DebugOverlay = Instantiate(Resources.Load<DebugOverlay>("DebugOverlay"));
DontDestroyOnLoad(m_DebugOverlay);
m_DebugOverlay.Init();
var hdpipe = RenderPipelineManager.currentPipeline as HDRenderPipeline;
if (hdpipe != null)
{
hdpipe.DebugLayer2DCallback = DebugOverlay.Render;
hdpipe.DebugLayer3DCallback = DebugOverlay.Render3D;
}
m_GameStatistics = new GameStatistics();
}
// If -logfile was passed, we try to put our own logs next to the engine's logfile
var engineLogFileLocation = ".";
var logfileArgIdx = commandLineArgs.IndexOf("-logfile");
if(logfileArgIdx >= 0 && commandLineArgs.Count >= logfileArgIdx)
{
engineLogFileLocation = System.IO.Path.GetDirectoryName(commandLineArgs[logfileArgIdx + 1]);
}
var logName = m_isHeadless ? "game_"+DateTime.UtcNow.ToString("yyyyMMdd_HHmmss_fff") : "game";
GameDebug.Init(engineLogFileLocation, logName);
ConfigVar.Init();
// Support -port and -query_port as per Multiplay standard
var serverPort = ArgumentForOption(commandLineArgs, "-port");
if (serverPort != null)
Console.EnqueueCommandNoHistory("server.port " + serverPort);
var sqpPort = ArgumentForOption(commandLineArgs, "-query_port");
if (sqpPort != null)
Console.EnqueueCommandNoHistory("server.sqp_port " + sqpPort);
Console.EnqueueCommandNoHistory("exec -s " + k_UserConfigFilename);
// Default is to allow no frame cap, i.e. as fast as possible if vsync is disabled
Application.targetFrameRate = -1;
if (m_isHeadless)
{
Application.targetFrameRate = serverTickRate.IntValue;
QualitySettings.vSyncCount = 0; // Needed to make targetFramerate work; even in headless mode
#if !UNITY_STANDALONE_LINUX
if (!commandLineArgs.Contains("-nographics"))
GameDebug.Log("WARNING: running -batchmod without -nographics");
#endif
}
else
{
RenderSettings.Init();
}
// Out of the box game behaviour is driven by boot.cfg unless you ask it not to
if(!commandLineArgs.Contains("-noboot"))
{
Console.EnqueueCommandNoHistory("exec -s " + k_BootConfigFilename);
}
if(m_isHeadless)
{
m_SoundSystem = new SoundSystemNull();
}
else
{
m_SoundSystem = new SoundSystem();
m_SoundSystem.Init(audioMixer);
m_SoundSystem.MountBank(defaultBank);
GameObject go = (GameObject)GameObject.Instantiate(Resources.Load("Prefabs/ClientFrontend", typeof(GameObject)));
UnityEngine.Object.DontDestroyOnLoad(go);
clientFrontend = go.GetComponentInChildren<ClientFrontend>();
}
sqpClient = new SQP.SQPClient();
GameDebug.Log("FPS Sample initialized");
#if UNITY_EDITOR
GameDebug.Log("Build type: editor");
#elif DEVELOPMENT_BUILD
GameDebug.Log("Build type: development");
#else
GameDebug.Log("Build type: release");
#endif
GameDebug.Log("BuildID: " + buildId);
GameDebug.Log("Cwd: " + System.IO.Directory.GetCurrentDirectory());
SimpleBundleManager.Init();
GameDebug.Log("SimpleBundleManager initialized");
levelManager = new LevelManager();
levelManager.Init();
GameDebug.Log("LevelManager initialized");
inputSystem = new InputSystem();
GameDebug.Log("InputSystem initialized");
// TODO (petera) added Instantiate here to avoid making changes to asset file.
// Feels like maybe SO is not really the right tool here.
config = Instantiate((GameConfiguration)Resources.Load("GameConfiguration"));
GameDebug.Log("Loaded game config");
// Game loops
Console.AddCommand("preview", CmdPreview, "Start preview mode");
Console.AddCommand("serve", CmdServe, "Start server listening");
Console.AddCommand("client", CmdClient, "client: Enter client mode.");
Console.AddCommand("thinclient", CmdThinClient, "client: Enter thin client mode.");
Console.AddCommand("boot", CmdBoot, "Go back to boot loop");
Console.AddCommand("connect", CmdConnect, "connect <ip>: Connect to server on ip (default: localhost)");
Console.AddCommand("menu", CmdMenu, "show the main menu");
Console.AddCommand("load", CmdLoad, "Load level");
Console.AddCommand("quit", CmdQuit, "Quits");
Console.AddCommand("screenshot", CmdScreenshot, "Capture screenshot. Optional argument is destination folder or filename.");
Console.AddCommand("crashme", (string[] args) => { GameDebug.Assert(false); }, "Crashes the game next frame ");
Console.AddCommand("saveconfig", CmdSaveConfig, "Save the user config variables");
Console.AddCommand("loadconfig", CmdLoadConfig, "Load the user config variables");
#if UNITY_STANDALONE_WIN
Console.AddCommand("windowpos", CmdWindowPosition, "Position of window. e.g. windowpos 100,100");
#endif
Console.SetOpen(true);
Console.ProcessCommandLineArguments(commandLineArgs.ToArray());
PushCamera(bootCamera);
}
public Camera TopCamera()
{
var c = m_CameraStack.Count;
return c == 0 ? null : m_CameraStack[c - 1];
}
public void PushCamera(Camera cam)
{
if (m_CameraStack.Count > 0)
SetCameraEnabled(m_CameraStack[m_CameraStack.Count - 1],false);
m_CameraStack.Add(cam);
SetCameraEnabled(cam,true);
m_ExposureReleaseCount = 10;
}
public void BlackFade(bool enabled)
{
if(m_Exposure != null)
m_Exposure.active = enabled;
}
public void PopCamera(Camera cam)
{
GameDebug.Assert(m_CameraStack.Count > 1, "Trying to pop last camera off stack!");
GameDebug.Assert(cam == m_CameraStack[m_CameraStack.Count - 1]);
if(cam != null)
SetCameraEnabled(cam,false);
m_CameraStack.RemoveAt(m_CameraStack.Count - 1);
SetCameraEnabled(m_CameraStack[m_CameraStack.Count - 1],true);
}
void SetCameraEnabled(Camera cam, bool enabled)
{
if (enabled)
RenderSettings.UpdateCameraSettings(cam);
cam.enabled = enabled;
var audioListener = cam.GetComponent<AudioListener>();
if(audioListener != null)
{
audioListener.enabled = enabled;
if(SoundSystem != null)
SoundSystem.SetCurrentListener(enabled ? audioListener : null);
}
}
void OnDestroy()
{
GameDebug.Shutdown();
Console.Shutdown();
if (m_DebugOverlay != null)
m_DebugOverlay.Shutdown();
}
bool pipeSetup = false;
public void Update()
{
if (!m_isHeadless)
RenderSettings.Update();
// TODO (petera) remove this hack once we know exactly when renderer is available...
if (!pipeSetup)
{
var hdpipe = RenderPipelineManager.currentPipeline as HDRenderPipeline;
if (hdpipe != null)
{
hdpipe.DebugLayer2DCallback = DebugOverlay.Render;
hdpipe.DebugLayer3DCallback = DebugOverlay.Render3D;
var layer = LayerMask.NameToLayer("PostProcess Volumes");
if (layer == -1)
GameDebug.LogWarning("Unable to find layer mask for camera fader");
else
{
m_Exposure = ScriptableObject.CreateInstance<AutoExposure>();
m_Exposure.active = false;
m_Exposure.enabled.Override(true);
m_Exposure.keyValue.Override(0);
m_ExposureVolume = PostProcessManager.instance.QuickVolume(layer, 100.0f, m_Exposure);
}
pipeSetup = true;
}
}
if(m_ExposureReleaseCount > 0)
{
m_ExposureReleaseCount--;
if (m_ExposureReleaseCount == 0)
BlackFade(false);
}
// Verify if camera was somehow destroyed and pop it
if(m_CameraStack.Count > 1 && m_CameraStack[m_CameraStack.Count-1] == null)
{
PopCamera(null);
}
#if UNITY_EDITOR
// Ugly hack to force focus to game view when using scriptable renderloops.
if (Time.frameCount < 4)
{
try
{
var gameViewType = typeof(UnityEditor.EditorWindow).Assembly.GetType("UnityEditor.GameView");
var gameView = (EditorWindow)Resources.FindObjectsOfTypeAll(gameViewType)[0];
gameView.Focus();
}
catch (System.Exception) { /* too bad */ }
}
#endif
frameTime = (double)m_Clock.ElapsedTicks / m_StopwatchFrequency;
// Switch game loop if needed
if (m_RequestedGameLoopTypes.Count > 0)
{
// Multiple running gameloops only allowed in editor
#if !UNITY_EDITOR
ShutdownGameLoops();
#endif
bool initSucceeded = false;
for(int i=0;i<m_RequestedGameLoopTypes.Count;i++)
{
try
{
IGameLoop gameLoop = (IGameLoop)System.Activator.CreateInstance(m_RequestedGameLoopTypes[i]);
initSucceeded = gameLoop.Init(m_RequestedGameLoopArguments[i]);
if (!initSucceeded)
break;
m_gameLoops.Add(gameLoop);
}
catch (System.Exception e)
{
GameDebug.Log(string.Format("Game loop initialization threw exception : ({0})\n{1}", e.Message, e.StackTrace));
}
}
if (!initSucceeded)
{
ShutdownGameLoops();
GameDebug.Log("Game loop initialization failed ... reverting to boot loop");
}
m_RequestedGameLoopTypes.Clear();
m_RequestedGameLoopArguments.Clear();
}
try
{
if (!m_ErrorState)
{
foreach (var gameLoop in m_gameLoops)
{
gameLoop.Update();
}
levelManager.Update();
}
}
catch (System.Exception e)
{
HandleGameloopException(e);
throw;
}
if (m_SoundSystem != null)
m_SoundSystem.Update();
if (clientFrontend != null)
clientFrontend.UpdateGame();
Console.ConsoleUpdate();
WindowFocusUpdate();
UpdateCPUStats();
sqpClient.Update();
endUpdateEvent?.Invoke();
}
bool m_ErrorState;
public void FixedUpdate()
{
foreach (var gameLoop in m_gameLoops)
{
gameLoop.FixedUpdate();
}
}
public void LateUpdate()
{
try
{
if (!m_ErrorState)
{
foreach (var gameLoop in m_gameLoops)
{
gameLoop.LateUpdate();
}
Console.ConsoleLateUpdate();
}
}
catch (System.Exception e)
{
HandleGameloopException(e);
throw;
}
if (m_GameStatistics != null)
m_GameStatistics.TickLateUpdate();
if (m_DebugOverlay != null)
m_DebugOverlay.TickLateUpdate();
}
void OnApplicationQuit()
{
#if !UNITY_EDITOR && UNITY_STANDALONE_WIN
GameDebug.Log("Farewell, cruel world...");
System.Diagnostics.Process.GetCurrentProcess().Kill();
#endif
ShutdownGameLoops();
}
float m_NextCpuProfileTime = 0;
double m_LastCpuUsage = 0;
double m_LastCpuUsageUser = 0;
void UpdateCPUStats()
{
if(debugCpuProfile.IntValue > 0)
{
if(Time.time > m_NextCpuProfileTime)
{
const float interval = 5.0f;
m_NextCpuProfileTime = Time.time + interval;
var process = System.Diagnostics.Process.GetCurrentProcess();
var user = process.UserProcessorTime.TotalMilliseconds;
var total = process.TotalProcessorTime.TotalMilliseconds;
float userUsagePct = (float)(user - m_LastCpuUsageUser) / 10.0f / interval;
float totalUsagePct = (float)(total- m_LastCpuUsage) / 10.0f / interval;
m_LastCpuUsage = total;
m_LastCpuUsageUser = user;
GameDebug.Log(string.Format("CPU Usage {0}% (user: {1}%)", totalUsagePct, userUsagePct));
}
}
}
public void LoadLevel(string levelname)
{
if (!Game.game.levelManager.CanLoadLevel(levelname))
{
GameDebug.Log("ERROR : Cannot load level : " + levelname);
return;
}
Game.game.levelManager.LoadLevel(levelname);
}
void UnloadLevel()
{
// TODO
}
void HandleGameloopException(System.Exception e)
{
if (debugCatchLoop.IntValue > 0)
{
GameDebug.Log("EXCEPTION " + e.Message + "\n" + e.StackTrace);
Console.SetOpen(true);
m_ErrorState = true;
}
}
string FindNewFilename(string pattern)
{
for(var i = 0; i < 10000; i++)
{
var f = string.Format(pattern, i);
if (System.IO.File.Exists(string.Format(pattern, i)))
continue;
return f;
}
return null;
}
void ShutdownGameLoops()
{
foreach (var gameLoop in m_gameLoops)
gameLoop.Shutdown();
m_gameLoops.Clear();
}
void CmdPreview(string[] args)
{
RequestGameLoop(typeof(PreviewGameLoop), args);
Console.s_PendingCommandsWaitForFrames = 1;
}
void CmdServe(string[] args)
{
RequestGameLoop( typeof(ServerGameLoop) , args);
Console.s_PendingCommandsWaitForFrames = 1;
}
void CmdLoad(string[] args)
{
LoadLevel(args[0]);
Console.SetOpen(false);
}
void CmdBoot(string[] args)
{
clientFrontend.ShowMenu(ClientFrontend.MenuShowing.None);
levelManager.UnloadLevel();
ShutdownGameLoops();
Console.s_PendingCommandsWaitForFrames = 1;
Console.SetOpen(true);
}
void CmdClient(string[] args)
{
RequestGameLoop( typeof(ClientGameLoop), args);
Console.s_PendingCommandsWaitForFrames = 1;
}
void CmdConnect(string[] args)
{
// Special hack to allow "connect a.b.c.d" as shorthand
if (m_gameLoops.Count == 0)
{
RequestGameLoop( typeof(ClientGameLoop), args);
Console.s_PendingCommandsWaitForFrames = 1;
return;
}
ClientGameLoop clientGameLoop = GetGameLoop<ClientGameLoop>();
ThinClientGameLoop thinClientGameLoop = GetGameLoop<ThinClientGameLoop>();
if (clientGameLoop != null)
clientGameLoop.CmdConnect(args);
else if (thinClientGameLoop != null)
thinClientGameLoop.CmdConnect(args);
else
GameDebug.Log("Cannot connect from current gamemode");
}
void CmdThinClient(string[] args)
{
RequestGameLoop( typeof(ThinClientGameLoop), args);
Console.s_PendingCommandsWaitForFrames = 1;
}
void CmdQuit(string[] args)
{
#if UNITY_EDITOR
EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
void CmdScreenshot(string[] arguments)
{
string filename = null;
var root = System.IO.Path.GetFullPath(".");
if (arguments.Length == 0)
filename = FindNewFilename(root+"/screenshot{0}.png");
else if (arguments.Length == 1)
{
var a = arguments[0];
if (System.IO.Directory.Exists(a))
filename = FindNewFilename(a + "/screenshot{0}.png");
else if (!System.IO.File.Exists(a))
filename = a;
else
{
Console.Write("File " + a + " already exists");
return;
}
}
if (filename != null)
{
GameDebug.Log("Saving screenshot to " + filename);
Console.SetOpen(false);
ScreenCapture.CaptureScreenshot(filename);
}
}
public ClientFrontend clientFrontend;
private void CmdMenu(string[] args)
{
float fadeTime = 0.0f;
ClientFrontend.MenuShowing show = ClientFrontend.MenuShowing.Main;
if(args.Length > 0)
{
if (args[0] == "0")
show = ClientFrontend.MenuShowing.None;
else if (args[0] == "2")
show = ClientFrontend.MenuShowing.Ingame;
}
if(args.Length > 1)
{
float.TryParse(args[1], NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out fadeTime);
}
clientFrontend.ShowMenu(show, fadeTime);
Console.SetOpen(false);
}
void CmdSaveConfig(string[] arguments)
{
ConfigVar.Save(k_UserConfigFilename);
}
void CmdLoadConfig(string[] arguments)
{
Console.EnqueueCommandNoHistory("exec " + k_UserConfigFilename);
}
#if UNITY_STANDALONE_WIN
void CmdWindowPosition(string[] arguments)
{
if (arguments.Length == 1)
{
string[] cords = arguments[0].Split(',');
if (cords.Length == 2)
{
int x, y;
var xParsed = int.TryParse(cords[0], out x);
var yParsed = int.TryParse(cords[1], out y);
if (xParsed && yParsed)
{
WindowsUtil.SetWindowPosition(x, y);
return;
}
}
}
Console.Write("Usage: windowpos <x,y>");
}
#endif
public static void RequestMousePointerLock()
{
s_bMouseLockFrameNo = Time.frameCount + 1;
}
public static void SetMousePointerLock(bool locked)
{
Cursor.lockState = locked ? CursorLockMode.Locked : CursorLockMode.None;
Cursor.visible = !locked;
s_bMouseLockFrameNo = Time.frameCount; // prevent default handling in WindowFocusUpdate overriding requests
}
public static bool GetMousePointerLock()
{
return Cursor.lockState == CursorLockMode.Locked;
}
void WindowFocusUpdate()
{
bool menusShowing = (clientFrontend != null && clientFrontend.menuShowing != ClientFrontend.MenuShowing.None);
bool lockWhenClicked = !menusShowing && !Console.IsOpen();
if(s_bMouseLockFrameNo == Time.frameCount)
{
SetMousePointerLock(true);
return;
}
if (lockWhenClicked)
{
// Default behaviour when no menus or anything. Catch mouse on click, release on escape.
if (UnityEngine.Input.GetMouseButtonUp(0) && !GetMousePointerLock())
SetMousePointerLock(true);
if (UnityEngine.Input.GetKeyUp(KeyCode.Escape) && GetMousePointerLock())
SetMousePointerLock(false);
}
else
{
// When menu or console open, release lock
if (GetMousePointerLock())
{
SetMousePointerLock(false);
}
}
}
List<Type> m_RequestedGameLoopTypes = new List<System.Type>();
private List<string[]> m_RequestedGameLoopArguments = new List<string[]>();
// Global camera handling
List<Camera> m_CameraStack = new List<Camera>();
AutoExposure m_Exposure;
PostProcessVolume m_ExposureVolume;
int m_ExposureReleaseCount;
List<IGameLoop> m_gameLoops = new List<IGameLoop>();
DebugOverlay m_DebugOverlay;
ISoundSystem m_SoundSystem;
bool m_isHeadless;
long m_StopwatchFrequency;
System.Diagnostics.Stopwatch m_Clock;
static int s_bMouseLockFrameNo;
}