-
Notifications
You must be signed in to change notification settings - Fork 1
/
GameMemory.cs
287 lines (242 loc) · 10.2 KB
/
GameMemory.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using LiveSplit.ComponentUtil;
namespace LiveSplit.RedFaction
{
class GameMemory
{
public event EventHandler OnPlayerGainedControl;
public event EventHandler OnLoadStarted;
public event EventHandler OnFirstLevelLoading;
public event EventHandler OnLoadFinished;
public delegate void SplitCompletedEventHandler(object sender, int split, uint frame);
public event SplitCompletedEventHandler OnSplitCompleted;
private Task _thread;
private CancellationTokenSource _cancelSource;
private SynchronizationContext _uiThread;
private List<int> _ignorePIDs;
private RedFactionSettings _settings;
private DeepPointer _isLoadingPtr;
private DeepPointer _levelNamePtr;
private DeepPointer _binkMoviePlaying;
ProcessModuleWow64Safe binkw32;
private string[] validExeNames =
{
"pf",
"rf",
"rf_120na"
};
private enum ExpectedDllSizes
{
PureFaction30d = 29945856,
RedFaction1_20 = 29917184
}
public List<SplitStructOverall> currentSplits { get; set; }
public bool[] splitStates { get; set; }
public void resetSplitStates()
{
for (int i = 0; i < currentSplits.Count; i++)
{
splitStates[i] = false;
}
}
public GameMemory(RedFactionSettings componentSettings)
{
_settings = componentSettings;
currentSplits = componentSettings.Mods[componentSettings.ModIndex].Splits;
splitStates = new bool[currentSplits.Count];
_isLoadingPtr = new DeepPointer(0x13756AC); // == 1 if a loadscreen is happening
_levelNamePtr = new DeepPointer(0x0246144, 0x0);
_binkMoviePlaying = new DeepPointer("binkw32.dll", 0x41BD8); //binkw32.dll+41BD8
resetSplitStates();
_ignorePIDs = new List<int>();
}
public void StartMonitoring()
{
if (_thread != null && _thread.Status == TaskStatus.Running)
{
throw new InvalidOperationException();
}
if (!(SynchronizationContext.Current is WindowsFormsSynchronizationContext))
{
throw new InvalidOperationException("SynchronizationContext.Current is not a UI thread.");
}
_uiThread = SynchronizationContext.Current;
_cancelSource = new CancellationTokenSource();
_thread = Task.Factory.StartNew(MemoryReadThread);
}
public void Stop()
{
if (_cancelSource == null || _thread == null || _thread.Status != TaskStatus.Running)
{
return;
}
_cancelSource.Cancel();
_thread.Wait();
}
void MemoryReadThread()
{
Debug.WriteLine("[NoLoads] MemoryReadThread");
while (!_cancelSource.IsCancellationRequested)
{
try
{
Debug.WriteLine("[NoLoads] Waiting for pf.exe...");
Process game;
while ((game = GetGameProcess()) == null)
{
Thread.Sleep(250);
if (_cancelSource.IsCancellationRequested)
{
return;
}
}
Debug.WriteLine("[NoLoads] Got games process!");
uint frameCounter = 0;
bool prevIsLoading = false;
bool prevIsMoviePlaying = false;
string prevLevelName = "";
bool loadingStarted = false;
while (!game.HasExited)
{
bool isLoading;
bool isMoviePlaying;
string levelName = "";
_levelNamePtr.DerefString(game, 32, out levelName);
levelName = levelName != null ? levelName.ToLower() : ""; //cause it can read null if the game started off fresh and then you'd try to convert it to lowercase and would get exception
_isLoadingPtr.Deref(game, out isLoading);
_binkMoviePlaying.Deref(game, out isMoviePlaying);
if (levelName != prevLevelName && levelName != null || isMoviePlaying != prevIsLoading)
{
#if DEBUG
Debug.WriteIf(levelName != prevLevelName, $"[NoLoads] Level change {prevLevelName} -> {levelName} (frame #{frameCounter})");
#endif
for (int i=0; i<splitStates.Length; i++)
{
if(!splitStates[i] && currentSplits[i].Check(in levelName, in prevLevelName, isMoviePlaying))
{
Split(i, frameCounter);
}
}
}
_isLoadingPtr.Deref(game, out isLoading);
if (isLoading != prevIsLoading || prevIsMoviePlaying != isMoviePlaying)
{
if (isLoading)
{
#if DEBUG
Debug.WriteLine("[NoLoads] Load Start - {frameCounter}");
#endif
loadingStarted = true;
// pause game timer
_uiThread.Post(d =>
{
if (this.OnLoadStarted != null)
{
this.OnLoadStarted(this, EventArgs.Empty);
}
}, null);
if (levelName == "l1s1.rfl" && isMoviePlaying)
{
//reset game timer
_uiThread.Post(d =>
{
if (this.OnFirstLevelLoading != null)
{
this.OnFirstLevelLoading(this, EventArgs.Empty);
}
}, null);
}
}
else
{
#if DEBUG
Debug.WriteLine($"[NoLoads] Load End - {frameCounter}");
#endif
if (loadingStarted)
{
loadingStarted = false;
// unpause game timer
_uiThread.Post(d =>
{
if (this.OnLoadFinished != null)
{
this.OnLoadFinished(this, EventArgs.Empty);
}
}, null);
if (levelName == "l1s1.rfl")
{
// start game timer
_uiThread.Post(d =>
{
if (this.OnPlayerGainedControl != null)
{
this.OnPlayerGainedControl(this, EventArgs.Empty);
}
}, null);
}
}
}
}
prevLevelName = levelName;
prevIsLoading = isLoading;
prevIsMoviePlaying = isMoviePlaying;
frameCounter++;
Thread.Sleep(15);
if (_cancelSource.IsCancellationRequested)
{
return;
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
Thread.Sleep(1000);
}
}
}
private void Split(int split, uint frame)
{
#if DEBUG
Debug.WriteLine($"[NoLoads] split {split} ({currentSplits[split].Name}) - {frame}");
#endif
_uiThread.Post(d =>
{
if (this.OnSplitCompleted != null)
{
this.OnSplitCompleted(this, split, frame);
}
}, null);
}
Process GetGameProcess()
{
Process game = Process.GetProcesses().FirstOrDefault(p => (validExeNames.Any(x => x == p.ProcessName.ToLower()))
&& !p.HasExited && !_ignorePIDs.Contains(p.Id));
if (game == null)
{
return null;
}
binkw32 = game.ModulesWow64Safe().FirstOrDefault(p => p.ModuleName.ToLower() == "binkw32.dll");
if (binkw32 == null)
return null;
var mainModuleSize = game.MainModuleWow64Safe().ModuleMemorySize;
if (mainModuleSize == (int)ExpectedDllSizes.PureFaction30d || mainModuleSize == (int)ExpectedDllSizes.RedFaction1_20)
{
}
else
{
_ignorePIDs.Add(game.Id);
_uiThread.Send(d => MessageBox.Show("Unexpected game version. Red Faction 1.20 (including DashFaction) or Pure Faction 3.0d is required", "LiveSplit.RedFaction",
MessageBoxButtons.OK, MessageBoxIcon.Error), null);
return null;
}
return game;
}
}
}