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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
|
using System;
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 System.Threading.Tasks;
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.Deprecations;
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;
#if SMAPI_DEPRECATED
using StardewModdingAPI.Framework.StateTracking.Comparers;
#endif
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.Toolkit.Utilities.PathLookups;
using StardewModdingAPI.Utilities;
using StardewValley;
using StardewValley.Menus;
using StardewValley.Objects;
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>Whether the game should exit immediately and any pending initialization should be cancelled.</summary>
private bool IsExiting;
/// <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 = null!; // initialized very early
/// <summary>SMAPI's content manager.</summary>
private ContentCoordinator ContentCore = null!; // initialized very early
/// <summary>The game's core multiplayer utility for the main player.</summary>
private SMultiplayer Multiplayer = null!; // initialized very early
/// <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
#if SMAPI_DEPRECATED
/// <summary>Asset interceptors added or removed since the last tick.</summary>
private readonly List<AssetInterceptorChange> ReloadAssetInterceptorsQueue = new();
#endif
/// <summary>A list of queued commands to parse and execute.</summary>
private readonly CommandQueue RawCommandQueue = new();
/// <summary>A list of commands to execute on each screen.</summary>
private readonly PerScreen<List<QueuedCommand>> ScreenCommandQueue = new(() => new List<QueuedCommand>());
/*********
** 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; } = null!; // initialized in constructor, which happens before other code can access it
/// <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; } = null!; // initialized in constructor, which happens before other code can access it
/// <summary>The number of game 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; }
/// <summary>A specialized form of <see cref="TicksElapsed"/> which is incremented each time SMAPI performs a processing tick (whether that's a game update, one wait cycle while synchronizing code, etc).</summary>
internal static uint ProcessTicksElapsed { 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>
/// <param name="developerMode">Whether to enable development features, or <c>null</c> to use the value from the settings file.</param>
public SCore(string modsPath, bool writeToConsole, bool? developerMode)
{
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);
if (developerMode.HasValue)
this.Settings.OverrideDeveloperMode(developerMode.Value);
this.LogManager = new LogManager(logPath: logPath, colorConfig: this.Settings.ConsoleColors, writeToConsole: writeToConsole, verboseLogging: 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 += (_, e) => this.Monitor.Log($"Critical app domain exception: {e.ExceptionObject}", LogLevel.Error);
// add more lenient assembly resolver
AppDomain.CurrentDomain.AssemblyResolve += (_, e) => AssemblyLoader.ResolveAssembly(e.Name);
// hook locale event
LocalizedContentManager.OnLanguageChange += _ => 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)
);
// 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>
[SuppressMessage("ReSharper", "ConstantConditionalAccessQualifier", Justification = "May be disposed before SMAPI is fully initialized.")]
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.IsExiting = true;
this.ContentCore?.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.IsExiting)
{
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, useCaseInsensitiveFilePaths: this.Settings.UseCaseInsensitivePaths).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, getFileLookup: this.GetFileLookup);
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); // ignore task since the main thread doesn't need to wait for it
}
// 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.Add(input),
continueWhile: () => this.IsGameRunning && !this.IsExiting
)
).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.IsExiting)
{
this.Monitor.Log("SMAPI shutting down: aborting update.");
return;
}
#if SMAPI_DEPRECATED
/*********
** 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)));
}
#endif
/*********
** Parse commands
*********/
if (this.RawCommandQueue.TryDequeue(out string[]? rawCommands))
{
foreach (string rawInput in rawCommands)
{
// 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(new(command, name, args));
}
}
/*********
** Run game update
*********/
runGameUpdate();
/*********
** Reset crash timer
*********/
this.UpdateCrashTimer.Reset();
}
catch (Exception ex)
{
// log error
this.Monitor.Log($"An error occurred 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++;
SCore.ProcessTicksElapsed++;
}
}
/// <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)
{
EventManager events = this.EventManager;
bool verbose = this.Monitor.IsVerbose;
try
{
/*********
** Reapply overrides
*********/
if (this.JustReturnedToTitle)
{
if (Game1.mapDisplayDevice is not SDisplayDevice)
Game1.mapDisplayDevice = this.GetMapDisplayDevice();
this.JustReturnedToTitle = false;
}
/*********
** Execute commands
*********/
if (this.ScreenCommandQueue.Value.Any())
{
var commandQueue = this.ScreenCommandQueue.Value;
foreach ((Command? command, string? name, string[]? args) in commandQueue)
{
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
// ReSharper disable once ConstantConditionalAccessQualifier -- may become null within the loop
while (Game1.currentLoader?.MoveNext() == true)
{
SCore.ProcessTicksElapsed++;
// 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 (verbose)
this.Monitor.Log($"Events: window size changed to {state.WindowSize.New}.");
if (events.WindowResized.HasListeners)
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.HasListeners)
events.CursorMoved.Raise(new CursorMovedEventArgs(state.Cursor.Old!, state.Cursor.New!));
// raise mouse wheel scrolled
if (state.MouseWheelScroll.IsChanged)
{
if (verbose)
this.Monitor.Log($"Events: mouse wheel scrolled to {state.MouseWheelScroll.New}.");
if (events.MouseWheelScrolled.HasListeners)
events.MouseWheelScrolled.Raise(new MouseWheelScrolledEventArgs(cursor, state.MouseWheelScroll.Old, state.MouseWheelScroll.New));
}
// raise input button events
if (inputState.ButtonStates.Count > 0)
{
if (events.ButtonsChanged.HasListeners)
events.ButtonsChanged.Raise(new ButtonsChangedEventArgs(cursor, inputState));
bool raisePressed = events.ButtonPressed.HasListeners;
bool raiseReleased = events.ButtonReleased.HasListeners;
if (verbose || raisePressed || raiseReleased)
{
foreach ((SButton button, SButtonState status) in inputState.ButtonStates)
{
switch (status)
{
case SButtonState.Pressed:
if (verbose)
this.Monitor.Log($"Events: button {button} pressed.");
if (raisePressed)
events.ButtonPressed.Raise(new ButtonPressedEventArgs(button, cursor, inputState));
break;
case SButtonState.Released:
if (verbose)
this.Monitor.Log($"Events: button {button} released.");
if (raiseReleased)
events.ButtonReleased.Raise(new ButtonReleasedEventArgs(button, cursor, inputState));
break;
}
}
}
}
}
}
/*********
** Menu events
*********/
if (state.ActiveMenu.IsChanged)
{
IClickableMenu? was = state.ActiveMenu.Old;
IClickableMenu? now = state.ActiveMenu.New;
if (verbose)
this.Monitor.Log($"Context: menu changed from {was?.GetType().FullName ?? "none"} to {now?.GetType().FullName ?? "none"}.");
// raise menu events
if (events.MenuChanged.HasListeners)
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 || verbose))
{
var added = state.Locations.LocationList.Added.ToArray();
var removed = state.Locations.LocationList.Removed.ToArray();
if (verbose)
{
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}).");
}
if (events.LocationListChanged.HasListeners)
events.LocationListChanged.Raise(new LocationListChangedEventArgs(added, removed));
}
// raise location contents changed
if (raiseWorldEvents)
{
foreach (LocationSnapshot locState in state.Locations.Locations)
{
GameLocation location = locState.Location;
// buildings changed
if (locState.Buildings.IsChanged && events.BuildingListChanged.HasListeners)
events.BuildingListChanged.Raise(new BuildingListChangedEventArgs(location, locState.Buildings.Added, locState.Buildings.Removed));
// debris changed
if (locState.Debris.IsChanged && events.DebrisListChanged.HasListeners)
events.DebrisListChanged.Raise(new DebrisListChangedEventArgs(location, locState.Debris.Added, locState.Debris.Removed));
// large terrain features changed
if (locState.LargeTerrainFeatures.IsChanged && events.LargeTerrainFeatureListChanged.HasListeners)
events.LargeTerrainFeatureListChanged.Raise(new LargeTerrainFeatureListChangedEventArgs(location, locState.LargeTerrainFeatures.Added, locState.LargeTerrainFeatures.Removed));
// NPCs changed
if (locState.Npcs.IsChanged && events.NpcListChanged.HasListeners)
events.NpcListChanged.Raise(new NpcListChangedEventArgs(location, locState.Npcs.Added, locState.Npcs.Removed));
// objects changed
if (locState.Objects.IsChanged && events.ObjectListChanged.HasListeners)
events.ObjectListChanged.Raise(new ObjectListChangedEventArgs(location, locState.Objects.Added, locState.Objects.Removed));
// chest items changed
if (events.ChestInventoryChanged.HasListeners)
{
foreach ((Chest chest, SnapshotItemListDiff diff) in locState.ChestItems)
events.ChestInventoryChanged.Raise(new ChestInventoryChangedEventArgs(chest, location, added: diff.Added, removed: diff.Removed, quantityChanged: diff.QuantityChanged));
}
// terrain features changed
if (locState.TerrainFeatures.IsChanged && events.TerrainFeatureListChanged.HasListeners)
events.TerrainFeatureListChanged.Raise(new TerrainFeatureListChangedEventArgs(location, locState.TerrainFeatures.Added, locState.TerrainFeatures.Removed));
// furniture changed
if (locState.Furniture.IsChanged && events.FurnitureListChanged.HasListeners)
events.FurnitureListChanged.Raise(new FurnitureListChangedEventArgs(location, locState.Furniture.Added, locState.Furniture.Removed));
}
}
// raise time changed
if (raiseWorldEvents && state.Time.IsChanged)
{
if (verbose)
this.Monitor.Log($"Context: time changed to {state.Time.New}.");
if (events.TimeChanged.HasListeners)
events.TimeChanged.Raise(new TimeChangedEventArgs(state.Time.Old, state.Time.New));
}
// raise player events
if (raiseWorldEvents)
{
PlayerSnapshot playerState = state.CurrentPlayer!; // not null at this point
Farmer player = playerState.Player;
// raise current location changed
if (playerState.Location.IsChanged)
{
if (verbose)
this.Monitor.Log($"Context: set location to {playerState.Location.New}.");
if (events.Warped.HasListeners)
events.Warped.Raise(new WarpedEventArgs(player, playerState.Location.Old!, playerState.Location.New!));
}
// raise player leveled up a skill
bool raiseLevelChanged = events.LevelChanged.HasListeners;
if (verbose || raiseLevelChanged)
{
foreach ((SkillType skill, var value) in playerState.Skills)
{
if (!value.IsChanged)
continue;
if (verbose)
this.Monitor.Log($"Events: player skill '{skill}' changed from {value.Old} to {value.New}.");
if (raiseLevelChanged)
events.LevelChanged.Raise(new LevelChangedEventArgs(player, skill, value.Old, value.New));
}
}
// raise player inventory changed
if (playerState.Inventory.IsChanged)
{
if (verbose)
this.Monitor.Log("Events: player inventory changed.");
if (events.InventoryChanged.HasListeners)
{
SnapshotItemListDiff inventory = playerState.Inventory;
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;
if (events.GameLaunched.HasListeners)
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)
{
this.AreCustomLanguagesInitialized = true;
this.ContentCore.OnAdditionalLanguagesInitialized();
}
}
/*********
** Game update tick
*********/
{
bool isOneSecond = SCore.TicksElapsed % 60 == 0;
events.UnvalidatedUpdateTicking.RaiseEmpty();
events.UpdateTicking.RaiseEmpty();
if (isOneSecond)
events.OneSecondUpdateTicking.RaiseEmpty();
try
{
instance.Input.ApplyOverrides(); // if mods added any new overrides since the update, process them now
runUpdate();
}
catch (Exception ex)
{
this.LogManager.MonitorForGame.Log($"An error occurred in the base update loop: {ex.GetLogSummary()}", LogLevel.Error);
}
events.UnvalidatedUpdateTicked.RaiseEmpty();
events.UpdateTicked.RaiseEmpty();
if (isOneSecond)
events.OneSecondUpdateTicked.RaiseEmpty();
}
/*********
** Update events
*********/
this.UpdateCrashTimer.Reset();
}
catch (Exception ex)
{
// log error
this.Monitor.Log($"An error occurred 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.");
}
}
/// <summary>Handle the game changing locale.</summary>
private void OnLocaleChanged()
{
this.ContentCore.OnLocaleChanged();
// get locale
string locale = this.ContentCore.GetLocale();
LanguageCode languageCode = this.ContentCore.Language;
// update core translations
this.Translator.SetLocale(locale, languageCode);
// update mod translation helpers
foreach (IModMetadata mod in this.ModRegistry.GetAll())
{
TranslationHelper translations = mod.Translations!; // not null at this point
translations.SetLocale(locale, languageCode);
foreach (ContentPack contentPack in mod.GetFakeContentPacks())
contentPack.TranslationImpl.SetLocale(locale, languageCode);
}
// raise event
if (this.EventManager.LocaleChanged.HasListeners)
{
this.EventManager.LocaleChanged.Raise(
new LocaleChangedEventArgs(
oldLanguage: this.LastLanguage.Code,
oldLocale: this.LastLanguage.Locale,
newLanguage: languageCode,
newLocale: locale
)
);
}
this.LastLanguage = (locale, languageCode);
}
/// <summary>Raised when the low-level stage while loading a save changes.</summary>
/// <param name="newStage">The new load stage.</param>
internal void OnLoadStageChanged(LoadStage newStage)
{
// nothing to do
if (newStage == Context.LoadStage)
return;
// update data
LoadStage oldStage = Context.LoadStage;
Context.LoadStage = newStage;
this.Monitor.VerboseLog($"Context: load stage changed to {newStage}");
// handle stages
switch (newStage)
{
case LoadStage.ReturningToTitle:
this.Monitor.Log("Context: returning to title");
this.OnReturningToTitle();
break;
case LoadStage.None:
this.JustReturnedToTitle = true;
break;
case LoadStage.Loaded:
// override chat box
Game1.onScreenMenus.Remove(Game1.chatBox);
Game1.onScreenMenus.Add(Game1.chatBox = new SChatBox(this.LogManager.MonitorForGame));
break;
}
// raise events
EventManager events = this.EventManager;
if (events.LoadStageChanged.HasListeners)
events.LoadStageChanged.Raise(new LoadStageChangedEventArgs(oldStage, newStage));
if (newStage == LoadStage.None)
events.ReturnedToTitle.RaiseEmpty();
}
/// <summary>A callback invoked before <see cref="Game1.newDayAfterFade"/> runs.</summary>
protected void OnNewDayAfterFade()
{
this.EventManager.DayEnding.RaiseEmpty();
this.Reflection.NewCacheInterval();
}
/// <summary>A callback invoked after an asset is fully loaded through a content manager.</summary>
/// <param name="contentManager">The content manager through which the asset was loaded.</param>
/// <param name="assetName">The asset name that was loaded.</param>
private void OnAssetLoaded(IContentManager contentManager, IAssetName assetName)
{
if (this.EventManager.AssetReady.HasListeners)
this.EventManager.AssetReady.Raise(new AssetReadyEventArgs(assetName, assetName.GetBaseAssetName()));
}
/// <summary>A callback invoked after assets have been invalidated from the content cache.</summary>
/// <param name="assetNames">The invalidated asset names.</param>
private void OnAssetsInvalidated(IList<IAssetName> assetNames)
{
if (this.EventManager.AssetsInvalidated.HasListeners)
this.EventManager.AssetsInvalidated.Raise(new AssetsInvalidatedEventArgs(assetNames, assetNames.Select(p => p.GetBaseAssetName())));
}
/// <summary>Get the load/edit operations to apply to an asset by querying registered <see cref="IContentEvents.AssetRequested"/> event handlers.</summary>
/// <param name="asset">The asset info being requested.</param>
private AssetOperationGroup? RequestAssetOperations(IAssetInfo asset)
{
// get event
var requestedEvent = this.EventManager.AssetRequested;
if (!requestedEvent.HasListeners)
return null;
// raise event
AssetRequestedEventArgs args = new(asset, this.GetOnBehalfOfContentPack);
requestedEvent.Raise(
invoke: (mod, invoke) =>
{
args.SetMod(mod);
invoke(args);
}
);
// collect operations
return args.LoadOperations.Count != 0 || args.EditOperations.Count != 0
? new AssetOperationGroup(args.LoadOperations, args.EditOperations)
: null;
}
/// <summary>Get the mod metadata for a content pack whose ID matches <paramref name="id"/>, if it's a valid content pack for the given <paramref name="mod"/>.</summary>
/// <param name="mod">The mod requesting to act on the content pack's behalf.</param>
/// <param name="id">The content pack ID.</param>
/// <param name="verb">The verb phrase indicating what action will be performed, like 'load assets' or 'edit assets'.</param>
/// <returns>Returns the content pack metadata if valid, else <c>null</c>.</returns>
private IModMetadata? GetOnBehalfOfContentPack(IModMetadata mod, string? id, string verb)
{
if (id == null)
return null;
string errorPrefix = $"Can't {verb} on behalf of content pack ID '{id}'";
// get target mod
IModMetadata? onBehalfOf = this.ModRegistry.Get(id);
if (onBehalfOf == null)
{
mod.LogAsModOnce($"{errorPrefix}: there's no content pack installed with that ID.", LogLevel.Warn);
return null;
}
// make sure it's a content pack for the requesting mod
if (!onBehalfOf.IsContentPack || !string.Equals(onBehalfOf.Manifest.ContentPackFor?.UniqueID, mod.Manifest.UniqueID, StringComparison.OrdinalIgnoreCase))
{
mod.LogAsModOnce($"{errorPrefix}: that isn't a content pack for this mod.", LogLevel.Warn);
return null;
}
return onBehalfOf;
}
/// <summary>Raised immediately before the player returns to the title screen.</summary>
private void OnReturningToTitle()
{
// perform cleanup
this.Multiplayer.CleanupOnMultiplayerExit();
this.ContentCore.OnReturningToTitleScreen();
}
/// <summary>Raised before the game exits.</summary>
private void OnGameExiting()
{
this.Multiplayer.Disconnect(StardewValley.Multiplayer.DisconnectType.ClosedGame);
this.Dispose();
}
/// <summary>Raised when a mod network message is received.</summary>
/// <param name="message">The message to deliver to applicable mods.</param>
private void OnModMessageReceived(ModMessageModel message)
{
if (this.EventManager.ModMessageReceived.HasListeners)
{
// get mod IDs to notify
HashSet<string> modIDs = new(message.ToModIDs ?? this.ModRegistry.GetAll().Select(p => p.Manifest.UniqueID), StringComparer.OrdinalIgnoreCase);
if (message.FromPlayerID == Game1.player?.UniqueMultiplayerID)
modIDs.Remove(message.FromModID); // don't send a broadcast back to the sender
// raise events
ModMessageReceivedEventArgs? args = null;
this.EventManager.ModMessageReceived.Raise(
invoke: (mod, invoke) =>
{
if (modIDs.Contains(mod.Manifest.UniqueID))
{
args ??= new(message, this.Toolkit.JsonHelper);
invoke(args);
}
}
);
}
}
/// <summary>Constructor a content manager to read game content files.</summary>
/// <param name="serviceProvider">The service provider to use to locate services.</param>
/// <param name="rootDirectory">The root directory to search for content.</param>
private LocalizedContentManager CreateContentManager(IServiceProvider serviceProvider, string rootDirectory)
{
// Game1._temporaryContent initializing from SGame constructor
// ReSharper disable once ConditionIsAlwaysTrueOrFalse -- this is the method that initializes it
if (this.ContentCore == null)
{
this.ContentCore = new ContentCoordinator(
serviceProvider: serviceProvider,
rootDirectory: rootDirectory,
currentCulture: Thread.CurrentThread.CurrentUICulture,
monitor: this.Monitor,
reflection: this.Reflection,
jsonHelper: this.Toolkit.JsonHelper,
onLoadingFirstAsset: this.InitializeBeforeFirstAssetLoaded,
onAssetLoaded: this.OnAssetLoaded,
onAssetsInvalidated: this.OnAssetsInvalidated,
getFileLookup: this.GetFileLookup,
requestAssetOperations: this.RequestAssetOperations,
useRawImageLoading: this.Settings.UseRawImageLoading
);
if (this.ContentCore.Language != this.Translator.LocaleEnum)
this.Translator.SetLocale(this.ContentCore.GetLocale(), this.ContentCore.Language);
this.NextContentManagerIsMain = true;
return this.ContentCore.CreateGameContentManager("Game1._temporaryContent");
}
// Game1.content initializing from LoadContent
if (this.NextContentManagerIsMain)
{
this.NextContentManagerIsMain = false;
return this.ContentCore.MainContentManager;
}
// any other content manager
return this.ContentCore.CreateGameContentManager("(generated)");
}
/// <summary>Get the current game instance. This may not be the main player if playing in split-screen.</summary>
private SGame GetCurrentGameInstance()
{
return Game1.game1 as SGame
?? throw new InvalidOperationException("The current game instance wasn't created by SMAPI.");
}
/// <summary>Look for common issues with the game's XNB content, and log warnings if anything looks broken or outdated.</summary>
/// <returns>Returns whether all integrity checks passed.</returns>
private bool ValidateContentIntegrity()
{
this.Monitor.Log("Detecting common issues...");
bool issuesFound = false;
// object format (commonly broken by outdated files)
{
// detect issues
bool hasObjectIssues = false;
void LogIssue(int id, string issue) => this.Monitor.Log($@"Detected issue: item #{id} in Content\Data\ObjectInformation.xnb is invalid ({issue}).");
foreach ((int id, string? fieldsStr) in Game1.objectInformation)
{
// must not be empty
if (string.IsNullOrWhiteSpace(fieldsStr))
{
LogIssue(id, "entry is empty");
hasObjectIssues = true;
continue;
}
// require core fields
string[] fields = fieldsStr.Split('/');
if (fields.Length < SObject.objectInfoDescriptionIndex + 1)
{
LogIssue(id, "too few fields for an object");
hasObjectIssues = true;
continue;
}
// check min length for specific types
switch (fields[SObject.objectInfoTypeIndex].Split(new[] { ' ' }, 2)[0])
{
case "Cooking":
if (fields.Length < SObject.objectInfoBuffDurationIndex + 1)
{
LogIssue(id, "too few fields for a cooking item");
hasObjectIssues = true;
}
break;
}
}
// log error
if (hasObjectIssues)
{
issuesFound = true;
this.Monitor.Log(@"Your Content\Data\ObjectInformation.xnb file seems to be broken or outdated.", LogLevel.Warn);
}
}
return !issuesFound;
}
/// <summary>Set the titles for the game and console windows.</summary>
private void UpdateWindowTitles()
{
string consoleTitle = $"SMAPI {Constants.ApiVersion} - running Stardew Valley {Constants.GameVersion}";
string gameTitle = $"Stardew Valley {Constants.GameVersion} - running SMAPI {Constants.ApiVersion}";
if (this.ModRegistry.AreAllModsLoaded)
{
int modsLoaded = this.ModRegistry.GetAll().Count();
consoleTitle += $" with {modsLoaded} mods";
gameTitle += $" with {modsLoaded} mods";
}
this.Game.Window.Title = gameTitle;
this.LogManager.SetConsoleTitle(consoleTitle);
}
/// <summary>Log a warning if software known to cause issues is installed.</summary>
private void CheckForSoftwareConflicts()
{
#if SMAPI_FOR_WINDOWS
this.Monitor.Log("Checking for known software conflicts...");
try
{
string[] registryKeys = { @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall", @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" };
string[] installedNames = registryKeys
.SelectMany(registryKey =>
{
using RegistryKey? key = Registry.LocalMachine.OpenSubKey(registryKey);
if (key == null)
return Array.Empty<string>();
return key
.GetSubKeyNames()
.Select(subkeyName =>
{
using RegistryKey? subkey = key.OpenSubKey(subkeyName);
string? displayName = (string?)subkey?.GetValue("DisplayName");
string? displayVersion = (string?)subkey?.GetValue("DisplayVersion");
if (displayName != null && displayVersion != null && displayName.EndsWith($" {displayVersion}"))
displayName = displayName.Substring(0, displayName.Length - displayVersion.Length - 1);
return displayName;
})
.ToArray();
})
.Where(name => name != null && (name.Contains("MSI Afterburner") || name.Contains("RivaTuner")))
.Select(name => name!)
.Distinct()
.OrderBy(name => name)
.ToArray();
if (installedNames.Any())
this.Monitor.Log($"Found {string.Join(" and ", installedNames)} installed, which may conflict with SMAPI. If you experience errors or crashes, try disabling that software or adding an exception for SMAPI and Stardew Valley.", LogLevel.Warn);
else
this.Monitor.Log(" None found!");
}
catch (Exception ex)
{
this.Monitor.Log($"Failed when checking for conflicting software. Technical details:\n{ex}");
}
#endif
}
/// <summary>Asynchronously check for a new version of SMAPI and any installed mods, and print alerts to the console if an update is available.</summary>
/// <param name="mods">The mods to include in the update check (if eligible).</param>
private async Task CheckForUpdatesAsync(IModMetadata[] mods)
{
try
{
if (!this.Settings.CheckForUpdates)
return;
// create client
using WebApiClient client = new(this.Settings.WebApiBaseUrl, Constants.ApiVersion);
this.Monitor.Log("Checking for updates...");
// check SMAPI version
{
ISemanticVersion? updateFound = null;
string? updateUrl = null;
try
{
// fetch update check
IDictionary<string, ModEntryModel> response = await client.GetModInfoAsync(
mods: new[] { new ModSearchEntryModel("Pathoschild.SMAPI", Constants.ApiVersion, new[] { $"GitHub:{this.Settings.GitHubProjectName}" }) },
apiVersion: Constants.ApiVersion,
gameVersion: Constants.GameVersion,
platform: Constants.Platform
);
ModEntryModel updateInfo = response.Single().Value;
updateFound = updateInfo.SuggestedUpdate?.Version;
updateUrl = updateInfo.SuggestedUpdate?.Url;
// log message
if (updateFound != null)
this.Monitor.Log($"You can update SMAPI to {updateFound}: {updateUrl}", LogLevel.Alert);
else
this.Monitor.Log(" SMAPI okay.");
// show errors
if (updateInfo.Errors.Any())
{
this.Monitor.Log("Couldn't check for a new version of SMAPI. This won't affect your game, but you may not be notified of new versions if this keeps happening.", LogLevel.Warn);
this.Monitor.Log($"Error: {string.Join("\n", updateInfo.Errors)}");
}
}
catch (Exception ex)
{
this.Monitor.Log("Couldn't check for a new version of SMAPI. This won't affect your game, but you won't be notified of new versions if this keeps happening.", LogLevel.Warn);
this.Monitor.Log(ex is WebException && ex.InnerException == null
? $"Error: {ex.Message}"
: $"Error: {ex.GetLogSummary()}"
);
}
// show update message on next launch
if (updateFound != null)
this.LogManager.WriteUpdateMarker(updateFound.ToString(), updateUrl ?? Constants.HomePageUrl);
}
// check mod versions
if (mods.Any())
{
try
{
HashSet<string> suppressUpdateChecks = this.Settings.SuppressUpdateChecks;
// prepare search model
List<ModSearchEntryModel> searchMods = new List<ModSearchEntryModel>();
foreach (IModMetadata mod in mods)
{
if (!mod.HasID() || suppressUpdateChecks.Contains(mod.Manifest.UniqueID))
continue;
string[] updateKeys = mod
.GetUpdateKeys(validOnly: true)
.Select(p => p.ToString())
.ToArray();
searchMods.Add(new ModSearchEntryModel(mod.Manifest.UniqueID, mod.Manifest.Version, updateKeys.ToArray(), isBroken: mod.Status == ModMetadataStatus.Failed));
}
// fetch results
this.Monitor.Log($" Checking for updates to {searchMods.Count} mods...");
IDictionary<string, ModEntryModel> results = await client.GetModInfoAsync(searchMods.ToArray(), apiVersion: Constants.ApiVersion, gameVersion: Constants.GameVersion, platform: Constants.Platform);
// extract update alerts & errors
var updates = new List<Tuple<IModMetadata, ISemanticVersion, string>>();
var errors = new StringBuilder();
foreach (IModMetadata mod in mods.OrderBy(p => p.DisplayName))
{
// link to update-check data
if (!mod.HasID() || !results.TryGetValue(mod.Manifest.UniqueID, out ModEntryModel? result))
continue;
mod.SetUpdateData(result);
// handle errors
if (result.Errors.Any())
{
errors.AppendLine(result.Errors.Length == 1
? $" {mod.DisplayName}: {result.Errors[0]}"
: $" {mod.DisplayName}:\n - {string.Join("\n - ", result.Errors)}"
);
}
// handle update
if (result.SuggestedUpdate != null)
updates.Add(Tuple.Create(mod, result.SuggestedUpdate.Version, result.SuggestedUpdate.Url));
}
// show update errors
if (errors.Length != 0)
this.Monitor.Log("Got update-check errors for some mods:\n" + errors.ToString().TrimEnd());
// show update alerts
if (updates.Any())
{
this.Monitor.Newline();
this.Monitor.Log($"You can update {updates.Count} mod{(updates.Count != 1 ? "s" : "")}:", LogLevel.Alert);
foreach ((IModMetadata mod, ISemanticVersion newVersion, string newUrl) in updates)
this.Monitor.Log($" {mod.DisplayName} {newVersion}: {newUrl}", LogLevel.Alert);
}
else
this.Monitor.Log(" All mods up to date.");
}
catch (Exception ex)
{
this.Monitor.Log("Couldn't check for new mod versions. This won't affect your game, but you won't be notified of mod updates if this keeps happening.", LogLevel.Warn);
this.Monitor.Log(ex is WebException && ex.InnerException == null
? ex.Message
: ex.ToString()
);
}
}
}
catch (Exception ex)
{
this.Monitor.Log("Couldn't check for updates. This won't affect your game, but you won't be notified of SMAPI or mod updates if this keeps happening.", LogLevel.Warn);
this.Monitor.Log(ex is WebException && ex.InnerException == null
? ex.Message
: ex.ToString()
);
}
}
/// <summary>Create a directory path if it doesn't exist.</summary>
/// <param name="path">The directory path.</param>
private void VerifyPath(string path)
{
try
{
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
}
catch (Exception ex)
{
// note: this happens before this.Monitor is initialized
Console.WriteLine($"Couldn't create a path: {path}\n\n{ex.GetLogSummary()}");
}
}
/// <summary>Load and hook up the given mods.</summary>
/// <param name="mods">The mods to load.</param>
/// <param name="jsonHelper">The JSON helper with which to read mods' JSON files.</param>
/// <param name="contentCore">The content manager to use for mod content.</param>
/// <param name="modDatabase">Handles access to SMAPI's internal mod metadata list.</param>
private void LoadMods(IModMetadata[] mods, JsonHelper jsonHelper, ContentCoordinator contentCore, ModDatabase modDatabase)
{
this.Monitor.Log("Loading mods...", LogLevel.Debug);
// load mods
IList<IModMetadata> skippedMods = new List<IModMetadata>();
using (AssemblyLoader modAssemblyLoader = new(Constants.Platform, this.Monitor, this.Settings.ParanoidWarnings, this.Settings.RewriteMods))
{
// init
HashSet<string> suppressUpdateChecks = this.Settings.SuppressUpdateChecks;
IInterfaceProxyFactory proxyFactory = new InterfaceProxyFactory();
// load mods
foreach (IModMetadata mod in mods)
{
if (!this.TryLoadMod(mod, mods, modAssemblyLoader, proxyFactory, jsonHelper, contentCore, modDatabase, suppressUpdateChecks, out ModFailReason? failReason, out string? errorPhrase, out string? errorDetails))
{
mod.SetStatus(ModMetadataStatus.Failed, failReason.Value, errorPhrase, errorDetails);
skippedMods.Add(mod);
}
}
}
IModMetadata[] loaded = this.ModRegistry.GetAll().ToArray();
IModMetadata[] loadedContentPacks = loaded.Where(p => p.IsContentPack).ToArray();
IModMetadata[] loadedMods = loaded.Where(p => !p.IsContentPack).ToArray();
// unlock content packs
this.ModRegistry.AreAllModsLoaded = true;
// log mod info
this.LogManager.LogModInfo(loaded, loadedContentPacks, loadedMods, skippedMods.ToArray(), this.Settings.ParanoidWarnings);
// initialize translations
this.ReloadTranslations(loaded);
// set temporary PyTK compatibility mode
// This is part of a three-part fix for PyTK 1.23.0 and earlier. When removing this,
// search 'Platonymous.Toolkit' to find the other part in SMAPI and Content Patcher.
{
IModInfo? pyTk = this.ModRegistry.Get("Platonymous.Toolkit");
ModContentManager.EnablePyTkLegacyMode = pyTk is not null && pyTk.Manifest.Version.IsOlderThan("1.23.1");
}
// initialize loaded non-content-pack mods
this.Monitor.Log("Launching mods...", LogLevel.Debug);
foreach (IModMetadata metadata in loadedMods)
{
#if SMAPI_DEPRECATED
// add interceptors
if (metadata.Mod?.Helper is ModHelper helper)
{
// ReSharper disable SuspiciousTypeConversion.Global
if (metadata.Mod is IAssetEditor editor)
{
SCore.DeprecationManager.Warn(
source: metadata,
nounPhrase: $"{nameof(IAssetEditor)}",
version: "3.14.0",
severity: DeprecationLevel.Notice,
logStackTrace: false
);
this.ContentCore.Editors.Add(new ModLinked<IAssetEditor>(metadata, editor));
}
if (metadata.Mod is IAssetLoader loader)
{
SCore.DeprecationManager.Warn(
source: metadata,
nounPhrase: $"{nameof(IAssetLoader)}",
version: "3.14.0",
severity: DeprecationLevel.Notice,
logStackTrace: false
);
this.ContentCore.Loaders.Add(new ModLinked<IAssetLoader>(metadata, loader));
}
// ReSharper restore SuspiciousTypeConversion.Global
ContentHelper content = helper.GetLegacyContentHelper();
content.ObservableAssetEditors.CollectionChanged += (_, e) => this.OnAssetInterceptorsChanged(metadata, e.NewItems?.Cast<IAssetEditor>(), e.OldItems?.Cast<IAssetEditor>(), this.ContentCore.Editors);
content.ObservableAssetLoaders.CollectionChanged += (_, e) => this.OnAssetInterceptorsChanged(metadata, e.NewItems?.Cast<IAssetLoader>(), e.OldItems?.Cast<IAssetLoader>(), this.ContentCore.Loaders);
}
// log deprecation warnings
if (metadata.HasWarnings(ModWarning.DetectedLegacyCachingDll, ModWarning.DetectedLegacyConfigurationDll, ModWarning.DetectedLegacyPermissionsDll))
{
string?[] referenced =
new[]
{
metadata.Warnings.HasFlag(ModWarning.DetectedLegacyConfigurationDll) ? "System.Configuration.ConfigurationManager" : null,
metadata.Warnings.HasFlag(ModWarning.DetectedLegacyCachingDll) ? "System.Runtime.Caching" : null,
metadata.Warnings.HasFlag(ModWarning.DetectedLegacyPermissionsDll) ? "System.Security.Permissions" : null
}
.Where(p => p is not null)
.ToArray();
foreach (string? name in referenced)
{
DeprecationManager.Warn(
metadata,
$"using {name} without bundling it",
"3.14.7",
DeprecationLevel.Notice,
logStackTrace: false
);
}
}
#endif
// call entry method
Context.HeuristicModsRunningCode.Push(metadata);
try
{
IMod mod = metadata.Mod!;
mod.Entry(mod.Helper!);
}
catch (Exception ex)
{
metadata.LogAsMod($"Mod crashed on entry and might not work correctly. Technical details:\n{ex.GetLogSummary()}", LogLevel.Error);
}
// get mod API
try
{
object? api = metadata.Mod!.GetApi();
if (api != null && !api.GetType().IsPublic)
{
api = null;
this.Monitor.Log($"{metadata.DisplayName} provides an API instance with a non-public type. This isn't currently supported, so the API won't be available to other mods.", LogLevel.Warn);
}
if (api != null)
this.Monitor.Log($" Found mod-provided API ({api.GetType().FullName}).");
metadata.SetApi(api);
}
catch (Exception ex)
{
this.Monitor.Log($"Failed loading mod-provided API for {metadata.DisplayName}. Integrations with other mods may not work. Error: {ex.GetLogSummary()}", LogLevel.Error);
}
Context.HeuristicModsRunningCode.TryPop(out _);
}
// unlock mod integrations
this.ModRegistry.AreAllModsInitialized = true;
this.Monitor.Log("Mods loaded and ready!", LogLevel.Debug);
}
#if SMAPI_DEPRECATED
/// <summary>Raised after a mod adds or removes asset interceptors.</summary>
/// <typeparam name="T">The asset interceptor type (one of <see cref="IAssetEditor"/> or <see cref="IAssetLoader"/>).</typeparam>
/// <param name="mod">The mod metadata.</param>
/// <param name="added">The interceptors that were added.</param>
/// <param name="removed">The interceptors that were removed.</param>
/// <param name="list">A list of interceptors to update for the change.</param>
private void OnAssetInterceptorsChanged<T>(IModMetadata mod, IEnumerable<T>? added, IEnumerable<T>? removed, IList<ModLinked<T>> list)
where T : notnull
{
foreach (T interceptor in added ?? Array.Empty<T>())
{
this.ReloadAssetInterceptorsQueue.Add(new AssetInterceptorChange(mod, interceptor, wasAdded: true));
list.Add(new ModLinked<T>(mod, interceptor));
}
foreach (T interceptor in removed ?? Array.Empty<T>())
{
this.ReloadAssetInterceptorsQueue.Add(new AssetInterceptorChange(mod, interceptor, wasAdded: false));
foreach (ModLinked<T> entry in list.Where(p => p.Mod == mod && object.ReferenceEquals(p.Data, interceptor)).ToArray())
list.Remove(entry);
}
}
#endif
/// <summary>Load a given mod.</summary>
/// <param name="mod">The mod to load.</param>
/// <param name="mods">The mods being loaded.</param>
/// <param name="assemblyLoader">Preprocesses and loads mod assemblies.</param>
/// <param name="proxyFactory">Generates proxy classes to access mod APIs through an arbitrary interface.</param>
/// <param name="jsonHelper">The JSON helper with which to read mods' JSON files.</param>
/// <param name="contentCore">The content manager to use for mod content.</param>
/// <param name="modDatabase">Handles access to SMAPI's internal mod metadata list.</param>
/// <param name="suppressUpdateChecks">The mod IDs to ignore when validating update keys.</param>
/// <param name="failReason">The reason the mod couldn't be loaded, if applicable.</param>
/// <param name="errorReasonPhrase">The user-facing reason phrase explaining why the mod couldn't be loaded (if applicable).</param>
/// <param name="errorDetails">More detailed details about the error intended for developers (if any).</param>
/// <returns>Returns whether the mod was successfully loaded.</returns>
private bool TryLoadMod(IModMetadata mod, IModMetadata[] mods, AssemblyLoader assemblyLoader, IInterfaceProxyFactory proxyFactory, JsonHelper jsonHelper, ContentCoordinator contentCore, ModDatabase modDatabase, HashSet<string> suppressUpdateChecks, [NotNullWhen(false)] out ModFailReason? failReason, out string? errorReasonPhrase, out string? errorDetails)
{
errorDetails = null;
// log entry
{
string relativePath = mod.GetRelativePathWithRoot();
if (mod.IsContentPack)
this.Monitor.Log($" {mod.DisplayName} (from {relativePath}) [content pack]...");
// ReSharper disable once ConstantConditionalAccessQualifier -- mod may be invalid at this point
else if (mod.Manifest?.EntryDll != null)
this.Monitor.Log($" {mod.DisplayName} (from {relativePath}{Path.DirectorySeparatorChar}{mod.Manifest.EntryDll})..."); // don't use Path.Combine here, since EntryDLL might not be valid
else
this.Monitor.Log($" {mod.DisplayName} (from {relativePath})...");
}
// add warning for missing update key
if (mod.HasID() && !suppressUpdateChecks.Contains(mod.Manifest!.UniqueID) && !mod.HasValidUpdateKeys())
mod.SetWarning(ModWarning.NoUpdateKeys);
// validate status
if (mod.Status == ModMetadataStatus.Failed)
{
this.Monitor.Log($" Failed: {mod.ErrorDetails ?? mod.Error}");
failReason = mod.FailReason ?? ModFailReason.LoadFailed;
errorReasonPhrase = mod.Error;
return false;
}
IManifest manifest = mod.Manifest!;
// validate dependencies
// Although dependencies are validated before mods are loaded, a dependency may have failed to load.
foreach (IManifestDependency dependency in manifest.Dependencies.Where(p => p.IsRequired))
{
if (this.ModRegistry.Get(dependency.UniqueID) == null)
{
string dependencyName = mods
.FirstOrDefault(otherMod => otherMod.HasID(dependency.UniqueID))
?.DisplayName ?? dependency.UniqueID;
errorReasonPhrase = $"it needs the '{dependencyName}' mod, which couldn't be loaded.";
failReason = ModFailReason.MissingDependencies;
return false;
}
}
// load as content pack
if (mod.IsContentPack)
{
IMonitor monitor = this.LogManager.GetMonitor(manifest.UniqueID, mod.DisplayName);
IFileLookup fileLookup = this.GetFileLookup(mod.DirectoryPath);
GameContentHelper gameContentHelper = new(this.ContentCore, mod, mod.DisplayName, monitor, this.Reflection);
IModContentHelper modContentHelper = new ModContentHelper(this.ContentCore, mod.DirectoryPath, mod, mod.DisplayName, gameContentHelper.GetUnderlyingContentManager(), this.Reflection);
TranslationHelper translationHelper = new(mod, contentCore.GetLocale(), contentCore.Language);
IContentPack contentPack = new ContentPack(mod.DirectoryPath, manifest, modContentHelper, translationHelper, jsonHelper, fileLookup);
mod.SetMod(contentPack, monitor, translationHelper);
this.ModRegistry.Add(mod);
errorReasonPhrase = null;
failReason = null;
return true;
}
// load as mod
else
{
// get mod info
FileInfo assemblyFile = this.GetFileLookup(mod.DirectoryPath).GetFile(manifest.EntryDll!);
// load mod
Assembly modAssembly;
try
{
modAssembly = assemblyLoader.Load(mod, assemblyFile, assumeCompatible: mod.DataRecord?.Status == ModStatus.AssumeCompatible);
this.ModRegistry.TrackAssemblies(mod, modAssembly);
}
catch (IncompatibleInstructionException) // details already in trace logs
{
string[] updateUrls = new[] { modDatabase.GetModPageUrlFor(manifest.UniqueID), "https://smapi.io/mods" }.Where(p => p != null).ToArray()!;
errorReasonPhrase = $"it's no longer compatible. Please check for a new version at {string.Join(" or ", updateUrls)}";
failReason = ModFailReason.Incompatible;
return false;
}
catch (SAssemblyLoadFailedException ex)
{
errorReasonPhrase = $"its DLL couldn't be loaded: {ex.Message}";
failReason = ModFailReason.LoadFailed;
return false;
}
catch (Exception ex)
{
errorReasonPhrase = "its DLL couldn't be loaded.";
if (ex is BadImageFormatException && !EnvironmentUtility.Is64BitAssembly(assemblyFile.FullName))
errorReasonPhrase = "it needs to be updated for 64-bit mode.";
errorDetails = $"Error: {ex.GetLogSummary()}";
failReason = ModFailReason.LoadFailed;
return false;
}
// initialize mod
try
{
// get mod instance
if (!this.TryLoadModEntry(mod, modAssembly, out Mod? modEntry, out errorReasonPhrase))
{
failReason = ModFailReason.LoadFailed;
return false;
}
// get content packs
IContentPack[] GetContentPacks()
{
if (!this.ModRegistry.AreAllModsLoaded)
throw new InvalidOperationException("Can't access content packs before SMAPI finishes loading mods.");
return this.ModRegistry
.GetAll(assemblyMods: false)
.Where(p => p.IsContentPack && mod.HasID(p.Manifest.ContentPackFor!.UniqueID))
.Select(p => p.ContentPack!)
.ToArray();
}
// init mod helpers
IMonitor monitor = this.LogManager.GetMonitor(manifest.UniqueID, mod.DisplayName);
TranslationHelper translationHelper = new(mod, contentCore.GetLocale(), contentCore.Language);
IModHelper modHelper;
{
IModEvents events = new ModEvents(mod, this.EventManager);
ICommandHelper commandHelper = new CommandHelper(mod, this.CommandManager);
#if SMAPI_DEPRECATED
ContentHelper contentHelper = new(contentCore, mod.DirectoryPath, mod, monitor, this.Reflection);
#endif
GameContentHelper gameContentHelper = new(contentCore, mod, mod.DisplayName, monitor, this.Reflection);
IModContentHelper modContentHelper = new ModContentHelper(contentCore, mod.DirectoryPath, mod, mod.DisplayName, gameContentHelper.GetUnderlyingContentManager(), this.Reflection);
IContentPackHelper contentPackHelper = new ContentPackHelper(
mod: mod,
contentPacks: new Lazy<IContentPack[]>(GetContentPacks),
createContentPack: (dirPath, fakeManifest) => this.CreateFakeContentPack(dirPath, fakeManifest, contentCore, mod)
);
IDataHelper dataHelper = new DataHelper(mod, mod.DirectoryPath, jsonHelper);
IReflectionHelper reflectionHelper = new ReflectionHelper(mod, mod.DisplayName, this.Reflection);
IModRegistry modRegistryHelper = new ModRegistryHelper(mod, this.ModRegistry, proxyFactory, monitor);
IMultiplayerHelper multiplayerHelper = new MultiplayerHelper(mod, this.Multiplayer);
modHelper = new ModHelper(mod, mod.DirectoryPath, () => this.GetCurrentGameInstance().Input, events,
#if SMAPI_DEPRECATED
contentHelper,
#endif
gameContentHelper, modContentHelper, contentPackHelper, commandHelper, dataHelper, modRegistryHelper, reflectionHelper, multiplayerHelper, translationHelper);
}
// init mod
modEntry.ModManifest = manifest;
modEntry.Helper = modHelper;
modEntry.Monitor = monitor;
// track mod
mod.SetMod(modEntry, translationHelper);
this.ModRegistry.Add(mod);
failReason = null;
return true;
}
catch (Exception ex)
{
errorReasonPhrase = $"initialization failed:\n{ex.GetLogSummary()}";
failReason = ModFailReason.LoadFailed;
return false;
}
}
}
/// <summary>Create a fake content pack instance for a parent mod.</summary>
/// <param name="packDirPath">The absolute path to the fake content pack's directory.</param>
/// <param name="packManifest">The fake content pack's manifest.</param>
/// <param name="contentCore">The content manager to use for mod content.</param>
/// <param name="parentMod">The mod for which the content pack is being created.</param>
private IContentPack CreateFakeContentPack(string packDirPath, IManifest packManifest, ContentCoordinator contentCore, IModMetadata parentMod)
{
// create fake mod info
string relativePath = Path.GetRelativePath(Constants.ModsPath, packDirPath);
IModMetadata fakeMod = new ModMetadata(
displayName: packManifest.Name,
directoryPath: packDirPath,
rootPath: Constants.ModsPath,
manifest: packManifest,
dataRecord: null,
isIgnored: false
);
// create mod helpers
IMonitor packMonitor = this.LogManager.GetMonitor(packManifest.UniqueID, packManifest.Name);
GameContentHelper gameContentHelper = new(contentCore, fakeMod, packManifest.Name, packMonitor, this.Reflection);
IModContentHelper packContentHelper = new ModContentHelper(contentCore, packDirPath, fakeMod, packManifest.Name, gameContentHelper.GetUnderlyingContentManager(), this.Reflection);
TranslationHelper packTranslationHelper = new(fakeMod, contentCore.GetLocale(), contentCore.Language);
// add content pack
IFileLookup fileLookup = this.GetFileLookup(packDirPath);
ContentPack contentPack = new(packDirPath, packManifest, packContentHelper, packTranslationHelper, this.Toolkit.JsonHelper, fileLookup);
this.ReloadTranslationsForTemporaryContentPack(parentMod, contentPack);
parentMod.FakeContentPacks.Add(new WeakReference<ContentPack>(contentPack));
// log change
string pathLabel = packDirPath.Contains("..") ? packDirPath : relativePath;
this.Monitor.Log($"{parentMod.DisplayName} created dynamic content pack '{packManifest.Name}' (unique ID: {packManifest.UniqueID}{(packManifest.Name.Contains(pathLabel) ? "" : $", path: {pathLabel}")}).");
return contentPack;
}
/// <summary>Load a mod's entry class.</summary>
/// <param name="metadata">The mod metadata whose entry class is being loaded.</param>
/// <param name="modAssembly">The mod assembly.</param>
/// <param name="mod">The loaded instance.</param>
/// <param name="error">The error indicating why loading failed (if applicable).</param>
/// <returns>Returns whether the mod entry class was successfully loaded.</returns>
private bool TryLoadModEntry(IModMetadata metadata, Assembly modAssembly, [NotNullWhen(true)] out Mod? mod, [NotNullWhen(false)] out string? error)
{
mod = null;
// find type
TypeInfo[] modEntries = modAssembly.DefinedTypes.Where(type => typeof(Mod).IsAssignableFrom(type) && !type.IsAbstract).Take(2).ToArray();
if (modEntries.Length == 0)
{
error = $"its DLL has no '{nameof(Mod)}' subclass.";
return false;
}
if (modEntries.Length > 1)
{
error = $"its DLL contains multiple '{nameof(Mod)}' subclasses.";
return false;
}
// get implementation
Context.HeuristicModsRunningCode.Push(metadata);
try
{
mod = (Mod?)modAssembly.CreateInstance(modEntries[0].ToString());
}
finally
{
Context.HeuristicModsRunningCode.TryPop(out _);
}
if (mod == null)
{
error = "its entry class couldn't be instantiated.";
return false;
}
error = null;
return true;
}
/// <summary>Reload translations for all mods.</summary>
private void ReloadTranslations()
{
this.ReloadTranslations(this.ModRegistry.GetAll());
}
/// <summary>Reload translations for the given mods.</summary>
/// <param name="mods">The mods for which to reload translations.</param>
private void ReloadTranslations(IEnumerable<IModMetadata> mods)
{
// core SMAPI translations
{
var translations = this.ReadTranslationFiles(Path.Combine(Constants.InternalFilesPath, "i18n"), out IList<string> errors);
if (errors.Any() || !translations.Any())
{
this.Monitor.Log("SMAPI couldn't load some core translations. You may need to reinstall SMAPI.", LogLevel.Warn);
foreach (string error in errors)
this.Monitor.Log($" - {error}", LogLevel.Warn);
}
this.Translator.SetTranslations(translations);
}
// mod translations
foreach (IModMetadata metadata in mods)
{
// top-level mod
{
var translations = this.ReadTranslationFiles(Path.Combine(metadata.DirectoryPath, "i18n"), out IList<string> errors);
if (errors.Any())
{
metadata.LogAsMod("Mod couldn't load some translation files:", LogLevel.Warn);
foreach (string error in errors)
metadata.LogAsMod($" - {error}", LogLevel.Warn);
}
metadata.Translations!.SetTranslations(translations);
}
// fake content packs
foreach (ContentPack pack in metadata.GetFakeContentPacks())
this.ReloadTranslationsForTemporaryContentPack(metadata, pack);
}
}
/// <summary>Load or reload translations for a temporary content pack created by a mod.</summary>
/// <param name="parentMod">The parent mod which created the content pack.</param>
/// <param name="contentPack">The content pack instance.</param>
private void ReloadTranslationsForTemporaryContentPack(IModMetadata parentMod, ContentPack contentPack)
{
var translations = this.ReadTranslationFiles(Path.Combine(contentPack.DirectoryPath, "i18n"), out IList<string> errors);
if (errors.Any())
{
parentMod.LogAsMod($"Generated content pack at '{PathUtilities.GetRelativePath(Constants.ModsPath, contentPack.DirectoryPath)}' couldn't load some translation files:", LogLevel.Warn);
foreach (string error in errors)
parentMod.LogAsMod($" - {error}", LogLevel.Warn);
}
contentPack.TranslationImpl.SetTranslations(translations);
}
/// <summary>Read translations from a directory containing JSON translation files.</summary>
/// <param name="folderPath">The folder path to search.</param>
/// <param name="errors">The errors indicating why translation files couldn't be parsed, indexed by translation filename.</param>
private IDictionary<string, IDictionary<string, string>> ReadTranslationFiles(string folderPath, out IList<string> errors)
{
JsonHelper jsonHelper = this.Toolkit.JsonHelper;
// read translation files
var translations = new Dictionary<string, IDictionary<string, string>>();
errors = new List<string>();
DirectoryInfo translationsDir = new(folderPath);
if (translationsDir.Exists)
{
foreach (FileInfo file in translationsDir.EnumerateFiles("*.json"))
{
string locale = Path.GetFileNameWithoutExtension(file.Name.ToLower().Trim());
try
{
if (!jsonHelper.ReadJsonFileIfExists(file.FullName, out IDictionary<string, string>? data))
{
errors.Add($"{file.Name} file couldn't be read"); // mainly happens when the file is corrupted or empty
continue;
}
translations[locale] = data;
}
catch (Exception ex)
{
errors.Add($"{file.Name} file couldn't be parsed: {ex.GetLogSummary()}");
}
}
}
// validate translations
foreach (string locale in translations.Keys.ToArray())
{
// handle duplicates
HashSet<string> keys = new(StringComparer.OrdinalIgnoreCase);
HashSet<string> duplicateKeys = new(StringComparer.OrdinalIgnoreCase);
foreach (string key in translations[locale].Keys.ToArray())
{
if (!keys.Add(key))
{
duplicateKeys.Add(key);
translations[locale].Remove(key);
}
}
if (duplicateKeys.Any())
errors.Add($"{locale}.json has duplicate translation keys: [{string.Join(", ", duplicateKeys)}]. Keys are case-insensitive.");
}
return translations;
}
/// <summary>Get a file lookup for the given directory.</summary>
/// <param name="rootDirectory">The root path to scan.</param>
private IFileLookup GetFileLookup(string rootDirectory)
{
return this.Settings.UseCaseInsensitivePaths
? CaseInsensitiveFileLookup.GetCachedFor(rootDirectory)
: MinimalFileLookup.GetCachedFor(rootDirectory);
}
/// <summary>Get the map display device which applies SMAPI features like tile rotation to loaded maps.</summary>
/// <remarks>This is separate to let mods like PyTK wrap it with their own functionality.</remarks>
private IDisplayDevice GetMapDisplayDevice()
{
return new SDisplayDevice(Game1.content, Game1.game1.GraphicsDevice);
}
/// <summary>Get the absolute path to the next available log file.</summary>
private string GetLogPath()
{
// default path
{
FileInfo defaultFile = new(Path.Combine(Constants.LogDir, $"{Constants.LogFilename}.{Constants.LogExtension}"));
if (!defaultFile.Exists)
return defaultFile.FullName;
}
// get first disambiguated path
for (int i = 2; i < int.MaxValue; i++)
{
FileInfo file = new(Path.Combine(Constants.LogDir, $"{Constants.LogFilename}.player-{i}.{Constants.LogExtension}"));
if (!file.Exists)
return file.FullName;
}
// should never happen
throw new InvalidOperationException("Could not find an available log path.");
}
/// <summary>Delete normal (non-crash) log files created by SMAPI.</summary>
private void PurgeNormalLogs()
{
DirectoryInfo logsDir = new(Constants.LogDir);
if (!logsDir.Exists)
return;
foreach (FileInfo logFile in logsDir.EnumerateFiles())
{
// skip non-SMAPI file
if (!logFile.Name.StartsWith(Constants.LogNamePrefix, StringComparison.OrdinalIgnoreCase))
continue;
// skip crash log
if (logFile.FullName == Constants.FatalCrashLog)
continue;
// delete file
try
{
FileUtilities.ForceDelete(logFile);
}
catch (IOException)
{
// ignore file if it's in use
}
}
}
/// <summary>Immediately exit the game without saving. This should only be invoked when an irrecoverable fatal error happens that risks save corruption or game-breaking bugs.</summary>
/// <param name="message">The fatal log message.</param>
private void ExitGameImmediately(string message)
{
this.Monitor.LogFatal(message);
this.LogManager.WriteCrashLog();
this.IsExiting = true;
this.Game.Exit();
}
/// <summary>Get the screen ID that should be logged to distinguish between players in split-screen mode, if any.</summary>
private int? GetScreenIdForLog()
{
if (Context.ScreenId != 0 || (Context.IsWorldReady && Context.IsSplitScreen))
return Context.ScreenId;
return null;
}
/*********
** Private types
*********/
/// <summary>A queued console command to run during the update loop.</summary>
/// <param name="Command">The command which can handle the input.</param>
/// <param name="Name">The parsed command name.</param>
/// <param name="Args">The parsed command arguments.</param>
private readonly record struct QueuedCommand(Command Command, string Name, string[] Args);
}
}
|