forked from Pathoschild/SMAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSCore.cs
More file actions
2126 lines (1843 loc) · 101 KB
/
SCore.cs
File metadata and controls
2126 lines (1843 loc) · 101 KB
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 System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Security;
using System.Text;
using System.Threading;
using Microsoft.Xna.Framework;
#if SMAPI_FOR_WINDOWS
using Microsoft.Win32;
#endif
using Newtonsoft.Json;
using StardewModdingAPI.Enums;
using StardewModdingAPI.Events;
using StardewModdingAPI.Framework.Content;
using StardewModdingAPI.Framework.ContentManagers;
using StardewModdingAPI.Framework.Events;
using StardewModdingAPI.Framework.Exceptions;
using StardewModdingAPI.Framework.Input;
using StardewModdingAPI.Framework.Logging;
using StardewModdingAPI.Framework.Models;
using StardewModdingAPI.Framework.ModHelpers;
using StardewModdingAPI.Framework.ModLoading;
using StardewModdingAPI.Framework.Networking;
using StardewModdingAPI.Framework.Reflection;
using StardewModdingAPI.Framework.Rendering;
using StardewModdingAPI.Framework.Serialization;
using StardewModdingAPI.Framework.StateTracking.Comparers;
using StardewModdingAPI.Framework.StateTracking.Snapshots;
using StardewModdingAPI.Framework.Utilities;
using StardewModdingAPI.Internal;
using StardewModdingAPI.Internal.Patching;
using StardewModdingAPI.Patches;
using StardewModdingAPI.Toolkit;
using StardewModdingAPI.Toolkit.Framework.Clients.WebApi;
using StardewModdingAPI.Toolkit.Framework.ModData;
using StardewModdingAPI.Toolkit.Serialization;
using StardewModdingAPI.Toolkit.Utilities;
using StardewModdingAPI.Utilities;
using StardewValley;
using StardewValley.Menus;
using xTile.Display;
using LanguageCode = StardewValley.LocalizedContentManager.LanguageCode;
using MiniMonoModHotfix = MonoMod.Utils.MiniMonoModHotfix;
using PathUtilities = StardewModdingAPI.Toolkit.Utilities.PathUtilities;
using SObject = StardewValley.Object;
namespace StardewModdingAPI.Framework
{
/// <summary>The core class which initializes and manages SMAPI.</summary>
internal class SCore : IDisposable
{
/*********
** Fields
*********/
/****
** Low-level components
****/
/// <summary>Tracks whether the game should exit immediately and any pending initialization should be cancelled.</summary>
private readonly CancellationTokenSource CancellationToken = new();
/// <summary>Manages the SMAPI console window and log file.</summary>
private readonly LogManager LogManager;
/// <summary>The core logger and monitor for SMAPI.</summary>
private Monitor Monitor => this.LogManager.Monitor;
/// <summary>Simplifies access to private game code.</summary>
private readonly Reflector Reflection = new();
/// <summary>Encapsulates access to SMAPI core translations.</summary>
private readonly Translator Translator = new();
/// <summary>The SMAPI configuration settings.</summary>
private readonly SConfig Settings;
/// <summary>The mod toolkit used for generic mod interactions.</summary>
private readonly ModToolkit Toolkit = new();
/****
** Higher-level components
****/
/// <summary>Manages console commands.</summary>
private readonly CommandManager CommandManager;
/// <summary>The underlying game instance.</summary>
private SGameRunner Game;
/// <summary>SMAPI's content manager.</summary>
private ContentCoordinator ContentCore;
/// <summary>The game's core multiplayer utility for the main player.</summary>
private SMultiplayer Multiplayer;
/// <summary>Tracks the installed mods.</summary>
/// <remarks>This is initialized after the game starts.</remarks>
private readonly ModRegistry ModRegistry = new();
/// <summary>Manages SMAPI events for mods.</summary>
private readonly EventManager EventManager;
/****
** State
****/
/// <summary>The path to search for mods.</summary>
private string ModsPath => Constants.ModsPath;
/// <summary>Whether the game is currently running.</summary>
private bool IsGameRunning;
/// <summary>Whether the program has been disposed.</summary>
private bool IsDisposed;
/// <summary>Whether the next content manager requested by the game will be for <see cref="Game1.content"/>.</summary>
private bool NextContentManagerIsMain;
/// <summary>Whether post-game-startup initialization has been performed.</summary>
private bool IsInitialized;
/// <summary>Whether the game has initialized for any custom languages from <c>Data/AdditionalLanguages</c>.</summary>
private bool AreCustomLanguagesInitialized;
/// <summary>Whether the player just returned to the title screen.</summary>
public bool JustReturnedToTitle { get; set; }
/// <summary>The last language set by the game.</summary>
private (string Locale, LanguageCode Code) LastLanguage { get; set; } = ("", LanguageCode.en);
/// <summary>The maximum number of consecutive attempts SMAPI should make to recover from an update error.</summary>
private readonly Countdown UpdateCrashTimer = new(60); // 60 ticks = roughly one second
/// <summary>Asset interceptors added or removed since the last tick.</summary>
private readonly List<AssetInterceptorChange> ReloadAssetInterceptorsQueue = new();
/// <summary>A list of queued commands to parse and execute.</summary>
/// <remarks>This property must be thread-safe, since it's accessed from a separate console input thread.</remarks>
private readonly ConcurrentQueue<string> RawCommandQueue = new();
/// <summary>A list of commands to execute on each screen.</summary>
private readonly PerScreen<List<Tuple<Command, string, string[]>>> ScreenCommandQueue = new(() => new List<Tuple<Command, string, string[]>>());
/*********
** Accessors
*********/
/// <summary>Manages deprecation warnings.</summary>
/// <remarks>This is initialized after the game starts. This is accessed directly because it's not part of the normal class model.</remarks>
internal static DeprecationManager DeprecationManager { get; private set; }
/// <summary>The singleton instance.</summary>
/// <remarks>This is only intended for use by external code like the Error Handler mod.</remarks>
internal static SCore Instance { get; private set; }
/// <summary>The number of update ticks which have already executed. This is similar to <see cref="Game1.ticks"/>, but incremented more consistently for every tick.</summary>
internal static uint TicksElapsed { get; private set; }
/*********
** Public methods
*********/
/// <summary>Construct an instance.</summary>
/// <param name="modsPath">The path to search for mods.</param>
/// <param name="writeToConsole">Whether to output log messages to the console.</param>
public SCore(string modsPath, bool writeToConsole)
{
SCore.Instance = this;
// init paths
this.VerifyPath(modsPath);
this.VerifyPath(Constants.LogDir);
Constants.ModsPath = modsPath;
// init log file
this.PurgeNormalLogs();
string logPath = this.GetLogPath();
// init basics
this.Settings = JsonConvert.DeserializeObject<SConfig>(File.ReadAllText(Constants.ApiConfigPath));
if (File.Exists(Constants.ApiUserConfigPath))
JsonConvert.PopulateObject(File.ReadAllText(Constants.ApiUserConfigPath), this.Settings);
this.LogManager = new LogManager(logPath: logPath, colorConfig: this.Settings.ConsoleColors, writeToConsole: writeToConsole, isVerbose: this.Settings.VerboseLogging, isDeveloperMode: this.Settings.DeveloperMode, getScreenIdForLog: this.GetScreenIdForLog);
this.CommandManager = new CommandManager(this.Monitor);
this.EventManager = new EventManager(this.ModRegistry);
SCore.DeprecationManager = new DeprecationManager(this.Monitor, this.ModRegistry);
SDate.Translations = this.Translator;
// log SMAPI/OS info
this.LogManager.LogIntro(modsPath, this.Settings.GetCustomSettings());
// validate platform
#if SMAPI_FOR_WINDOWS
if (Constants.Platform != Platform.Windows)
{
this.Monitor.Log("Oops! You're running Windows, but this version of SMAPI is for Linux or macOS. Please reinstall SMAPI to fix this.", LogLevel.Error);
this.LogManager.PressAnyKeyToExit();
}
#else
if (Constants.Platform == Platform.Windows)
{
this.Monitor.Log($"Oops! You're running {Constants.Platform}, but this version of SMAPI is for Windows. Please reinstall SMAPI to fix this.", LogLevel.Error);
this.LogManager.PressAnyKeyToExit();
}
#endif
}
/// <summary>Launch SMAPI.</summary>
[HandleProcessCorruptedStateExceptions, SecurityCritical] // let try..catch handle corrupted state exceptions
public void RunInteractively()
{
// initialize SMAPI
try
{
JsonConverter[] converters = {
new ColorConverter(),
new KeybindConverter(),
new PointConverter(),
new Vector2Converter(),
new RectangleConverter()
};
foreach (JsonConverter converter in converters)
this.Toolkit.JsonHelper.JsonSettings.Converters.Add(converter);
// add error handlers
AppDomain.CurrentDomain.UnhandledException += (sender, e) => this.Monitor.Log($"Critical app domain exception: {e.ExceptionObject}", LogLevel.Error);
// add more lenient assembly resolver
AppDomain.CurrentDomain.AssemblyResolve += (sender, e) => AssemblyLoader.ResolveAssembly(e.Name);
// hook locale event
LocalizedContentManager.OnLanguageChange += locale => this.OnLocaleChanged();
// override game
this.Multiplayer = new SMultiplayer(this.Monitor, this.EventManager, this.Toolkit.JsonHelper, this.ModRegistry, this.Reflection, this.OnModMessageReceived, this.Settings.LogNetworkTraffic);
SGame.CreateContentManagerImpl = this.CreateContentManager; // must be static since the game accesses it before the SGame constructor is called
this.Game = new SGameRunner(
monitor: this.Monitor,
reflection: this.Reflection,
eventManager: this.EventManager,
modHooks: new SModHooks(this.OnNewDayAfterFade, this.Monitor),
multiplayer: this.Multiplayer,
exitGameImmediately: this.ExitGameImmediately,
onGameContentLoaded: this.OnInstanceContentLoaded,
onGameUpdating: this.OnGameUpdating,
onPlayerInstanceUpdating: this.OnPlayerInstanceUpdating,
onGameExiting: this.OnGameExiting
);
StardewValley.GameRunner.instance = this.Game;
// apply game patches
MiniMonoModHotfix.Apply();
HarmonyPatcher.Apply("SMAPI", this.Monitor,
new Game1Patcher(this.Reflection, this.OnLoadStageChanged),
new TitleMenuPatcher(this.OnLoadStageChanged)
);
// add exit handler
this.CancellationToken.Token.Register(() =>
{
if (this.IsGameRunning)
{
this.LogManager.WriteCrashLog();
this.Game.Exit();
}
});
// set window titles
this.UpdateWindowTitles();
}
catch (Exception ex)
{
this.Monitor.Log($"SMAPI failed to initialize: {ex.GetLogSummary()}", LogLevel.Error);
this.LogManager.PressAnyKeyToExit();
return;
}
// log basic info
this.LogManager.HandleMarkerFiles();
this.LogManager.LogSettingsHeader(this.Settings);
// set window titles
this.UpdateWindowTitles();
// start game
this.Monitor.Log("Waiting for game to launch...", LogLevel.Debug);
try
{
this.IsGameRunning = true;
StardewValley.Program.releaseBuild = true; // game's debug logic interferes with SMAPI opening the game window
this.Game.Run();
}
catch (Exception ex)
{
this.LogManager.LogFatalLaunchError(ex);
this.LogManager.PressAnyKeyToExit();
}
finally
{
try
{
this.Dispose();
}
catch (Exception ex)
{
this.Monitor.Log($"The game ended, but SMAPI wasn't able to dispose correctly. Technical details: {ex}", LogLevel.Error);
}
}
}
/// <summary>Get the core logger and monitor on behalf of the game.</summary>
/// <remarks>This method is called using reflection by the ErrorHandler mod to log game errors.</remarks>
[SuppressMessage("ReSharper", "UnusedMember.Global", Justification = "Used via reflection")]
public IMonitor GetMonitorForGame()
{
return this.LogManager.MonitorForGame;
}
/// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
public void Dispose()
{
// skip if already disposed
if (this.IsDisposed)
return;
this.IsDisposed = true;
this.Monitor.Log("Disposing...");
// dispose mod data
foreach (IModMetadata mod in this.ModRegistry.GetAll())
{
try
{
(mod.Mod as IDisposable)?.Dispose();
}
catch (Exception ex)
{
mod.LogAsMod($"Mod failed during disposal: {ex.GetLogSummary()}.", LogLevel.Warn);
}
}
// dispose core components
this.IsGameRunning = false;
this.ContentCore?.Dispose();
this.CancellationToken?.Dispose();
this.Game?.Dispose();
this.LogManager?.Dispose(); // dispose last to allow for any last-second log messages
// end game (moved from Game1.OnExiting to let us clean up first)
Process.GetCurrentProcess().Kill();
}
/*********
** Private methods
*********/
/// <summary>Initialize mods before the first game asset is loaded. At this point the core content managers are loaded (so mods can load their own assets), but the game is mostly uninitialized.</summary>
private void InitializeBeforeFirstAssetLoaded()
{
if (this.CancellationToken.IsCancellationRequested)
{
this.Monitor.Log("SMAPI shutting down: aborting initialization.", LogLevel.Warn);
return;
}
// init TMX support
xTile.Format.FormatManager.Instance.RegisterMapFormat(new TMXTile.TMXFormat(Game1.tileSize / Game1.pixelZoom, Game1.tileSize / Game1.pixelZoom, Game1.pixelZoom, Game1.pixelZoom));
// load mod data
ModToolkit toolkit = new();
ModDatabase modDatabase = toolkit.GetModDatabase(Constants.ApiMetadataPath);
// load mods
{
this.Monitor.Log("Loading mod metadata...", LogLevel.Debug);
ModResolver resolver = new();
// log loose files
{
string[] looseFiles = new DirectoryInfo(this.ModsPath).GetFiles().Select(p => p.Name).ToArray();
if (looseFiles.Any())
this.Monitor.Log($" Ignored loose files: {string.Join(", ", looseFiles.OrderBy(p => p, StringComparer.OrdinalIgnoreCase))}");
}
// load manifests
IModMetadata[] mods = resolver.ReadManifests(toolkit, this.ModsPath, modDatabase).ToArray();
// filter out ignored mods
foreach (IModMetadata mod in mods.Where(p => p.IsIgnored))
this.Monitor.Log($" Skipped {mod.GetRelativePathWithRoot()} (folder name starts with a dot).");
mods = mods.Where(p => !p.IsIgnored).ToArray();
// load mods
resolver.ValidateManifests(mods, Constants.ApiVersion, toolkit.GetUpdateUrl);
mods = resolver.ProcessDependencies(mods, modDatabase).ToArray();
this.LoadMods(mods, this.Toolkit.JsonHelper, this.ContentCore, modDatabase);
// check for software likely to cause issues
this.CheckForSoftwareConflicts();
// check for updates
this.CheckForUpdatesAsync(mods);
}
// update window titles
this.UpdateWindowTitles();
}
/// <summary>Raised after the game finishes initializing.</summary>
private void OnGameInitialized()
{
// validate XNB integrity
if (!this.ValidateContentIntegrity())
this.Monitor.Log("SMAPI found problems in your game's content files which are likely to cause errors or crashes. Consider uninstalling XNB mods or reinstalling the game.", LogLevel.Error);
// start SMAPI console
new Thread(
() => this.LogManager.RunConsoleInputLoop(
commandManager: this.CommandManager,
reloadTranslations: this.ReloadTranslations,
handleInput: input => this.RawCommandQueue.Enqueue(input),
continueWhile: () => this.IsGameRunning && !this.CancellationToken.IsCancellationRequested
)
).Start();
}
/// <summary>Raised after an instance finishes loading its initial content.</summary>
private void OnInstanceContentLoaded()
{
// override map display device
Game1.mapDisplayDevice = new SDisplayDevice(Game1.content, Game1.game1.GraphicsDevice);
// log GPU info
#if SMAPI_FOR_WINDOWS
this.Monitor.Log($"Running on GPU: {Game1.game1.GraphicsDevice?.Adapter?.Description ?? "<unknown>"}");
#endif
}
/// <summary>Raised when the game is updating its state (roughly 60 times per second).</summary>
/// <param name="gameTime">A snapshot of the game timing state.</param>
/// <param name="runGameUpdate">Invoke the game's update logic.</param>
private void OnGameUpdating(GameTime gameTime, Action runGameUpdate)
{
try
{
/*********
** Safe queued work
*********/
// print warnings/alerts
SCore.DeprecationManager.PrintQueued();
/*********
** First-tick initialization
*********/
if (!this.IsInitialized)
{
this.IsInitialized = true;
this.OnGameInitialized();
}
/*********
** Special cases
*********/
// Abort if SMAPI is exiting.
if (this.CancellationToken.IsCancellationRequested)
{
this.Monitor.Log("SMAPI shutting down: aborting update.");
return;
}
/*********
** Reload assets when interceptors are added/removed
*********/
if (this.ReloadAssetInterceptorsQueue.Any())
{
// get unique interceptors
AssetInterceptorChange[] interceptors = this.ReloadAssetInterceptorsQueue
.GroupBy(p => p.Instance, new ObjectReferenceComparer<object>())
.Select(p => p.First())
.ToArray();
this.ReloadAssetInterceptorsQueue.Clear();
// log summary
this.Monitor.Log("Invalidating cached assets for new editors & loaders...");
this.Monitor.Log(
" changed: "
+ string.Join(", ",
interceptors
.GroupBy(p => p.Mod)
.OrderBy(p => p.Key.DisplayName)
.Select(modGroup =>
$"{modGroup.Key.DisplayName} ("
+ string.Join(", ", modGroup.GroupBy(p => p.WasAdded).ToDictionary(p => p.Key, p => p.Count()).Select(p => $"{(p.Key ? "added" : "removed")} {p.Value}"))
+ ")"
)
)
+ "."
);
// reload affected assets
this.ContentCore.InvalidateCache(asset => interceptors.Any(p => p.CanIntercept(asset)));
}
/*********
** Parse commands
*********/
while (this.RawCommandQueue.TryDequeue(out string rawInput))
{
// parse command
string name;
string[] args;
Command command;
int screenId;
try
{
if (!this.CommandManager.TryParse(rawInput, out name, out args, out command, out screenId))
{
this.Monitor.Log("Unknown command; type 'help' for a list of available commands.", LogLevel.Error);
continue;
}
}
catch (Exception ex)
{
this.Monitor.Log($"Failed parsing that command:\n{ex.GetLogSummary()}", LogLevel.Error);
continue;
}
// queue command for screen
this.ScreenCommandQueue.GetValueForScreen(screenId).Add(Tuple.Create(command, name, args));
}
/*********
** Run game update
*********/
runGameUpdate();
/*********
** Reset crash timer
*********/
this.UpdateCrashTimer.Reset();
}
catch (Exception ex)
{
// log error
this.Monitor.Log($"An error occured in the overridden update loop: {ex.GetLogSummary()}", LogLevel.Error);
// exit if irrecoverable
if (!this.UpdateCrashTimer.Decrement())
this.ExitGameImmediately("The game crashed when updating, and SMAPI was unable to recover the game.");
}
finally
{
SCore.TicksElapsed++;
}
}
/// <summary>Raised when the game instance for a local player is updating (once per <see cref="OnGameUpdating"/> per player).</summary>
/// <param name="instance">The game instance being updated.</param>
/// <param name="gameTime">A snapshot of the game timing state.</param>
/// <param name="runUpdate">Invoke the game's update logic.</param>
private void OnPlayerInstanceUpdating(SGame instance, GameTime gameTime, Action runUpdate)
{
var events = this.EventManager;
try
{
/*********
** Reapply overrides
*********/
if (this.JustReturnedToTitle)
{
if (!(Game1.mapDisplayDevice is SDisplayDevice))
Game1.mapDisplayDevice = this.GetMapDisplayDevice();
this.JustReturnedToTitle = false;
}
/*********
** Execute commands
*********/
{
var commandQueue = this.ScreenCommandQueue.Value;
foreach (var entry in commandQueue)
{
Command command = entry.Item1;
string name = entry.Item2;
string[] args = entry.Item3;
try
{
command.Callback.Invoke(name, args);
}
catch (Exception ex)
{
if (command.Mod != null)
command.Mod.LogAsMod($"Mod failed handling that command:\n{ex.GetLogSummary()}", LogLevel.Error);
else
this.Monitor.Log($"Failed handling that command:\n{ex.GetLogSummary()}", LogLevel.Error);
}
}
commandQueue.Clear();
}
/*********
** Update input
*********/
// This should *always* run, even when suppressing mod events, since the game uses
// this too. For example, doing this after mod event suppression would prevent the
// user from doing anything on the overnight shipping screen.
SInputState inputState = instance.Input;
if (this.Game.IsActive)
inputState.TrueUpdate();
/*********
** Special cases
*********/
// Run async tasks synchronously to avoid issues due to mod events triggering
// concurrently with game code.
bool saveParsed = false;
if (Game1.currentLoader != null)
{
this.Monitor.Log("Game loader synchronizing...");
this.Reflection.GetMethod(Game1.game1, "UpdateTitleScreen").Invoke(Game1.currentGameTime); // run game logic to change music on load, etc
while (Game1.currentLoader?.MoveNext() == true)
{
// raise load stage changed
switch (Game1.currentLoader.Current)
{
case 20 when (!saveParsed && SaveGame.loaded != null):
saveParsed = true;
this.OnLoadStageChanged(LoadStage.SaveParsed);
break;
case 36:
this.OnLoadStageChanged(LoadStage.SaveLoadedBasicInfo);
break;
case 50:
this.OnLoadStageChanged(LoadStage.SaveLoadedLocations);
break;
default:
if (Game1.gameMode == Game1.playingGameMode)
this.OnLoadStageChanged(LoadStage.Preloaded);
break;
}
}
Game1.currentLoader = null;
this.Monitor.Log("Game loader done.");
}
// While a background task is in progress, the game may make changes to the game
// state while mods are running their code. This is risky, because data changes can
// conflict (e.g. collection changed during enumeration errors) and data may change
// unexpectedly from one mod instruction to the next.
//
// Therefore we can just run Game1.Update here without raising any SMAPI events. There's
// a small chance that the task will finish after we defer but before the game checks,
// which means technically events should be raised, but the effects of missing one
// update tick are negligible and not worth the complications of bypassing Game1.Update.
if (Game1.gameMode == Game1.loadingMode)
{
events.UnvalidatedUpdateTicking.RaiseEmpty();
runUpdate();
events.UnvalidatedUpdateTicked.RaiseEmpty();
return;
}
// Raise minimal events while saving.
// While the game is writing to the save file in the background, mods can unexpectedly
// fail since they don't have exclusive access to resources (e.g. collection changed
// during enumeration errors). To avoid problems, events are not invoked while a save
// is in progress. It's safe to raise SaveEvents.BeforeSave as soon as the menu is
// opened (since the save hasn't started yet), but all other events should be suppressed.
if (Context.IsSaving)
{
// raise before-create
if (!Context.IsWorldReady && !instance.IsBetweenCreateEvents)
{
instance.IsBetweenCreateEvents = true;
this.Monitor.Log("Context: before save creation.");
events.SaveCreating.RaiseEmpty();
}
// raise before-save
if (Context.IsWorldReady && !instance.IsBetweenSaveEvents)
{
instance.IsBetweenSaveEvents = true;
this.Monitor.Log("Context: before save.");
events.Saving.RaiseEmpty();
}
// suppress non-save events
events.UnvalidatedUpdateTicking.RaiseEmpty();
runUpdate();
events.UnvalidatedUpdateTicked.RaiseEmpty();
return;
}
/*********
** Update context
*********/
bool wasWorldReady = Context.IsWorldReady;
if ((Context.IsWorldReady && !Context.IsSaveLoaded) || Game1.exitToTitle)
{
Context.IsWorldReady = false;
instance.AfterLoadTimer.Reset();
}
else if (Context.IsSaveLoaded && instance.AfterLoadTimer.Current > 0 && Game1.currentLocation != null)
{
if (Game1.dayOfMonth != 0) // wait until new-game intro finishes (world not fully initialized yet)
instance.AfterLoadTimer.Decrement();
Context.IsWorldReady = instance.AfterLoadTimer.Current == 0;
}
/*********
** Update watchers
** (Watchers need to be updated, checked, and reset in one go so we can detect any changes mods make in event handlers.)
*********/
instance.Watchers.Update();
instance.WatcherSnapshot.Update(instance.Watchers);
instance.Watchers.Reset();
WatcherSnapshot state = instance.WatcherSnapshot;
/*********
** Pre-update events
*********/
{
/*********
** Save created/loaded events
*********/
if (instance.IsBetweenCreateEvents)
{
// raise after-create
instance.IsBetweenCreateEvents = false;
this.Monitor.Log($"Context: after save creation, starting {Game1.currentSeason} {Game1.dayOfMonth} Y{Game1.year}.");
this.OnLoadStageChanged(LoadStage.CreatedSaveFile);
events.SaveCreated.RaiseEmpty();
}
if (instance.IsBetweenSaveEvents)
{
// raise after-save
instance.IsBetweenSaveEvents = false;
this.Monitor.Log($"Context: after save, starting {Game1.currentSeason} {Game1.dayOfMonth} Y{Game1.year}.");
events.Saved.RaiseEmpty();
events.DayStarted.RaiseEmpty();
}
/*********
** Locale changed events
*********/
if (state.Locale.IsChanged)
this.Monitor.Log($"Context: locale set to {state.Locale.New} ({this.ContentCore.GetLocaleCode(state.Locale.New)}).");
/*********
** Load / return-to-title events
*********/
if (wasWorldReady && !Context.IsWorldReady)
this.OnLoadStageChanged(LoadStage.None);
else if (Context.IsWorldReady && Context.LoadStage != LoadStage.Ready)
{
// print context
string context = $"Context: loaded save '{Constants.SaveFolderName}', starting {Game1.currentSeason} {Game1.dayOfMonth} Y{Game1.year}, locale set to {this.ContentCore.GetLocale()}.";
if (Context.IsMultiplayer)
{
int onlineCount = Game1.getOnlineFarmers().Count();
context += $" {(Context.IsMainPlayer ? "Main player" : "Farmhand")} with {onlineCount} {(onlineCount == 1 ? "player" : "players")} online.";
}
else
context += " Single-player.";
this.Monitor.Log(context);
// raise events
this.OnLoadStageChanged(LoadStage.Ready);
events.SaveLoaded.RaiseEmpty();
events.DayStarted.RaiseEmpty();
}
/*********
** Window events
*********/
// Here we depend on the game's viewport instead of listening to the Window.Resize
// event because we need to notify mods after the game handles the resize, so the
// game's metadata (like Game1.viewport) are updated. That's a bit complicated
// since the game adds & removes its own handler on the fly.
if (state.WindowSize.IsChanged)
{
if (this.Monitor.IsVerbose)
this.Monitor.Log($"Events: window size changed to {state.WindowSize.New}.");
events.WindowResized.Raise(new WindowResizedEventArgs(state.WindowSize.Old, state.WindowSize.New));
}
/*********
** Input events (if window has focus)
*********/
if (this.Game.IsActive)
{
// raise events
bool isChatInput = Game1.IsChatting || (Context.IsMultiplayer && Context.IsWorldReady && Game1.activeClickableMenu == null && Game1.currentMinigame == null && inputState.IsAnyDown(Game1.options.chatButton));
if (!isChatInput)
{
ICursorPosition cursor = instance.Input.CursorPosition;
// raise cursor moved event
if (state.Cursor.IsChanged)
events.CursorMoved.Raise(new CursorMovedEventArgs(state.Cursor.Old, state.Cursor.New));
// raise mouse wheel scrolled
if (state.MouseWheelScroll.IsChanged)
{
if (this.Monitor.IsVerbose)
this.Monitor.Log($"Events: mouse wheel scrolled to {state.MouseWheelScroll.New}.");
events.MouseWheelScrolled.Raise(new MouseWheelScrolledEventArgs(cursor, state.MouseWheelScroll.Old, state.MouseWheelScroll.New));
}
// raise input button events
if (inputState.ButtonStates.Count > 0)
{
events.ButtonsChanged.Raise(new ButtonsChangedEventArgs(cursor, inputState));
foreach (var pair in inputState.ButtonStates)
{
SButton button = pair.Key;
SButtonState status = pair.Value;
if (status == SButtonState.Pressed)
{
if (this.Monitor.IsVerbose)
this.Monitor.Log($"Events: button {button} pressed.");
events.ButtonPressed.Raise(new ButtonPressedEventArgs(button, cursor, inputState));
}
else if (status == SButtonState.Released)
{
if (this.Monitor.IsVerbose)
this.Monitor.Log($"Events: button {button} released.");
events.ButtonReleased.Raise(new ButtonReleasedEventArgs(button, cursor, inputState));
}
}
}
}
}
/*********
** Menu events
*********/
if (state.ActiveMenu.IsChanged)
{
var was = state.ActiveMenu.Old;
var now = state.ActiveMenu.New;
if (this.Monitor.IsVerbose)
this.Monitor.Log($"Context: menu changed from {was?.GetType().FullName ?? "none"} to {now?.GetType().FullName ?? "none"}.");
// raise menu events
events.MenuChanged.Raise(new MenuChangedEventArgs(was, now));
}
/*********
** World & player events
*********/
if (Context.IsWorldReady)
{
bool raiseWorldEvents = !state.SaveID.IsChanged; // don't report changes from unloaded => loaded
// location list changes
if (state.Locations.LocationList.IsChanged && (events.LocationListChanged.HasListeners() || this.Monitor.IsVerbose))
{
var added = state.Locations.LocationList.Added.ToArray();
var removed = state.Locations.LocationList.Removed.ToArray();
if (this.Monitor.IsVerbose)
{
string addedText = added.Any() ? string.Join(", ", added.Select(p => p.Name)) : "none";
string removedText = removed.Any() ? string.Join(", ", removed.Select(p => p.Name)) : "none";
this.Monitor.Log($"Context: location list changed (added {addedText}; removed {removedText}).");
}
events.LocationListChanged.Raise(new LocationListChangedEventArgs(added, removed));
}
// raise location contents changed
if (raiseWorldEvents)
{
foreach (LocationSnapshot locState in state.Locations.Locations)
{
var location = locState.Location;
// buildings changed
if (locState.Buildings.IsChanged)
events.BuildingListChanged.Raise(new BuildingListChangedEventArgs(location, locState.Buildings.Added, locState.Buildings.Removed));
// debris changed
if (locState.Debris.IsChanged)
events.DebrisListChanged.Raise(new DebrisListChangedEventArgs(location, locState.Debris.Added, locState.Debris.Removed));
// large terrain features changed
if (locState.LargeTerrainFeatures.IsChanged)
events.LargeTerrainFeatureListChanged.Raise(new LargeTerrainFeatureListChangedEventArgs(location, locState.LargeTerrainFeatures.Added, locState.LargeTerrainFeatures.Removed));
// NPCs changed
if (locState.Npcs.IsChanged)
events.NpcListChanged.Raise(new NpcListChangedEventArgs(location, locState.Npcs.Added, locState.Npcs.Removed));
// objects changed
if (locState.Objects.IsChanged)
events.ObjectListChanged.Raise(new ObjectListChangedEventArgs(location, locState.Objects.Added, locState.Objects.Removed));
// chest items changed
if (events.ChestInventoryChanged.HasListeners())
{
foreach (var pair in locState.ChestItems)
{
SnapshotItemListDiff diff = pair.Value;
events.ChestInventoryChanged.Raise(new ChestInventoryChangedEventArgs(pair.Key, location, added: diff.Added, removed: diff.Removed, quantityChanged: diff.QuantityChanged));
}
}
// terrain features changed
if (locState.TerrainFeatures.IsChanged)
events.TerrainFeatureListChanged.Raise(new TerrainFeatureListChangedEventArgs(location, locState.TerrainFeatures.Added, locState.TerrainFeatures.Removed));
// furniture changed
if (locState.Furniture.IsChanged)
events.FurnitureListChanged.Raise(new FurnitureListChangedEventArgs(location, locState.Furniture.Added, locState.Furniture.Removed));
}
}
// raise time changed
if (raiseWorldEvents && state.Time.IsChanged)
events.TimeChanged.Raise(new TimeChangedEventArgs(state.Time.Old, state.Time.New));
// raise player events
if (raiseWorldEvents)
{
PlayerSnapshot playerState = state.CurrentPlayer;
Farmer player = playerState.Player;
// raise current location changed
if (playerState.Location.IsChanged)
{
if (this.Monitor.IsVerbose)
this.Monitor.Log($"Context: set location to {playerState.Location.New}.");
events.Warped.Raise(new WarpedEventArgs(player, playerState.Location.Old, playerState.Location.New));
}
// raise player leveled up a skill
foreach (var pair in playerState.Skills)
{
if (!pair.Value.IsChanged)
continue;
if (this.Monitor.IsVerbose)
this.Monitor.Log($"Events: player skill '{pair.Key}' changed from {pair.Value.Old} to {pair.Value.New}.");
events.LevelChanged.Raise(new LevelChangedEventArgs(player, pair.Key, pair.Value.Old, pair.Value.New));
}
// raise player inventory changed
if (playerState.Inventory.IsChanged)
{
var inventory = playerState.Inventory;
if (this.Monitor.IsVerbose)
this.Monitor.Log("Events: player inventory changed.");
events.InventoryChanged.Raise(new InventoryChangedEventArgs(player, added: inventory.Added, removed: inventory.Removed, quantityChanged: inventory.QuantityChanged));
}
}
}
/*********
** Game update
*********/
// game launched (not raised for secondary players in split-screen mode)
if (instance.IsFirstTick && !Context.IsGameLaunched)
{
Context.IsGameLaunched = true;
events.GameLaunched.Raise(new GameLaunchedEventArgs());
}
// preloaded
if (Context.IsSaveLoaded && Context.LoadStage != LoadStage.Loaded && Context.LoadStage != LoadStage.Ready && Game1.dayOfMonth != 0)
this.OnLoadStageChanged(LoadStage.Loaded);
// additional languages initialized
if (!this.AreCustomLanguagesInitialized && TitleMenu.ticksUntilLanguageLoad < 0)