-
Notifications
You must be signed in to change notification settings - Fork 1
/
App.xaml.cs
634 lines (594 loc) · 27.1 KB
/
App.xaml.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
using Serilog;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Media;
using Microsoft.Win32;
using The_Ezio_Trilogy_Launcher.Classes;
namespace The_Ezio_Trilogy_Launcher
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : System.Windows.Application
{
// This is needed for Console to show up when using argument -console
[DllImport("Kernel32")]
public static extern void AllocConsole();
[DllImport("Kernel32")]
public static extern void FreeConsole();
private bool logging = false;
// Used to detect refresh Rate
[DllImport("user32.dll")]
private static extern int EnumDisplaySettings(string? deviceName, int modeNum, ref DEVMODE devMode);
// Used to detect "Saved Games" Folder
[DllImport("shell32.dll")]
private static extern int SHGetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags, IntPtr hToken, out IntPtr pszPath);
[StructLayout(LayoutKind.Sequential)]
private struct DEVMODE
{
private const int CCHDEVICENAME = 32;
private const int CCHFORMNAME = 32;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCHDEVICENAME)]
public string dmDeviceName;
public short dmSpecVersion;
public short dmDriverVersion;
public short dmSize;
public short dmDriverExtra;
public int dmFields;
public int dmPositionX;
public int dmPositionY;
public int dmDisplayOrientation;
public int dmDisplayFixedOutput;
public short dmColor;
public short dmDuplex;
public short dmYResolution;
public short dmTTOption;
public short dmCollate;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCHFORMNAME)]
public string dmFormName;
public short dmLogPixels;
public int dmBitsPerPel;
public int dmPelsWidth;
public int dmPelsHeight;
public int dmDisplayFlags;
public int dmDisplayFrequency;
}
private bool start = true;
/// <summary>
/// Stores how many Cores the CPU has
/// </summary>
public static int NumberOfCores { get; set; }
/// <summary>
/// Stores how many Threads the CPU has
/// </summary>
public static int NumberOfThreads { get; set; }
/// <summary>
/// Path to Assassin's Creed 2 installation folder
/// </summary>
public static string? AC2Path { get; set; }
/// <summary>
/// Path to Assassin's Creed:Brotherhood installation folder
/// </summary>
public static string? ACBPath { get; set; }
/// <summary>
/// Path to Assassin's Creed:Revelations installation folder
/// </summary>
public static string? ACRPath { get; set; }
/// <summary>
/// True if uMod is enabled
/// False if uMod is disabled
/// </summary>
public static bool AC2uModStatus = false;
/// <summary>
/// True if uMod is enabled
/// False if uMod is disabled
/// </summary>
public static bool ACBuModStatus = false;
/// <summary>
/// List of supported Resolutions by users Monitor
/// </summary>
public static List<Resolution> compatibleResolutions = new List<Resolution>();
/// <summary>
/// List of supported Refresh Rates by users Monitor
/// </summary>
public static List<int> compatibleRefreshRates = new List<int>();
/// <summary>
/// Monitor's Refresh Rate
/// </summary>
public static double RefreshRate { get; set; }
/// <summary>
/// Sets the process affinity according to the number of cores/threads in the PC
/// </summary>
public static AffinityManager ProcessAffinityManager { get; } = new AffinityManager();
/// <summary>
/// Used for DiscordRPC
/// </summary>
public static DiscordRPCManager discordRPCManager = new DiscordRPCManager();
/// <summary>
/// Stores Saved Games Path
/// </summary>
public static string? SavedGamesFolderPath { get; set; }
public App()
{
InitializeComponent();
}
// Misc
/// <summary>
/// Grabs all of the game installations paths
/// </summary>
private async Task FindGameInstallations()
{
try
{
Log.Information("Grabbing all of the paths to game installations");
// Checks if launcher's folder exists
if (System.IO.Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments) + @"\Assassin's Creed - The Ezio Trilogy Remastered"))
{
// Checks if there's something in launchers folder
if (System.IO.Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments) + @"\Assassin's Creed - The Ezio Trilogy Remastered").Count() > 0)
{
// For every file in launchers folder
foreach (string path in System.IO.Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments) + @"\Assassin's Creed - The Ezio Trilogy Remastered"))
{
FileInfo fileInfo = new FileInfo(path);
// If it's AC2Path.txt then it adds the path inside of it to AC2Path variable
if (fileInfo.Name == "AC2Path.txt")
{
Log.Information("Assassin's Creed 2 is installed.");
using (StreamReader sr = new StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments) + @"\Assassin's Creed - The Ezio Trilogy Remastered\" + fileInfo.Name))
{
AC2Path = sr.ReadLine();
Log.Information($"Assassin's Creed 2 Installation Path: {AC2Path}");
}
}
// If it's ACBPath.txt then it adds the path inside of it to ACBPath variable
else if (fileInfo.Name == "ACBPath.txt")
{
Log.Information("Assassin's Creed Brotherhood is installed.");
using (StreamReader sr = new StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments) + @"\Assassin's Creed - The Ezio Trilogy Remastered\" + fileInfo.Name))
{
ACBPath = sr.ReadLine();
Log.Information($"Assassin's Creed Brotherhood Installation Path: {ACBPath}");
}
}
// If it's ACRPath.txt then it adds the path inside of it to ACRPath variable
else if (fileInfo.Name == "ACRPath.txt")
{
Log.Information("Assassin's Creed Revelations is installed.");
using (StreamReader sr = new StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments) + @"\Assassin's Creed - The Ezio Trilogy Remastered\" + fileInfo.Name))
{
ACRPath = sr.ReadLine();
Log.Information($"Assassin's Creed Revelations Installation Path: {ACRPath}");
}
}
}
}
}
await Task.Delay(1);
}
catch (Exception ex)
{
Log.Error(ex, "");
}
}
/// <summary>
/// Finds Core Count of the CPU. Needed for a tweak to fix the stutters via Affinity
/// </summary>
private async Task FindNumberOfCores()
{
try
{
Log.Information("Trying to find number of Cores and Threads of this PC");
// Create a query to get information about the processor.
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Processor");
// Create a ManagementObjectSearcher to execute the query.
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
// Get the collection of management objects.
ManagementObjectCollection queryCollection = searcher.Get();
foreach (ManagementObject m in queryCollection)
{
NumberOfCores = int.Parse(m["NumberOfCores"].ToString());
NumberOfThreads = int.Parse(m["NumberOfLogicalProcessors"].ToString());
Log.Information($"Number of Cores: {NumberOfCores}");
Log.Information($"Number of Threads: {NumberOfThreads}");
}
await Task.Delay(1);
}
catch (Exception ex)
{
Log.Error(ex, "Error:");
}
}
/// <summary>
/// Finds all of the resolutions supported by the users monitor.
/// </summary>
private async Task FindSupportedResolutions()
{
try
{
// This has every supported resolution for the current screen where the launcher is loading
Screen[] allScreens = Screen.AllScreens;
int resolutionWidth = 0;
int resolutionHeight = 0;
foreach (Screen screen in allScreens)
{
if (resolutionWidth < screen.Bounds.Width)
{
resolutionWidth = screen.Bounds.Width;
resolutionHeight = screen.Bounds.Height;
};
}
Log.Information($"Monitors Resolution: {resolutionWidth}x{resolutionHeight}");
// Adding all of the resolutions supported by the game and the monitor to a List
using (StreamReader sr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("The_Ezio_Trilogy_Launcher.Assets.ListofSupportedResolutions.txt")))
{
string? line = sr.ReadLine();
while (line != null)
{
string[] splitLine = line.Split('x');
if (double.Parse(splitLine[0]) < resolutionWidth && double.Parse(splitLine[1]) < resolutionHeight)
{
Resolution newRes = new Resolution();
newRes.Res = line;
newRes.Width = double.Parse(splitLine[0]);
newRes.Height = double.Parse(splitLine[1]);
compatibleResolutions.Add(newRes);
}
else if (double.Parse(splitLine[0]) == resolutionWidth && double.Parse(splitLine[1]) == resolutionHeight)
{
Resolution newRes = new Resolution();
newRes.Res = line;
newRes.Width = double.Parse(splitLine[0]);
newRes.Height = double.Parse(splitLine[1]);
compatibleResolutions.Add(newRes);
break;
}
line = sr.ReadLine();
}
}
await Task.Delay(1);
}
catch (Exception ex)
{
Log.Error(ex, "");
}
}
/// <summary>
/// Detects the Refresh Rate of the monitor
/// </summary>
private async Task FindRefreshRate()
{
try
{
RefreshRate = 0;
DEVMODE dm = new DEVMODE();
dm.dmSize = (short)Marshal.SizeOf(typeof(DEVMODE));
if (EnumDisplaySettings(null, -1, ref dm) != 0)
{
RefreshRate = dm.dmDisplayFrequency;
}
// Adds all of the supported refresh rates to a List
using (StreamReader sr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("The_Ezio_Trilogy_Launcher.Assets.ListOfSupportedRefreshRates.txt")))
{
string? line = sr.ReadLine();
while (line != null)
{
if (RefreshRate > double.Parse(line))
{
compatibleRefreshRates.Add(int.Parse(line));
}
else if (RefreshRate == double.Parse(line))
{
compatibleRefreshRates.Add(int.Parse(line));
break;
}
line = sr.ReadLine();
}
}
await Task.Delay(1);
Log.Information($"Monitor's Refresh Rate: {RefreshRate}");
}
catch (Exception ex)
{
Log.Error(ex, "");
}
}
/// <summary>
/// Finds Saved Games Folder
/// </summary>
/// <returns></returns>
private async Task FindSavedGamesFolder()
{
try
{
IntPtr pathPtr;
int result = SHGetKnownFolderPath(new Guid("4C5C32FF-BB9D-43b0-B5B4-2D72E54EAAA4"), 0, IntPtr.Zero, out pathPtr);
if (result >= 0)
{
SavedGamesFolderPath = Marshal.PtrToStringUni(pathPtr);
Marshal.FreeCoTaskMem(pathPtr);
Log.Information("Saved Games folder path: " + SavedGamesFolderPath);
}
else
{
Log.Information("Failed to retrieve the Saved Games folder path.");
Log.Information("Using alternative method");
if ((string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders", "{4C5C32FF-BB9D-43B0-B5B4-2D72E54EAAA4}", null) != null)
{
SavedGamesFolderPath = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders", "{4C5C32FF-BB9D-43B0-B5B4-2D72E54EAAA4}", null);
Log.Information("Saved Games folder path: " + SavedGamesFolderPath);
}
else
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"))
{
if (key != null)
{
string[] valueNames = key.GetValueNames();
foreach (string valueName in valueNames)
{
string value = (string)key.GetValue(valueName);
if (value != null && value.EndsWith("Saved Games", StringComparison.OrdinalIgnoreCase))
{
SavedGamesFolderPath = (string)key.GetValue(valueName);
Log.Information("Saved Games folder path: " + SavedGamesFolderPath);
}
}
}
}
}
}
if (SavedGamesFolderPath != null)
{
SavedGamesFolderPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)), @"Saved Games\");
}
await Task.Delay(1);
}
catch (Exception ex)
{
Log.Error(ex, "");
System.Windows.MessageBox.Show(ex.Message);
}
}
/// <summary>
/// Checks if uMod is enabled or disabled.
/// </summary>
private async Task uModStatus()
{
try
{
// AC2
Log.Information("Checking if uMod is enabled for Assassin's Creed 2");
if (System.IO.File.Exists(AC2Path + @"\uMod\Status.txt"))
{
string[] statusFile = File.ReadAllLines(AC2Path + @"\uMod\Status.txt");
foreach (string status in statusFile)
{
if (status.StartsWith("Enabled"))
{
string[] splitLine = status.Split('=');
if (int.Parse(splitLine[1]) == 1)
{
Log.Information("uMod is enabled for Assassin's Creed 2");
AC2uModStatus = true;
}
else
{
Log.Information("uMod is disabled for Assassin's Creed 2");
AC2uModStatus = false;
}
}
}
}
// ACB
Log.Information("Checking if uMod is enabled for Assassin's Creed Brotherhood");
if (System.IO.File.Exists(ACBPath + @"\uMod\Status.txt"))
{
string[] statusFile = System.IO.File.ReadAllLines(ACBPath + @"\uMod\Status.txt");
foreach (string status in statusFile)
{
if (status.StartsWith("Enabled"))
{
string[] splitLine = status.Split('=');
if (int.Parse(splitLine[1]) == 1)
{
Log.Information("uMod is enabled for Assassin's Creed Brotherhood");
ACBuModStatus = true;
}
else
{
Log.Information("uMod is disabled for Assassin's Creed Brotherhood");
ACBuModStatus = false;
}
}
}
}
GC.Collect();
await Task.Delay(1);
}
catch (Exception ex)
{
Log.Error(ex, "");
System.Windows.MessageBox.Show(ex.Message);
}
}
/// <summary>
/// Starts the game
/// </summary>
/// <param name="executableName">Name of the executable</param>
/// <param name="workingDirectory">Directory where the game is</param>
/// <param name="uMod">Does the game use uMod</param>
/// <returns></returns>
public async Task StartGame(string executableName, string? workingDirectory, bool uMod, bool skipLauncher=false)
{
try
{
Process[] gameProcesses = Process.GetProcessesByName(executableName);
if (gameProcesses.Length <= 0)
{
Process gameProcess = new Process();
gameProcess.StartInfo.WorkingDirectory = workingDirectory;
gameProcess.StartInfo.FileName = $"{executableName}.exe";
gameProcess.StartInfo.UseShellExecute = true;
Process uModProcess = new Process();
if (uMod)
{
uModProcess.StartInfo.WorkingDirectory = $"{workingDirectory}\\uMod";
uModProcess.StartInfo.FileName = "uMod.exe";
uModProcess.StartInfo.UseShellExecute = true;
uModProcess.Start();
gameProcess.Start();
Log.Information("Game is starting");
await Task.Delay(5000);
}
else
{
gameProcess.Start();
Log.Information("Game is starting");
}
Log.Information("Setting game affinity based on CPU Core/Thread Count");
gameProcesses = Process.GetProcessesByName(executableName);
while (gameProcesses.Length <= 0)
{
await Task.Delay(1000);
gameProcesses = Process.GetProcessesByName(executableName);
}
foreach (Process process in gameProcesses)
{
process.PriorityClass = ProcessPriorityClass.AboveNormal;
await ProcessAffinityManager.SetProcessAffinity(process.ProcessName);
}
Log.Information("Game started");
Log.Information("Waiting for game to be closed");
await Task.Delay(10000);
while (gameProcesses.Length > 0)
{
await Task.Delay(1000);
gameProcesses = Process.GetProcessesByName(executableName);
}
Log.Information("Game Closed");
if (uMod)
{
try
{
if (Process.GetProcessById(uModProcess.Id) != null)
{
uModProcess.CloseMainWindow();
}
}
catch (Exception)
{
Log.Information("uMod is already closed.");
}
}
GC.Collect();
await Task.Delay(1);
if (skipLauncher)
{
Environment.Exit(0);
}
}
else
{
Log.Information($"Game {executableName} is already running");
System.Windows.MessageBox.Show($"Game {executableName} is already running.");
}
GC.Collect();
}
catch (Exception ex)
{
Log.Error(ex, "");
return;
}
}
/// <summary>
/// At startup it launches the Logger for debugging and checks for Launch arguments.
/// </summary>
/// <param name="e">Holds all of the launch Arguemnts as e.Args</param>
private async void Application_Startup(object sender, StartupEventArgs e)
{
// This is to disable double startup
if (start)
{
start = false;
Serilog.Log.Logger = Log.Logger; // Initializing Logger
// Checks for all of the Launch Arguments
if (e.Args.Contains("-console"))
{
AllocConsole();
logging = true;
}
// Creating Logger Configuration
if (logging)
{
Log.Logger = new LoggerConfiguration()
.WriteTo.Console(
outputTemplate: "{Timestamp:dd-MM-yyyy HH:mm:ss}|{Level}|{Message}{NewLine}{Exception}")
.WriteTo.File("Logs.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();
}
else
{
Log.Logger = new LoggerConfiguration()
.WriteTo.Console(
outputTemplate: "{Timestamp:dd-MM-yyyy HH:mm:ss}|{Level}|{Message}{NewLine}{Exception}")
//.WriteTo.File("Logs.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();
}
await FindGameInstallations();
await FindNumberOfCores();
await FindSupportedResolutions();
await FindRefreshRate();
await FindSavedGamesFolder();
await uModStatus();
discordRPCManager.InitializePresence("Idle");
App.discordRPCManager.UpdateStateAndIcon("icon", "Main Window", "Idle");
foreach (var argument in e.Args)
{
switch (argument)
{
case "-AC2":
MainWindow.Visibility = Visibility.Hidden;
discordRPCManager.UpdateStateAndIcon("acii1", "Assassin's Creed 2 - In Game", "Idle");
discordRPCManager.InitializeInGamePresence();
await StartGame("AssassinsCreedIIGame", App.AC2Path, App.AC2uModStatus, true);
discordRPCManager.UpdateStateAndIcon("acii1", "Assassin's Creed 2", "Idle");
break;
case "-ACB":
MainWindow.Visibility = Visibility.Hidden;
discordRPCManager.UpdateStateAndIcon("acb1", "Assassin's Creed: Brotherhood - In Game", "Idle");
discordRPCManager.InitializeInGamePresence();
await StartGame("ACBSP", App.ACBPath, App.ACBuModStatus, true);
discordRPCManager.UpdateStateAndIcon("acb1", "Assassin's Creed: Brotherhood", "Idle");
break;
case "-ACR":
MainWindow.Visibility = Visibility.Hidden;
discordRPCManager.UpdateStateAndIcon("acr2", "Assassin's Creed: Revelations - In Game", "Idle");
discordRPCManager.InitializeInGamePresence();
await StartGame("ACRSP", App.ACRPath, false, true);
discordRPCManager.UpdateStateAndIcon("acr2", "Assassin's Creed: Revelations", "Idle");
break;
default:
break;
}
}
}
}
private void Application_Exit(object sender, ExitEventArgs e)
{
Log.CloseAndFlush();
}
}
}