From 06c7e4e2b92849858002835ed41c7e9cce60fde4 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Tue, 29 Dec 2020 23:58:54 -0500 Subject: show details in TRACE logs when a mod is blocked by compatibility list --- src/SMAPI/Framework/ModLoading/ModResolver.cs | 36 +++++++++++++++++++++++++-- src/SMAPI/Framework/SCore.cs | 2 +- 2 files changed, 35 insertions(+), 3 deletions(-) (limited to 'src/SMAPI/Framework') diff --git a/src/SMAPI/Framework/ModLoading/ModResolver.cs b/src/SMAPI/Framework/ModLoading/ModResolver.cs index 08df7b76..af7d90f6 100644 --- a/src/SMAPI/Framework/ModLoading/ModResolver.cs +++ b/src/SMAPI/Framework/ModLoading/ModResolver.cs @@ -72,7 +72,7 @@ namespace StardewModdingAPI.Framework.ModLoading switch (mod.DataRecord?.Status) { case ModStatus.Obsolete: - mod.SetStatus(ModMetadataStatus.Failed, ModFailReason.Obsolete, $"it's obsolete: {mod.DataRecord.StatusReasonPhrase}"); + mod.SetStatus(ModMetadataStatus.Failed, ModFailReason.Obsolete, $"it's obsolete: {mod.DataRecord.StatusReasonPhrase}", this.GetTechnicalReasonForStatusOverride(mod)); continue; case ModStatus.AssumeBroken: @@ -102,7 +102,7 @@ namespace StardewModdingAPI.Framework.ModLoading error += $"version newer than {mod.DataRecord.StatusUpperVersion}"; error += " at " + string.Join(" or ", updateUrls); - mod.SetStatus(ModMetadataStatus.Failed, ModFailReason.Incompatible, error); + mod.SetStatus(ModMetadataStatus.Failed, ModFailReason.Incompatible, error, this.GetTechnicalReasonForStatusOverride(mod)); } continue; } @@ -409,6 +409,38 @@ namespace StardewModdingAPI.Framework.ModLoading yield return new ModDependency(manifest.ContentPackFor.UniqueID, manifest.ContentPackFor.MinimumVersion, FindMod(manifest.ContentPackFor.UniqueID), isRequired: true); } + /// Get a technical message indicating why a mod's compatibility status was overridden, if applicable. + /// The mod metadata. + private string GetTechnicalReasonForStatusOverride(IModMetadata mod) + { + // get compatibility list record + var data = mod.DataRecord; + if (data == null) + return null; + + // get status label + string statusLabel = data.Status switch + { + ModStatus.AssumeBroken => "'assume broken'", + ModStatus.AssumeCompatible => "'assume compatible'", + ModStatus.Obsolete => "obsolete", + _ => data.Status.ToString() + }; + + // get reason + string[] reasons = new[] { mod.DataRecord.StatusReasonPhrase, mod.DataRecord.StatusReasonDetails } + .Where(p => !string.IsNullOrWhiteSpace(p)) + .ToArray(); + + // build message + return + $"marked {statusLabel} in SMAPI's internal compatibility list for " + + (mod.DataRecord.StatusUpperVersion != null ? $"versions up to {mod.DataRecord.StatusUpperVersion}" : "all versions") + + ": " + + (reasons.Any() ? string.Join(": ", reasons) : "no reason given") + + "."; + } + /********* ** Private models diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index e05213f0..27540442 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -1532,7 +1532,7 @@ namespace StardewModdingAPI.Framework // validate status if (mod.Status == ModMetadataStatus.Failed) { - this.Monitor.Log($" Failed: {mod.Error}"); + this.Monitor.Log($" Failed: {mod.ErrorDetails ?? mod.Error}"); failReason = mod.FailReason; errorReasonPhrase = mod.Error; return false; -- cgit From f95292953f95ec71071fce7a6438a5403dc85816 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 30 Dec 2020 19:38:48 -0500 Subject: fix repeated mods in 'skipped mods' section of console --- docs/release-notes.md | 1 + src/SMAPI/Framework/Logging/LogManager.cs | 18 ++++++++++++++---- 2 files changed, 15 insertions(+), 4 deletions(-) (limited to 'src/SMAPI/Framework') diff --git a/docs/release-notes.md b/docs/release-notes.md index c68b3d62..dbc8e905 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -10,6 +10,7 @@ ## Upcoming release * For players: * Updated compatibility list. + * Fixed 'skipped mods' section repeating mods in some cases. * For modders: * When a mod is blocked by SMAPI's internal compatibility list, the `TRACE` messages while loading it now indicates that and specifies the reason. diff --git a/src/SMAPI/Framework/Logging/LogManager.cs b/src/SMAPI/Framework/Logging/LogManager.cs index ee013a85..4a8019af 100644 --- a/src/SMAPI/Framework/Logging/LogManager.cs +++ b/src/SMAPI/Framework/Logging/LogManager.cs @@ -425,9 +425,11 @@ namespace StardewModdingAPI.Framework.Logging this.Monitor.Log($" ({mod.ErrorDetails})"); } - // find skipped dependencies - IModMetadata[] skippedDependencies; + // group mods + List skippedDependencies = new List(); + List otherSkippedMods = new List(); { + // track broken dependencies HashSet skippedDependencyIds = new HashSet(StringComparer.OrdinalIgnoreCase); HashSet skippedModIds = new HashSet(from mod in skippedMods where mod.HasID() select mod.Manifest.UniqueID, StringComparer.OrdinalIgnoreCase); foreach (IModMetadata mod in skippedMods) @@ -435,7 +437,15 @@ namespace StardewModdingAPI.Framework.Logging foreach (string requiredId in skippedModIds.Intersect(mod.GetRequiredModIds())) skippedDependencyIds.Add(requiredId); } - skippedDependencies = skippedMods.Where(p => p.HasID() && skippedDependencyIds.Contains(p.Manifest.UniqueID)).ToArray(); + + // collect mod groups + foreach (IModMetadata mod in skippedMods) + { + if (mod.HasID() && skippedDependencyIds.Contains(mod.Manifest.UniqueID)) + skippedDependencies.Add(mod); + else + otherSkippedMods.Add(mod); + } } // log skipped mods @@ -451,7 +461,7 @@ namespace StardewModdingAPI.Framework.Logging this.Monitor.Newline(); } - foreach (IModMetadata mod in skippedMods.OrderBy(p => p.DisplayName)) + foreach (IModMetadata mod in otherSkippedMods.OrderBy(p => p.DisplayName)) LogSkippedMod(mod); this.Monitor.Newline(); } -- cgit From 0fdb09f5f9ef463dbf867c3a46ce680706305f0e Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Fri, 1 Jan 2021 11:51:57 -0500 Subject: fix network messages not using same JSON serializer settings (#745) --- docs/release-notes.md | 1 + src/SMAPI.Toolkit/Serialization/JsonHelper.cs | 6 ++++++ src/SMAPI/Events/ModMessageReceivedEventArgs.cs | 10 ++++++++-- src/SMAPI/Framework/SCore.cs | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) (limited to 'src/SMAPI/Framework') diff --git a/docs/release-notes.md b/docs/release-notes.md index dbc8e905..dcd638a3 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -14,6 +14,7 @@ * For modders: * When a mod is blocked by SMAPI's internal compatibility list, the `TRACE` messages while loading it now indicates that and specifies the reason. + * Message data from the `ModMessageReceived` event now uses the same serializer settings as the rest of SMAPI. This mainly adds support for sending crossplatform `Color`, `Point`, `Vector2`, `Rectangle`, and `SemanticVersion` fields through network messages. ## 3.8.1 Released 26 December 2020 for Stardew Valley 1.5.1 or later. diff --git a/src/SMAPI.Toolkit/Serialization/JsonHelper.cs b/src/SMAPI.Toolkit/Serialization/JsonHelper.cs index 031afbb0..00db9903 100644 --- a/src/SMAPI.Toolkit/Serialization/JsonHelper.cs +++ b/src/SMAPI.Toolkit/Serialization/JsonHelper.cs @@ -132,5 +132,11 @@ namespace StardewModdingAPI.Toolkit.Serialization { return JsonConvert.SerializeObject(model, formatting, this.JsonSettings); } + + /// Get a low-level JSON serializer matching the . + public JsonSerializer GetSerializer() + { + return JsonSerializer.CreateDefault(this.JsonSettings); + } } } diff --git a/src/SMAPI/Events/ModMessageReceivedEventArgs.cs b/src/SMAPI/Events/ModMessageReceivedEventArgs.cs index d4370028..d75a7540 100644 --- a/src/SMAPI/Events/ModMessageReceivedEventArgs.cs +++ b/src/SMAPI/Events/ModMessageReceivedEventArgs.cs @@ -1,5 +1,6 @@ using System; using StardewModdingAPI.Framework.Networking; +using StardewModdingAPI.Toolkit.Serialization; namespace StardewModdingAPI.Events { @@ -12,6 +13,9 @@ namespace StardewModdingAPI.Events /// The underlying message model. private readonly ModMessageModel Message; + /// The JSON helper used to deserialize models. + private readonly JsonHelper JsonHelper; + /********* ** Accessors @@ -31,16 +35,18 @@ namespace StardewModdingAPI.Events *********/ /// Construct an instance. /// The received message. - internal ModMessageReceivedEventArgs(ModMessageModel message) + /// The JSON helper used to deserialize models. + internal ModMessageReceivedEventArgs(ModMessageModel message, JsonHelper jsonHelper) { this.Message = message; + this.JsonHelper = jsonHelper; } /// Read the message data into the given model type. /// The message model type. public TModel ReadAs() { - return this.Message.Data.ToObject(); + return this.Message.Data.ToObject(this.JsonHelper.GetSerializer()); } } } diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index 27540442..5dc33828 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -1128,7 +1128,7 @@ namespace StardewModdingAPI.Framework modIDs.Remove(message.FromModID); // don't send a broadcast back to the sender // raise events - this.EventManager.ModMessageReceived.Raise(new ModMessageReceivedEventArgs(message), mod => mod != null && modIDs.Contains(mod.Manifest.UniqueID)); + this.EventManager.ModMessageReceived.Raise(new ModMessageReceivedEventArgs(message, this.Toolkit.JsonHelper), mod => mod != null && modIDs.Contains(mod.Manifest.UniqueID)); } /// Constructor a content manager to read game content files. -- cgit From 251ee2121a870bd8210830a8bdb943f64c00e030 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 2 Jan 2021 12:33:19 -0500 Subject: fix players in split-screen mode sharing peer state (#747) --- docs/release-notes.md | 1 + src/SMAPI/Framework/SMultiplayer.cs | 15 +++++++++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) (limited to 'src/SMAPI/Framework') diff --git a/docs/release-notes.md b/docs/release-notes.md index dcd638a3..a12a5482 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -10,6 +10,7 @@ ## Upcoming release * For players: * Updated compatibility list. + * Fixed errors when multiple players join in split-screen mode. * Fixed 'skipped mods' section repeating mods in some cases. * For modders: diff --git a/src/SMAPI/Framework/SMultiplayer.cs b/src/SMAPI/Framework/SMultiplayer.cs index f3b5e9b9..2f89fce9 100644 --- a/src/SMAPI/Framework/SMultiplayer.cs +++ b/src/SMAPI/Framework/SMultiplayer.cs @@ -10,6 +10,7 @@ using StardewModdingAPI.Framework.Events; using StardewModdingAPI.Framework.Networking; using StardewModdingAPI.Framework.Reflection; using StardewModdingAPI.Toolkit.Serialization; +using StardewModdingAPI.Utilities; using StardewValley; using StardewValley.Network; using StardewValley.SDKs; @@ -54,15 +55,25 @@ namespace StardewModdingAPI.Framework /// Whether to log network traffic. private readonly bool LogNetworkTraffic; + /// The backing field for . + private readonly PerScreen> PeersImpl = new(() => new Dictionary()); + + /// The backing field for . + private readonly PerScreen HostPeerImpl = new(); + /********* ** Accessors *********/ /// The metadata for each connected peer. - public IDictionary Peers { get; } = new Dictionary(); + public IDictionary Peers => this.PeersImpl.Value; /// The metadata for the host player, if the current player is a farmhand. - public MultiplayerPeer HostPeer; + public MultiplayerPeer HostPeer + { + get => this.HostPeerImpl.Value; + private set => this.HostPeerImpl.Value = value; + } /********* -- cgit From 456480ef918fc4d864b425fb7a8779618a91475a Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 2 Jan 2021 15:02:58 -0500 Subject: fix cursor position incorrectly handling UI mode (#741) --- docs/release-notes.md | 1 + src/SMAPI/Framework/CursorPosition.cs | 21 +++++++++++++++++++-- src/SMAPI/Framework/Input/SInputState.cs | 18 ++++++++---------- src/SMAPI/ICursorPosition.cs | 18 ++++++++++++++++-- 4 files changed, 44 insertions(+), 14 deletions(-) (limited to 'src/SMAPI/Framework') diff --git a/docs/release-notes.md b/docs/release-notes.md index a12a5482..c4aa413e 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -16,6 +16,7 @@ * For modders: * When a mod is blocked by SMAPI's internal compatibility list, the `TRACE` messages while loading it now indicates that and specifies the reason. * Message data from the `ModMessageReceived` event now uses the same serializer settings as the rest of SMAPI. This mainly adds support for sending crossplatform `Color`, `Point`, `Vector2`, `Rectangle`, and `SemanticVersion` fields through network messages. + * Fixed how the input API handles UI scaling. This mainly affects `ICursorPosition` values returned by the API; see [the wiki docs](https://stardewvalleywiki.com/Modding:Modder_Guide/APIs/Input#ICursorPosition) for how to account for UI scaling. ## 3.8.1 Released 26 December 2020 for Stardew Valley 1.5.1 or later. diff --git a/src/SMAPI/Framework/CursorPosition.cs b/src/SMAPI/Framework/CursorPosition.cs index 80d89994..107481e7 100644 --- a/src/SMAPI/Framework/CursorPosition.cs +++ b/src/SMAPI/Framework/CursorPosition.cs @@ -1,4 +1,5 @@ using Microsoft.Xna.Framework; +using StardewValley; namespace StardewModdingAPI.Framework { @@ -25,8 +26,8 @@ namespace StardewModdingAPI.Framework ** Public methods *********/ /// Construct an instance. - /// The pixel position relative to the top-left corner of the in-game map, adjusted for pixel zoom. - /// The pixel position relative to the top-left corner of the visible screen, adjusted for pixel zoom. + /// The pixel position relative to the top-left corner of the in-game map, adjusted for zoom but not UI scaling. + /// The pixel position relative to the top-left corner of the visible screen, adjusted for zoom but not UI scaling. /// The tile position relative to the top-left corner of the map. /// The tile position that the game considers under the cursor for purposes of clicking actions. public CursorPosition(Vector2 absolutePixels, Vector2 screenPixels, Vector2 tile, Vector2 grabTile) @@ -42,5 +43,21 @@ namespace StardewModdingAPI.Framework { return other != null && this.AbsolutePixels == other.AbsolutePixels; } + + /// + public Vector2 GetScaledAbsolutePixels() + { + return Game1.uiMode + ? Utility.ModifyCoordinatesForUIScale(this.AbsolutePixels) + : this.AbsolutePixels; + } + + /// + public Vector2 GetScaledScreenPixels() + { + return Game1.uiMode + ? Utility.ModifyCoordinatesForUIScale(this.ScreenPixels) + : this.ScreenPixels; + } } } diff --git a/src/SMAPI/Framework/Input/SInputState.cs b/src/SMAPI/Framework/Input/SInputState.cs index 23670202..a8d1f371 100644 --- a/src/SMAPI/Framework/Input/SInputState.cs +++ b/src/SMAPI/Framework/Input/SInputState.cs @@ -63,18 +63,16 @@ namespace StardewModdingAPI.Framework.Input base.Update(); // update SMAPI extended data + // note: Stardew Valley is *not* in UI mode when this code runs try { - float scale = Game1.options.uiScale; + float zoomMultiplier = (1f / Game1.options.zoomLevel); // get real values var controller = new GamePadStateBuilder(base.GetGamePadState()); var keyboard = new KeyboardStateBuilder(base.GetKeyboardState()); var mouse = new MouseStateBuilder(base.GetMouseState()); - Vector2 cursorAbsolutePos = new Vector2( - x: (mouse.X / scale) + Game1.uiViewport.X, - y: (mouse.Y / scale) + Game1.uiViewport.Y - ); + Vector2 cursorAbsolutePos = new Vector2((mouse.X * zoomMultiplier) + Game1.viewport.X, (mouse.Y * zoomMultiplier) + Game1.viewport.Y); Vector2? playerTilePos = Context.IsPlayerFree ? Game1.player.getTileLocation() : (Vector2?)null; HashSet reallyDown = new HashSet(this.GetPressedButtons(keyboard, mouse, controller)); @@ -109,7 +107,7 @@ namespace StardewModdingAPI.Framework.Input if (cursorAbsolutePos != this.CursorPositionImpl?.AbsolutePixels || playerTilePos != this.LastPlayerTile) { this.LastPlayerTile = playerTilePos; - this.CursorPositionImpl = this.GetCursorPosition(this.MouseState, cursorAbsolutePos, scale); + this.CursorPositionImpl = this.GetCursorPosition(this.MouseState, cursorAbsolutePos, zoomMultiplier); } } catch (InvalidOperationException) @@ -202,11 +200,11 @@ namespace StardewModdingAPI.Framework.Input /// Get the current cursor position. /// The current mouse state. /// The absolute pixel position relative to the map, adjusted for pixel zoom. - /// The UI scale applied to pixel coordinates. - private CursorPosition GetCursorPosition(MouseState mouseState, Vector2 absolutePixels, float scale) + /// The multiplier applied to pixel coordinates to adjust them for pixel zoom. + private CursorPosition GetCursorPosition(MouseState mouseState, Vector2 absolutePixels, float zoomMultiplier) { - Vector2 screenPixels = new Vector2(mouseState.X / scale, mouseState.Y / scale); - Vector2 tile = new Vector2((int)((Game1.uiViewport.X + screenPixels.X) / Game1.tileSize), (int)((Game1.uiViewport.Y + screenPixels.Y) / Game1.tileSize)); + Vector2 screenPixels = new Vector2(mouseState.X * zoomMultiplier, mouseState.Y * zoomMultiplier); + Vector2 tile = new Vector2((int)((Game1.viewport.X + screenPixels.X) / Game1.tileSize), (int)((Game1.viewport.Y + screenPixels.Y) / Game1.tileSize)); Vector2 grabTile = (Game1.mouseCursorTransparency > 0 && Utility.tileWithinRadiusOfPlayer((int)tile.X, (int)tile.Y, 1, Game1.player)) // derived from Game1.pressActionButton ? tile : Game1.player.GetGrabTile(); diff --git a/src/SMAPI/ICursorPosition.cs b/src/SMAPI/ICursorPosition.cs index 21c57db0..99c1b84d 100644 --- a/src/SMAPI/ICursorPosition.cs +++ b/src/SMAPI/ICursorPosition.cs @@ -1,15 +1,19 @@ using System; using Microsoft.Xna.Framework; +using StardewValley; namespace StardewModdingAPI { /// Represents a cursor position in the different coordinate systems. public interface ICursorPosition : IEquatable { - /// The pixel position relative to the top-left corner of the in-game map. + /********* + ** Accessors + *********/ + /// The pixel position relative to the top-left corner of the in-game map, adjusted for zoom but not UI scaling. See also . Vector2 AbsolutePixels { get; } - /// The pixel position relative to the top-left corner of the visible screen. + /// The pixel position relative to the top-left corner of the visible screen, adjusted for zoom but not UI scaling. See also . Vector2 ScreenPixels { get; } /// The tile position under the cursor relative to the top-left corner of the map. @@ -17,5 +21,15 @@ namespace StardewModdingAPI /// The tile position that the game considers under the cursor for purposes of clicking actions. This may be different than if that's too far from the player. Vector2 GrabTile { get; } + + + /********* + ** Public methods + *********/ + /// Get the , adjusted for UI scaling if needed. This is only different if is true. + Vector2 GetScaledAbsolutePixels(); + + /// Get the , adjusted for UI scaling if needed. This is only different if is true. + Vector2 GetScaledScreenPixels(); } } -- cgit From 68bcf28e6cd92dd843c2e461ccca74c0b432f1e6 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 2 Jan 2021 18:22:30 -0500 Subject: update error text linking to renamed wiki section --- docs/release-notes.md | 1 + src/SMAPI/Framework/Logging/LogManager.cs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) (limited to 'src/SMAPI/Framework') diff --git a/docs/release-notes.md b/docs/release-notes.md index ecad1635..9fbfcbb3 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -13,6 +13,7 @@ * On Linux, the SMAPI installer now auto-detects flatpak Steam paths. * Fixed errors when multiple players join in split-screen mode. * Fixed 'skipped mods' section repeating mods in some cases. + * Fixed out-of-date error text. * For modders: * When a mod is blocked by SMAPI's internal compatibility list, the `TRACE` messages while loading it now indicates that and specifies the reason. diff --git a/src/SMAPI/Framework/Logging/LogManager.cs b/src/SMAPI/Framework/Logging/LogManager.cs index 4a8019af..e504218b 100644 --- a/src/SMAPI/Framework/Logging/LogManager.cs +++ b/src/SMAPI/Framework/Logging/LogManager.cs @@ -46,7 +46,7 @@ namespace StardewModdingAPI.Framework.Logging search: new Regex(@"^System\.InvalidOperationException: Steamworks is not initialized\.[\s\S]+$", RegexOptions.Compiled | RegexOptions.CultureInvariant), replacement: #if SMAPI_FOR_WINDOWS - "Oops! Steam achievements won't work because Steam isn't loaded. You can launch the game through Steam to fix that (see 'Part 2: Configure Steam' in the install guide for more info: https://smapi.io/install).", + "Oops! Steam achievements won't work because Steam isn't loaded. See 'Launch SMAPI through Steam or GOG Galaxy' in the install guide for more info: https://smapi.io/install.", #else "Oops! Steam achievements won't work because Steam isn't loaded. You can launch the game through Steam to fix that.", #endif -- cgit From 397f338394c31e2a9bad2e90383f1ff621ae5d91 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 2 Jan 2021 22:24:45 -0500 Subject: detect and block map replacements that would crash the game due to tilesheet changes --- docs/release-notes.md | 2 + src/SMAPI/Framework/ContentCoordinator.cs | 23 ++++++ .../ContentManagers/GameContentManager.cs | 84 +++++++++++++++++++--- src/SMAPI/Framework/DeprecationManager.cs | 5 ++ 4 files changed, 106 insertions(+), 8 deletions(-) (limited to 'src/SMAPI/Framework') diff --git a/docs/release-notes.md b/docs/release-notes.md index 9fbfcbb3..e671f373 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -10,6 +10,7 @@ ## Upcoming release * For players: * Updated compatibility list. + * SMAPI now blocks farm map replacements that would crash the game in Stardew Valley 1.5. * On Linux, the SMAPI installer now auto-detects flatpak Steam paths. * Fixed errors when multiple players join in split-screen mode. * Fixed 'skipped mods' section repeating mods in some cases. @@ -18,6 +19,7 @@ * For modders: * When a mod is blocked by SMAPI's internal compatibility list, the `TRACE` messages while loading it now indicates that and specifies the reason. * Message data from the `ModMessageReceived` event now uses the same serializer settings as the rest of SMAPI. This mainly adds support for sending crossplatform `Color`, `Point`, `Vector2`, `Rectangle`, and `SemanticVersion` fields through network messages. + * Added warning when a map replacement changes the tilesheet order/IDs, which may cause crashes. * Fixed how the input API handles UI scaling. This mainly affects `ICursorPosition` values returned by the API; see [the wiki docs](https://stardewvalleywiki.com/Modding:Modder_Guide/APIs/Input#ICursorPosition) for how to account for UI scaling. ## 3.8.1 diff --git a/src/SMAPI/Framework/ContentCoordinator.cs b/src/SMAPI/Framework/ContentCoordinator.cs index f9027972..3d5bb29d 100644 --- a/src/SMAPI/Framework/ContentCoordinator.cs +++ b/src/SMAPI/Framework/ContentCoordinator.cs @@ -54,6 +54,9 @@ namespace StardewModdingAPI.Framework /// The game may adds content managers in asynchronous threads (e.g. when populating the load screen). private readonly ReaderWriterLockSlim ContentManagerLock = new ReaderWriterLockSlim(); + /// An unmodified content manager which doesn't intercept assets, used to compare asset data. + private readonly LocalizedContentManager VanillaContentManager; + /********* ** Accessors @@ -95,6 +98,7 @@ namespace StardewModdingAPI.Framework this.ContentManagers.Add( this.MainContentManager = new GameContentManager("Game1.content", serviceProvider, rootDirectory, currentCulture, this, monitor, reflection, this.OnDisposing, onLoadingFirstAsset) ); + this.VanillaContentManager = new LocalizedContentManager(serviceProvider, rootDirectory); this.CoreAssets = new CoreAssetPropagator(this.MainContentManager.AssertAndNormalizeAssetName, reflection); } @@ -150,6 +154,8 @@ namespace StardewModdingAPI.Framework { foreach (IContentManager contentManager in this.ContentManagers) contentManager.OnLocaleChanged(); + + this.VanillaContentManager.Unload(); }); } @@ -287,6 +293,23 @@ namespace StardewModdingAPI.Framework }); } + /// Get a vanilla asset without interception. + /// The type of asset to load. + /// The asset path relative to the loader root directory, not including the .xnb extension. + public bool TryLoadVanillaAsset(string assetName, out T asset) + { + try + { + asset = this.VanillaContentManager.Load(assetName); + return true; + } + catch + { + asset = default; + return false; + } + } + /// Dispose held resources. public void Dispose() { diff --git a/src/SMAPI/Framework/ContentManagers/GameContentManager.cs b/src/SMAPI/Framework/ContentManagers/GameContentManager.cs index ad8f2ef1..424d6ff3 100644 --- a/src/SMAPI/Framework/ContentManagers/GameContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/GameContentManager.cs @@ -11,6 +11,7 @@ using StardewModdingAPI.Framework.Reflection; using StardewModdingAPI.Framework.Utilities; using StardewValley; using xTile; +using xTile.Tiles; namespace StardewModdingAPI.Framework.ContentManagers { @@ -308,15 +309,10 @@ namespace StardewModdingAPI.Framework.ContentManagers return null; } - // validate asset - if (data == null) - { - mod.LogAsMod($"Mod incorrectly set asset '{info.AssetName}' to a null value; ignoring override.", LogLevel.Error); - return null; - } - // return matched asset - return new AssetDataForObject(info, data, this.AssertAndNormalizeAssetName); + return this.TryValidateLoadedAsset(info, data, mod) + ? new AssetDataForObject(info, data, this.AssertAndNormalizeAssetName) + : null; } /// Apply any to a loaded asset. @@ -386,5 +382,77 @@ namespace StardewModdingAPI.Framework.ContentManagers // return result return asset; } + + /// Validate that an asset loaded by a mod is valid and won't cause issues. + /// The asset type. + /// The basic asset metadata. + /// The loaded asset data. + /// The mod which loaded the asset. + private bool TryValidateLoadedAsset(IAssetInfo info, T data, IModMetadata mod) + { + // can't load a null asset + if (data == null) + { + mod.LogAsMod($"SMAPI blocked asset replacement for '{info.AssetName}': mod incorrectly set asset to a null value.", LogLevel.Error); + return false; + } + + // when replacing a map, the vanilla tilesheets must have the same order and IDs + if (data is Map loadedMap && this.Coordinator.TryLoadVanillaAsset(info.AssetName, out Map vanillaMap)) + { + for (int i = 0; i < vanillaMap.TileSheets.Count; i++) + { + // check for match + TileSheet vanillaSheet = vanillaMap.TileSheets[i]; + bool found = this.TryFindTilesheet(loadedMap, vanillaSheet.Id, out int loadedIndex, out TileSheet loadedSheet); + if (found && loadedIndex == i) + continue; + + // handle mismatch + { + // only show warning if not farm map + // This is temporary: mods shouldn't do this for any vanilla map, but these are the ones we know will crash. Showing a warning for others instead gives modders time to update their mods, while still simplifying troubleshooting. + bool isFarmMap = info.AssetNameEquals("Maps/Farm") || info.AssetNameEquals("Maps/Farm_Combat") || info.AssetNameEquals("Maps/Farm_Fishing") || info.AssetNameEquals("Maps/Farm_Foraging") || info.AssetNameEquals("Maps/Farm_FourCorners") || info.AssetNameEquals("Maps/Farm_Island") || info.AssetNameEquals("Maps/Farm_Mining"); + + + string reason = found + ? $"mod reordered the original tilesheets, which {(isFarmMap ? "would cause a crash" : "often causes crashes")}.\n\nTechnical details for mod author:\nExpected order [{string.Join(", ", vanillaMap.TileSheets.Select(p => $"'{p.ImageSource}' (id: {p.Id})"))}], but found tilesheet '{vanillaSheet.Id}' at index {loadedIndex} instead of {i}. Make sure custom tilesheet IDs are prefixed with 'z_' to avoid reordering tilesheets." + : $"mod has no tilesheet with ID '{vanillaSheet.Id}'. Map replacements must keep the original tilesheets to avoid errors or crashes."; + + SCore.DeprecationManager.PlaceholderWarn("3.8.2", DeprecationLevel.PendingRemoval); + if (isFarmMap) + { + mod.LogAsMod($"SMAPI blocked asset replacement for '{info.AssetName}': {reason}", LogLevel.Error); + return false; + } + mod.LogAsMod($"SMAPI detected a potential issue with asset replacement for '{info.AssetName}' map: {reason}", LogLevel.Warn); + } + } + } + + return true; + } + + /// Find a map tilesheet by ID. + /// The map whose tilesheets to search. + /// The tilesheet ID to match. + /// The matched tilesheet index, if any. + /// The matched tilesheet, if any. + private bool TryFindTilesheet(Map map, string id, out int index, out TileSheet tilesheet) + { + for (int i = 0; i < map.TileSheets.Count; i++) + { + if (map.TileSheets[i].Id == id) + { + index = i; + tilesheet = map.TileSheets[i]; + return true; + } + } + + index = -1; + tilesheet = null; + return false; + } } } diff --git a/src/SMAPI/Framework/DeprecationManager.cs b/src/SMAPI/Framework/DeprecationManager.cs index c22b5718..fc1b434b 100644 --- a/src/SMAPI/Framework/DeprecationManager.cs +++ b/src/SMAPI/Framework/DeprecationManager.cs @@ -63,6 +63,11 @@ namespace StardewModdingAPI.Framework this.QueuedWarnings.Add(new DeprecationWarning(source, nounPhrase, version, severity, Environment.StackTrace)); } + /// A placeholder method used to track deprecated code for which a separate warning will be shown. + /// The SMAPI version which deprecated it. + /// How deprecated the code is. + public void PlaceholderWarn(string version, DeprecationLevel severity) { } + /// Print any queued messages. public void PrintQueued() { -- cgit