forked from Pathoschild/StardewMods
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModEntry.cs
More file actions
500 lines (438 loc) · 24.6 KB
/
ModEntry.cs
File metadata and controls
500 lines (438 loc) · 24.6 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
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using ContentPatcher.Framework;
using ContentPatcher.Framework.Commands;
using ContentPatcher.Framework.Conditions;
using ContentPatcher.Framework.ConfigModels;
using ContentPatcher.Framework.Migrations;
using ContentPatcher.Framework.Tokens;
using ContentPatcher.Framework.Tokens.ValueProviders;
using ContentPatcher.Framework.Validators;
using Pathoschild.Stardew.Common.Utilities;
using StardewModdingAPI;
using StardewModdingAPI.Enums;
using StardewModdingAPI.Events;
using StardewValley;
[assembly: InternalsVisibleTo("Pathoschild.Stardew.Tests.Mods")]
namespace ContentPatcher
{
/// <summary>The mod entry point.</summary>
internal class ModEntry : Mod
{
/*********
** Fields
*********/
/// <summary>The name of the file which contains patch metadata.</summary>
private readonly string PatchFileName = "content.json";
/// <summary>The name of the file which contains player settings.</summary>
private readonly string ConfigFileName = "config.json";
/// <summary>The recognized format versions and their migrations.</summary>
private readonly Func<ContentConfig, IMigration[]> GetFormatVersions = content => new IMigration[]
{
new Migration_1_0(),
new Migration_1_3(),
new Migration_1_4(),
new Migration_1_5(),
new Migration_1_6(),
new Migration_1_7(),
new Migration_1_8(),
new Migration_1_9(),
new Migration_1_10(),
new Migration_1_11(),
new Migration_1_13(),
new Migration_1_14(),
new Migration_1_15_Prevalidation(),
new Migration_1_15_Rewrites(content),
new Migration_1_16(),
new Migration_1_17(),
new Migration_1_18()
};
/// <summary>The special validation logic to apply to assets affected by patches.</summary>
private readonly Func<IAssetValidator[]> AssetValidators = () => new IAssetValidator[]
{
new StardewValley_1_3_36_Validator()
};
/// <summary>Manages the available contextual tokens.</summary>
private TokenManager TokenManager;
/// <summary>Manages loaded patches.</summary>
private PatchManager PatchManager;
/// <summary>Handles loading and unloading patches.</summary>
private PatchLoader PatchLoader;
/// <summary>Handles the 'patch' console command.</summary>
private CommandHandler CommandHandler;
/// <summary>The mod configuration.</summary>
private ModConfig Config;
/// <summary>The configured key bindings.</summary>
private ModConfigKeys Keys;
/// <summary>The debug overlay (if enabled).</summary>
private DebugOverlay DebugOverlay;
/// <summary>The mod tokens queued for addition. This is null after the first update tick, when new tokens can no longer be added.</summary>
private List<ModProvidedToken> QueuedModTokens = new List<ModProvidedToken>();
/// <summary>Whether the next tick is the first one.</summary>
private bool IsFirstTick = true;
/// <summary>The loaded content packs.</summary>
private readonly IList<RawContentPack> RawContentPacks = new List<RawContentPack>();
/*********
** Public methods
*********/
/// <summary>The mod entry point, called after the mod is first loaded.</summary>
/// <param name="helper">Provides simplified APIs for writing mods.</param>
public override void Entry(IModHelper helper)
{
this.Config = helper.ReadConfig<ModConfig>();
this.Keys = this.Config.Controls.ParseControls(helper.Input, this.Monitor);
helper.Events.GameLoop.UpdateTicked += this.OnUpdateTicked;
LocalizedContentManager.OnLanguageChange += this.OnLocaleChanged;
}
/// <summary>Get an API that other mods can access. This is always called after <see cref="Entry"/>.</summary>
public override object GetApi()
{
return new ContentPatcherAPI(this.ModManifest.UniqueID, this.Monitor, this.Helper.Reflection, this.AddModToken);
}
/*********
** Private methods
*********/
/****
** Event handlers
****/
/// <summary>The method invoked when the player presses a button.</summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event data.</param>
private void OnButtonPressed(object sender, ButtonPressedEventArgs e)
{
if (this.Config.EnableDebugFeatures)
{
// toggle overlay
if (this.Keys.ToggleDebug.JustPressedUnique())
{
if (this.DebugOverlay == null)
this.DebugOverlay = new DebugOverlay(this.Helper.Events, this.Helper.Input, this.Helper.Content, this.Helper.Reflection);
else
{
this.DebugOverlay.Dispose();
this.DebugOverlay = null;
}
return;
}
// cycle textures
if (this.DebugOverlay != null)
{
if (this.Keys.DebugPrevTexture.JustPressedUnique())
this.DebugOverlay.PrevTexture();
if (this.Keys.DebugNextTexture.JustPressedUnique())
this.DebugOverlay.NextTexture();
}
}
}
/// <summary>Raised when the low-level stage in the game's loading process has changed. This is an advanced event for mods which need to run code at specific points in the loading process. The available stages or when they happen might change without warning in future versions (e.g. due to changes in the game's load process), so mods using this event are more likely to break or have bugs.</summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event data.</param>
private void OnLoadStageChanged(object sender, LoadStageChangedEventArgs e)
{
switch (e.NewStage)
{
case LoadStage.CreatedBasicInfo:
case LoadStage.SaveLoadedBasicInfo:
case LoadStage.Loaded when Game1.dayOfMonth == 0: // handled by OnDayStarted if we're not creating a new save
this.Monitor.VerboseLog($"Updating context: load stage changed to {e.NewStage}.");
this.TokenManager.IsBasicInfoLoaded = true;
this.UpdateContext(ContextUpdateType.All);
break;
}
}
/// <summary>The method invoked when a new day starts.</summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event data.</param>
private void OnDayStarted(object sender, DayStartedEventArgs e)
{
this.Monitor.VerboseLog("Updating context: new day started.");
this.TokenManager.IsBasicInfoLoaded = true;
this.UpdateContext(ContextUpdateType.All);
}
/// <summary>The method invoked when the player warps.</summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event data.</param>
private void OnWarped(object sender, WarpedEventArgs e)
{
this.Monitor.VerboseLog("Updating context: player warped.");
this.UpdateContext(ContextUpdateType.OnLocationChange);
}
/// <summary>The method invoked when the player returns to the title screen.</summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event data.</param>
private void OnReturnedToTitle(object sender, ReturnedToTitleEventArgs e)
{
this.Monitor.VerboseLog("Updating context: returned to title.");
this.TokenManager.IsBasicInfoLoaded = false;
this.UpdateContext(ContextUpdateType.All);
}
/// <summary>Raised after the game performs its overall update tick (≈60 times per second).</summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event data.</param>
private void OnUpdateTicked(object sender, UpdateTickedEventArgs e)
{
// initialize after first tick so other mods can register their tokens in SMAPI's GameLoop.GameLaunched event
if (this.IsFirstTick)
{
this.IsFirstTick = false;
this.Initialize();
}
}
/// <summary>Raised after the game language is changed, and after SMAPI handles the change.</summary>
/// <param name="code">The new language code.</param>
private void OnLocaleChanged(LocalizedContentManager.LanguageCode code)
{
// update if locale changes after initialization
if (!this.IsFirstTick)
this.UpdateContext(ContextUpdateType.All);
}
/****
** Methods
****/
/// <summary>Initialize the mod and content packs.</summary>
private void Initialize()
{
var helper = this.Helper;
// fetch content packs
RawContentPack[] contentPacks = this.GetContentPacks().ToArray();
InvariantHashSet installedMods = new InvariantHashSet(
(contentPacks.Select(p => p.Manifest.UniqueID))
.Concat(helper.ModRegistry.GetAll().Select(p => p.Manifest.UniqueID))
.OrderByIgnoreCase(p => p)
);
// log custom tokens
{
var tokensByMod = (
from token in this.QueuedModTokens
orderby token.Name
group token by token.Mod into modGroup
select new { ModName = modGroup.Key.Name, ModPrefix = modGroup.First().NamePrefix, TokenNames = modGroup.Select(p => p.NameWithoutPrefix).ToArray() }
);
foreach (var group in tokensByMod)
this.Monitor.Log($"{group.ModName} added {(group.TokenNames.Length == 1 ? "a custom token" : $"{group.TokenNames.Length} custom tokens")} with prefix '{group.ModPrefix}': {string.Join(", ", group.TokenNames)}.");
}
// load content packs and context
this.TokenManager = new TokenManager(helper.Content, installedMods, this.QueuedModTokens, this.Helper.Reflection);
this.PatchManager = new PatchManager(this.Monitor, this.TokenManager, this.AssetValidators());
this.PatchLoader = new PatchLoader(this.PatchManager, this.TokenManager, this.Monitor, this.Helper.Reflection, installedMods, this.Helper.Content.NormalizeAssetName);
this.UpdateContext(ContextUpdateType.All); // set initial context before loading any custom mod tokens
// load context
this.LoadContentPacks(contentPacks, installedMods);
this.UpdateContext(ContextUpdateType.All); // set initial context once patches + dynamic tokens + custom tokens are loaded
// register patcher
helper.Content.AssetLoaders.Add(this.PatchManager);
helper.Content.AssetEditors.Add(this.PatchManager);
// set up events
if (this.Config.EnableDebugFeatures)
helper.Events.Input.ButtonPressed += this.OnButtonPressed;
helper.Events.GameLoop.ReturnedToTitle += this.OnReturnedToTitle;
helper.Events.GameLoop.DayStarted += this.OnDayStarted;
helper.Events.Player.Warped += this.OnWarped;
helper.Events.Specialized.LoadStageChanged += this.OnLoadStageChanged;
// set up commands
this.CommandHandler = new CommandHandler(this.TokenManager, this.PatchManager, this.PatchLoader, this.Monitor, this.RawContentPacks, modID => modID == null ? this.TokenManager : this.TokenManager.GetContextFor(modID), () => this.UpdateContext(ContextUpdateType.All));
helper.ConsoleCommands.Add(this.CommandHandler.CommandName, $"Starts a Content Patcher command. Type '{this.CommandHandler.CommandName} help' for details.", (name, args) => this.CommandHandler.Handle(args));
// can no longer queue tokens
this.QueuedModTokens = null;
}
/// <summary>Add a mod-provided token.</summary>
/// <param name="token">The token to add.</param>
private void AddModToken(ModProvidedToken token)
{
if (!this.IsFirstTick)
{
this.Monitor.Log($"Rejected token added by {token.Mod.Name} because tokens can't be added after SMAPI's {nameof(this.Helper.Events.GameLoop)}.{nameof(this.Helper.Events.GameLoop.GameLaunched)} event.", LogLevel.Error);
return;
}
this.QueuedModTokens.Add(token);
}
/// <summary>Update the current context.</summary>
/// <param name="updateType">The context update type.</param>
private void UpdateContext(ContextUpdateType updateType)
{
this.TokenManager.UpdateContext(out InvariantHashSet changedGlobalTokens);
this.PatchManager.UpdateContext(this.Helper.Content, changedGlobalTokens, updateType);
}
/// <summary>Load the registered content packs.</summary>
/// <returns>Returns the loaded content pack IDs.</returns>
[SuppressMessage("ReSharper", "AccessToModifiedClosure", Justification = "The value is used immediately, so this isn't an issue.")]
private IEnumerable<RawContentPack> GetContentPacks()
{
this.Monitor.VerboseLog("Preloading content packs...");
foreach (IContentPack contentPack in this.Helper.ContentPacks.GetOwned())
{
RawContentPack rawContentPack;
try
{
// validate content.json has required fields
ContentConfig content = contentPack.ReadJsonFile<ContentConfig>(this.PatchFileName);
if (content == null)
{
this.Monitor.Log($"Ignored content pack '{contentPack.Manifest.Name}' because it has no {this.PatchFileName} file.", LogLevel.Error);
continue;
}
if (content.Format == null || content.Changes == null)
{
this.Monitor.Log($"Ignored content pack '{contentPack.Manifest.Name}' because it doesn't specify the required {nameof(ContentConfig.Format)} or {nameof(ContentConfig.Changes)} fields.", LogLevel.Error);
continue;
}
// apply migrations
IMigration migrator = new AggregateMigration(content.Format, this.GetFormatVersions(content));
if (!migrator.TryMigrate(content, out string error))
{
this.Monitor.Log($"Loading content pack '{contentPack.Manifest.Name}' failed: {error}.", LogLevel.Error);
continue;
}
// init
rawContentPack = new RawContentPack(contentPack, content, migrator);
}
catch (Exception ex)
{
this.Monitor.Log($"Error preloading content pack '{contentPack.Manifest.Name}'. Technical details:\n{ex}", LogLevel.Error);
continue;
}
yield return rawContentPack;
}
}
/// <summary>Load the patches from all registered content packs.</summary>
/// <param name="contentPacks">The content packs to load.</param>
/// <param name="installedMods">The mod IDs which are currently installed.</param>
/// <returns>Returns the loaded content pack IDs.</returns>
[SuppressMessage("ReSharper", "AccessToModifiedClosure", Justification = "The value is used immediately, so this isn't an issue.")]
private void LoadContentPacks(IEnumerable<RawContentPack> contentPacks, InvariantHashSet installedMods)
{
// load content packs
ConfigFileHandler configFileHandler = new ConfigFileHandler(this.ConfigFileName, this.ParseCommaDelimitedField, (pack, label, reason) => this.Monitor.Log($"Ignored {pack.Manifest.Name} > {label}: {reason}", LogLevel.Warn));
foreach (RawContentPack current in contentPacks)
{
this.Monitor.VerboseLog($"Loading content pack '{current.Manifest.Name}'...");
LogPathBuilder path = new LogPathBuilder(current.Manifest.Name);
try
{
ContentConfig content = current.Content;
// load tokens
ModTokenContext modContext = this.TokenManager.TrackLocalTokens(current.ContentPack);
TokenParser tokenParser = new TokenParser(modContext, current.Manifest, current.Migrator, installedMods);
{
// load config.json
InvariantDictionary<ConfigField> config = configFileHandler.Read(current.ContentPack, content.ConfigSchema, current.Content.Format);
configFileHandler.Save(current.ContentPack, config, this.Helper);
if (config.Any())
this.Monitor.VerboseLog($" found config.json with {config.Count} fields...");
// load config tokens
foreach (KeyValuePair<string, ConfigField> pair in config)
this.AddConfigToken(pair.Key, pair.Value, modContext, current);
// register with Generic Mod Config Menu
if (config.Any())
{
GenericModConfigMenuIntegrationForContentPack configMenu = new GenericModConfigMenuIntegrationForContentPack(this.Helper.ModRegistry, this.Monitor, current.Manifest, this.ParseCommaDelimitedField, config, saveAndApply: () =>
{
configFileHandler.Save(current.ContentPack, config, this.Helper);
this.PatchLoader.UnloadPatchesLoadedBy(current, false);
this.PatchLoader.LoadPatches(current, current.Content.Changes, path, reindex: true, parentPatch: null);
});
configMenu.Register((name, field) => this.AddConfigToken(name, field, modContext, current));
}
// load dynamic tokens
IDictionary<string, int> dynamicTokenCountByName = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
foreach (DynamicTokenConfig entry in content.DynamicTokens ?? new DynamicTokenConfig[0])
{
void LogSkip(string reason) => this.Monitor.Log($"Ignored {current.Manifest.Name} > dynamic token '{entry.Name}': {reason}", LogLevel.Warn);
// get path
LogPathBuilder localPath = path.With(nameof(content.DynamicTokens));
{
if (!dynamicTokenCountByName.ContainsKey(entry.Name))
dynamicTokenCountByName[entry.Name] = -1;
int discriminator = ++dynamicTokenCountByName[entry.Name];
localPath = localPath.With($"{entry.Name} {discriminator}");
}
// validate token key
if (string.IsNullOrWhiteSpace(entry.Name))
{
LogSkip("the token name can't be empty.");
continue;
}
if (entry.Name.Contains(InternalConstants.PositionalInputArgSeparator))
{
LogSkip($"the token name can't have positional input arguments ({InternalConstants.PositionalInputArgSeparator} character).");
continue;
}
if (Enum.TryParse<ConditionType>(entry.Name, true, out _))
{
LogSkip("the token name is already used by a global token.");
continue;
}
if (config.ContainsKey(entry.Name))
{
LogSkip("the token name is already used by a config token.");
continue;
}
// parse conditions
IList<Condition> conditions;
InvariantHashSet immutableRequiredModIDs;
{
if (!this.PatchLoader.TryParseConditions(entry.When, tokenParser, localPath.With(nameof(entry.When)), out conditions, out immutableRequiredModIDs, out string conditionError))
{
this.Monitor.Log($"Ignored {current.Manifest.Name} > '{entry.Name}' token: its {nameof(DynamicTokenConfig.When)} field is invalid: {conditionError}.", LogLevel.Warn);
continue;
}
}
// parse values
IManagedTokenString values;
if (!string.IsNullOrWhiteSpace(entry.Value))
{
if (!tokenParser.TryParseString(entry.Value, immutableRequiredModIDs, localPath.With(nameof(entry.Value)), out string valueError, out values))
{
LogSkip($"the token value is invalid: {valueError}");
continue;
}
}
else
values = new LiteralString("", localPath.With(nameof(entry.Value)));
// add token
modContext.AddDynamicToken(entry.Name, values, conditions);
}
}
// load patches
this.PatchLoader.LoadPatches(current, content.Changes, path, reindex: false, parentPatch: null);
// add to content pack list
this.RawContentPacks.Add(current);
}
catch (Exception ex)
{
this.Monitor.Log($"Error loading content pack '{current.Manifest.Name}'. Technical details:\n{ex}", LogLevel.Error);
continue;
}
}
this.PatchManager.Reindex(patchListChanged: true);
}
/// <summary>Parse a comma-delimited set of case-insensitive condition values.</summary>
/// <param name="field">The field value to parse.</param>
private InvariantHashSet ParseCommaDelimitedField(string field)
{
if (string.IsNullOrWhiteSpace(field))
return new InvariantHashSet();
IEnumerable<string> values = (
from value in field.Split(',')
where !string.IsNullOrWhiteSpace(value)
select value.Trim()
);
return new InvariantHashSet(values);
}
/// <summary>Register a config token for a content pack.</summary>
/// <param name="name">The field name.</param>
/// <param name="field">The config field.</param>
/// <param name="modContext">The mod context to which to add the token.</param>
/// <param name="contentPack">The content pack for which to add the token.</param>
private void AddConfigToken(string name, ConfigField field, ModTokenContext modContext, RawContentPack contentPack)
{
modContext.RemoveLocalToken(name); // only needed when resetting a token for Generic Mod Config Menu, but has no effect otherwise
IValueProvider valueProvider = new ImmutableValueProvider(name, field.Value, allowedValues: field.AllowValues, canHaveMultipleValues: field.AllowMultiple);
IToken token = new Token(valueProvider, scope: contentPack.Manifest.UniqueID);
modContext.AddLocalToken(token);
}
}
}