From 48833b5c306dfc88669e4cf4fc77640c426c519b Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 3 Mar 2018 15:47:29 -0500 Subject: move technical compatibility details into TRACE log (#453) --- src/SMAPI/Program.cs | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) (limited to 'src/SMAPI/Program.cs') diff --git a/src/SMAPI/Program.cs b/src/SMAPI/Program.cs index 47db8e86..acab8c70 100644 --- a/src/SMAPI/Program.cs +++ b/src/SMAPI/Program.cs @@ -674,8 +674,8 @@ namespace StardewModdingAPI { this.Monitor.Log("Loading mods...", LogLevel.Trace); - IDictionary skippedMods = new Dictionary(); - void TrackSkip(IModMetadata mod, string reasonPhrase) => skippedMods[mod] = reasonPhrase; + IDictionary skippedMods = new Dictionary(); + void TrackSkip(IModMetadata mod, string userReasonPhrase, string devReasonPhrase = null) => skippedMods[mod] = new[] { userReasonPhrase, devReasonPhrase }; // load content packs foreach (IModMetadata metadata in mods.Where(p => p.IsContentPack)) @@ -746,17 +746,17 @@ namespace StardewModdingAPI } catch (IncompatibleInstructionException ex) { - TrackSkip(metadata, $"it's no longer compatible (detected {ex.NounPhrase}). Please check for a newer version of the mod."); + TrackSkip(metadata, "it's no longer compatible. Please check for a newer version of the mod."); continue; } catch (SAssemblyLoadFailedException ex) { - TrackSkip(metadata, $"its DLL '{manifest.EntryDll}' couldn't be loaded: {ex.Message}"); + TrackSkip(metadata, $"it DLL couldn't be loaded: {ex.Message}"); continue; } catch (Exception ex) { - TrackSkip(metadata, $"its DLL '{manifest.EntryDll}' couldn't be loaded:\n{ex.GetLogSummary()}"); + TrackSkip(metadata, "its DLL couldn't be loaded.", $"Error: {ex.GetLogSummary()}"); continue; } @@ -816,12 +816,11 @@ namespace StardewModdingAPI foreach (var pair in skippedMods.OrderBy(p => p.Key.DisplayName)) { IModMetadata mod = pair.Key; - string reason = pair.Value; + string[] reason = pair.Value; - if (mod.Manifest?.Version != null) - this.Monitor.Log($" {mod.DisplayName} {mod.Manifest.Version} because {reason}", LogLevel.Error); - else - this.Monitor.Log($" {mod.DisplayName} because {reason}", LogLevel.Error); + this.Monitor.Log($" {mod.DisplayName}{(mod.Manifest?.Version != null ? " " + mod.Manifest.Version.ToString() : "")} because {reason[0]}", LogLevel.Error); + if (reason[1] != null) + this.Monitor.Log($" {reason[1]}", LogLevel.Trace); } this.Monitor.Newline(); } -- cgit From 36a527956c5410fe5992bfc42fdc11adff9cd9db Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 3 Mar 2018 17:54:17 -0500 Subject: fix detected incompatibility errors not showing mod's update URL (#453) --- docs/release-notes.md | 3 +++ src/SMAPI/Program.cs | 10 ++++++---- 2 files changed, 9 insertions(+), 4 deletions(-) (limited to 'src/SMAPI/Program.cs') diff --git a/docs/release-notes.md b/docs/release-notes.md index 74db0256..190146fa 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -1,5 +1,8 @@ # Release notes ## 2.6 (upcoming) +* For players: + * Fixed some incompatible-mod errors not showing mod's update URL. + * For the [log parser][]: * Fixed mod list not including all mods if at least one has no author name. * Fixed some log entries being incorrectly filtered. diff --git a/src/SMAPI/Program.cs b/src/SMAPI/Program.cs index acab8c70..fec03d6f 100644 --- a/src/SMAPI/Program.cs +++ b/src/SMAPI/Program.cs @@ -388,7 +388,7 @@ namespace StardewModdingAPI mods = resolver.ProcessDependencies(mods, modDatabase).ToArray(); // load mods - this.LoadMods(mods, this.JsonHelper, this.ContentManager); + this.LoadMods(mods, this.JsonHelper, this.ContentManager, modDatabase); // check for updates this.CheckForUpdatesAsync(mods); @@ -670,7 +670,8 @@ namespace StardewModdingAPI /// The mods to load. /// The JSON helper with which to read mods' JSON files. /// The content manager to use for mod content. - private void LoadMods(IModMetadata[] mods, JsonHelper jsonHelper, SContentManager contentManager) + /// Handles access to SMAPI's internal mod metadata list. + private void LoadMods(IModMetadata[] mods, JsonHelper jsonHelper, SContentManager contentManager, ModDatabase modDatabase) { this.Monitor.Log("Loading mods...", LogLevel.Trace); @@ -744,9 +745,10 @@ namespace StardewModdingAPI { modAssembly = modAssemblyLoader.Load(metadata, assemblyPath, assumeCompatible: metadata.DataRecord?.Status == ModStatus.AssumeCompatible); } - catch (IncompatibleInstructionException ex) + catch (IncompatibleInstructionException) // details already in trace logs { - TrackSkip(metadata, "it's no longer compatible. Please check for a newer version of the mod."); + string url = modDatabase.GetModPageUrlFor(metadata.Manifest.UniqueID); + TrackSkip(metadata, $"it's no longer compatible. Please check for a newer version of the mod{(url != null ? $" at {url}" : "")}."); continue; } catch (SAssemblyLoadFailedException ex) -- cgit From a290a2fa5229a1105942300c5ccd471a34915758 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 3 Mar 2018 22:18:44 -0500 Subject: mark Stardew Valley 1.3 incompatible in SMAPI 2.5.x to reduce confusion when it's released (#453) --- docs/release-notes.md | 3 +++ src/SMAPI/Constants.cs | 2 +- src/SMAPI/Program.cs | 2 +- 3 files changed, 5 insertions(+), 2 deletions(-) (limited to 'src/SMAPI/Program.cs') diff --git a/docs/release-notes.md b/docs/release-notes.md index be6fdb27..d20584af 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -8,6 +8,9 @@ * Fixed mod list not including all mods if at least one has no author name. * Fixed some log entries being incorrectly filtered. +* For SMAPI developers: + * Internal changes to support the upcoming Stardew Valley 1.3 update. + ## 2.5.2 * For modders: * Fixed issue where replacing an asset through `asset.AsImage()` or `asset.AsDictionary()` didn't take effect. diff --git a/src/SMAPI/Constants.cs b/src/SMAPI/Constants.cs index fe9fdf9b..c5e378e2 100644 --- a/src/SMAPI/Constants.cs +++ b/src/SMAPI/Constants.cs @@ -43,7 +43,7 @@ namespace StardewModdingAPI public static ISemanticVersion MinimumGameVersion { get; } = new SemanticVersion("1.2.30"); /// The maximum supported version of Stardew Valley. - public static ISemanticVersion MaximumGameVersion { get; } = null; + public static ISemanticVersion MaximumGameVersion { get; } = new SemanticVersion("1.2.33"); /// The path to the game folder. public static string ExecutionPath { get; } = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); diff --git a/src/SMAPI/Program.cs b/src/SMAPI/Program.cs index fec03d6f..22bceafd 100644 --- a/src/SMAPI/Program.cs +++ b/src/SMAPI/Program.cs @@ -177,7 +177,7 @@ namespace StardewModdingAPI } if (Constants.MaximumGameVersion != null && Constants.GameVersion.IsNewerThan(Constants.MaximumGameVersion)) { - this.Monitor.Log($"Oops! You're running Stardew Valley {Constants.GameVersion}, but this version of SMAPI is only compatible up to Stardew Valley {Constants.MaximumGameVersion}. Please check for a newer version of SMAPI.", LogLevel.Error); + this.Monitor.Log($"Oops! You're running Stardew Valley {Constants.GameVersion}, but this version of SMAPI is only compatible up to Stardew Valley {Constants.MaximumGameVersion}. Please check for a newer version of SMAPI: https://smapi.io.", LogLevel.Error); this.PressAnyKeyToExit(); return; } -- cgit From 19570f43129dbd3dbfa77a9c62e135a72528a68e Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 4 Mar 2018 01:07:55 -0500 Subject: simplify and always include default update URL, shorten no-longer-compatible skip messages --- docs/release-notes.md | 1 + src/SMAPI.Web/Startup.cs | 3 +- src/SMAPI/Framework/ModLoading/ModResolver.cs | 5 +- src/SMAPI/Program.cs | 5 +- src/SMAPI/StardewModdingAPI.config.json | 201 +++++++++----------------- 5 files changed, 77 insertions(+), 138 deletions(-) (limited to 'src/SMAPI/Program.cs') diff --git a/docs/release-notes.md b/docs/release-notes.md index d20584af..fb056e79 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -2,6 +2,7 @@ ## 2.5.3 * For players: * Fixed some incompatible-mod errors not showing the mod URL. + * Simplified default mod update URL, which is now always included for incompatible mods. * Updated compatibility list. * For the [log parser][]: diff --git a/src/SMAPI.Web/Startup.cs b/src/SMAPI.Web/Startup.cs index bc3e9f7b..93135239 100644 --- a/src/SMAPI.Web/Startup.cs +++ b/src/SMAPI.Web/Startup.cs @@ -147,7 +147,8 @@ namespace StardewModdingAPI.Web )); // shortcut redirects - redirects.Add(new RedirectToUrlRule("^/docs$", "https://stardewvalleywiki.com/Modding:Index")); + redirects.Add(new RedirectToUrlRule(@"^/compat\.?$", "https://stardewvalleywiki.com/Modding:SMAPI_compatibility")); + redirects.Add(new RedirectToUrlRule(@"^/docs\.?$", "https://stardewvalleywiki.com/Modding:Index")); // redirect legacy canimod.com URLs var wikiRedirects = new Dictionary diff --git a/src/SMAPI/Framework/ModLoading/ModResolver.cs b/src/SMAPI/Framework/ModLoading/ModResolver.cs index ba6dab1a..f878a1b9 100644 --- a/src/SMAPI/Framework/ModLoading/ModResolver.cs +++ b/src/SMAPI/Framework/ModLoading/ModResolver.cs @@ -98,7 +98,7 @@ namespace StardewModdingAPI.Framework.ModLoading case ModStatus.AssumeBroken: { // get reason - string reasonPhrase = mod.DataRecord.StatusReasonPhrase ?? "it's no longer compatible"; + string reasonPhrase = mod.DataRecord.StatusReasonPhrase ?? "it's outdated"; // get update URLs List updateUrls = new List(); @@ -111,6 +111,9 @@ namespace StardewModdingAPI.Framework.ModLoading if (mod.DataRecord.AlternativeUrl != null) updateUrls.Add(mod.DataRecord.AlternativeUrl); + // default update URL + updateUrls.Add("https://smapi.io/compat"); + // build error string error = $"{reasonPhrase}. Please check for a "; if (mod.DataRecord.StatusUpperVersion == null || mod.Manifest.Version.Equals(mod.DataRecord.StatusUpperVersion)) diff --git a/src/SMAPI/Program.cs b/src/SMAPI/Program.cs index 22bceafd..979f6328 100644 --- a/src/SMAPI/Program.cs +++ b/src/SMAPI/Program.cs @@ -747,8 +747,9 @@ namespace StardewModdingAPI } catch (IncompatibleInstructionException) // details already in trace logs { - string url = modDatabase.GetModPageUrlFor(metadata.Manifest.UniqueID); - TrackSkip(metadata, $"it's no longer compatible. Please check for a newer version of the mod{(url != null ? $" at {url}" : "")}."); + string[] updateUrls = new[] { modDatabase.GetModPageUrlFor(metadata.Manifest.UniqueID), "https://smapi.io/compat" }.Where(p => p != null).ToArray(); + + TrackSkip(metadata, $"it's outdated. Please check for a new version at {string.Join(" or ", updateUrls)}."); continue; } catch (SAssemblyLoadFailedException ex) diff --git a/src/SMAPI/StardewModdingAPI.config.json b/src/SMAPI/StardewModdingAPI.config.json index 101b9dac..437feea5 100644 --- a/src/SMAPI/StardewModdingAPI.config.json +++ b/src/SMAPI/StardewModdingAPI.config.json @@ -97,15 +97,13 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "ID": "AccessChestAnywhere", "MapLocalVersions": { "1.1-1078": "1.1" }, "Default | UpdateKey": "Nexus:257", - "~1.1 | Status": "AssumeBroken", - "~1.1 | AlternativeUrl": "https://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.1 | Status": "AssumeBroken" }, "AdjustArtisanPrices": { "ID": "1e36d4ca-c7ef-4dfb-9927-d27a6c3c8bdc", "Default | UpdateKey": "Chucklefish:3532", - "~0.1 | Status": "AssumeBroken", - "~0.1 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~0.1 | Status": "AssumeBroken" }, "Adjust Monster": { @@ -127,8 +125,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "AgingMod": { "ID": "skn.AgingMod", "Default | UpdateKey": "Nexus:1129", - "~1.0 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.0 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "All Crops All Seasons": { @@ -173,8 +170,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "A Tapper's Dream": { "ID": "ddde5195-8f85-4061-90cc-0d4fd5459358", "Default | UpdateKey": "Nexus:260", - "~1.4 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.4 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.4 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Auto Animal Doors": { @@ -247,16 +243,14 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "ID": "Kithio:BetterShippingBox", "MapLocalVersions": { "1.0.1": "1.0.2" }, "Default | UpdateKey": "Chucklefish:4302", - "~1.0.2 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.0.2 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0.2 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Better Sprinklers": { "ID": "Speeder.BetterSprinklers", "FormerIDs": "SPDSprinklersMod", // changed in 2.3 "Default | UpdateKey": "Nexus:41", - "~2.3.1-pathoschild-update | Status": "AssumeBroken", // broke in SDV 1.2 - "~2.3.1-pathoschild-update | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~2.3.1-pathoschild-update | Status": "AssumeBroken" // broke in SDV 1.2 }, "Billboard Anywhere": { @@ -269,8 +263,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "ID": "KathrynHazuka.BirthdayMail", "FormerIDs": "005e02dc-d900-425c-9c68-1ff55c5a295d", // changed in 1.2.3-pathoschild-update "Default | UpdateKey": "Nexus:276", - "~1.2.2 | Status": "AssumeBroken", // broke in SDV 1.2 - "~1.2.2 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.2.2 | Status": "AssumeBroken" // broke in SDV 1.2 }, "Breed Like Rabbits": { @@ -331,8 +324,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "ID": "Speeder.ChestLabel", "FormerIDs": "SPDChestLabel", // changed in 1.5.1-pathoschild-update "Default | UpdateKey": "Nexus:242", - "~1.6 | Status": "AssumeBroken", // broke in SDV 1.1 - "~1.6 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.6 | Status": "AssumeBroken" // broke in SDV 1.1 }, "Chest Pooling": { @@ -352,8 +344,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Choose Baby Gender": { "FormerIDs": "{EntryDll: 'ChooseBabyGender.dll'}", "Default | UpdateKey": "Nexus:590", - "~1.0.2 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.0.2 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0.2 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "CJB Automation": { @@ -398,8 +389,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Cold Weather Haley": { "ID": "LordXamon.ColdWeatherHaleyPRO", "Default | UpdateKey": "Nexus:1169", - "~1.0 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.0 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Colored Chests": { @@ -411,8 +401,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Combat with Farm Implements": { "ID": "SPDFarmingImplementsInCombat", "Default | UpdateKey": "Nexus:313", - "~1.0 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.0 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Community Bundle Item Tooltip": { @@ -434,8 +423,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Configurable Shipping Dates": { "ID": "ConfigurableShippingDates", "Default | UpdateKey": "Nexus:675", - "~1.1.1 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.1.1 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.1.1 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Cooking Skill": { @@ -515,8 +503,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Customizable Traveling Cart Days": { "ID": "TravelingCartYyeahdude", "Default | UpdateKey": "Nexus:567", - "~1.0 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.0 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Custom Linens": { @@ -566,8 +553,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Dynamic Checklist": { "ID": "gunnargolf.DynamicChecklist", "Default | UpdateKey": "Nexus:1145", // added in 1.0.1-pathoschild-update - "~1.0 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.0 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Dynamic Horses": { @@ -580,8 +566,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "ID": "DynamicMachines", "MapLocalVersions": { "1.1": "1.1.1" }, "Default | UpdateKey": "Nexus:374", - "~1.1.1 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.1.1 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.1.1 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Dynamic NPC Sprites": { @@ -597,16 +582,14 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Empty Hands": { "ID": "QuicksilverFox.EmptyHands", "Default | UpdateKey": "Nexus:1176", // added in 1.0.1-pathoschild-update - "~1.0 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.0 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Enemy Health Bars": { "ID": "Speeder.HealthBars", "FormerIDs": "SPDHealthBar", // changed in 1.7.1-pathoschild-update "Default | UpdateKey": "Nexus:193", - "~1.7 | Status": "AssumeBroken", // broke in SDV 1.2 - "~1.7 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.7 | Status": "AssumeBroken" // broke in SDV 1.2 }, "Entoarox Framework": { @@ -636,15 +619,13 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "ID": "Crystalmir.ExtendedFridge", "FormerIDs": "Mystra007ExtendedFridge", // changed in 1.0.1 "Default | UpdateKey": "Nexus:485", - "~1.0 | Status": "AssumeBroken", // broke in SDV 1.2 - "~1.0 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0 | Status": "AssumeBroken" // broke in SDV 1.2 }, "Extended Greenhouse": { "ID": "ExtendedGreenhouse", "Default | UpdateKey": "Chucklefish:4303", - "~1.0.2 | Status": "AssumeBroken", // broke in SDV 1.2 - "~1.0.2 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0.2 | Status": "AssumeBroken" // broke in SDV 1.2 }, "Extended Minecart": { @@ -667,35 +648,30 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Farm Automation: Barn Door Automation": { "FormerIDs": "{EntryDll: 'FarmAutomation.BarnDoorAutomation.dll'}", - "~1.0 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.0 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Farm Automation: Item Collector": { "FormerIDs": "{EntryDll: 'FarmAutomation.ItemCollector.dll'}", - "~1.0 | Status": "AssumeBroken", // broke in SDV 1.2 - "~1.0 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0 | Status": "AssumeBroken" // broke in SDV 1.2 }, "Farm Automation Unofficial: Item Collector": { "ID": "Maddy99.FarmAutomation.ItemCollector", - "~0.5 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~0.5 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~0.5 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Farm Expansion": { "ID": "Advize.FarmExpansion", "FormerIDs": "3888bdfd-73f6-4776-8bb7-8ad45aea1915 | AdvizeFarmExpansionMod-2-0 | AdvizeFarmExpansionMod-2-0-5", // changed in 2.0, 2.0.5, and 3.0 "Default | UpdateKey": "Nexus:130", - "~2.0.5 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~2.0.5 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~2.0.5 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Farm Resource Generator": { "FormerIDs": "{EntryDll: 'FarmResourceGenerator.dll'}", "Default | UpdateKey": "Nexus:647", - "~1.0.4 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.0.4 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0.4 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Fast Animations": { @@ -718,8 +694,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "ID": "KathrynHazuka.FasterRun", "FormerIDs": "{EntryDll: 'FasterRun.dll'}", // changed in 1.1.1-pathoschild-update "Default | UpdateKey": "Nexus:733", // added in 1.1.1-pathoschild-update - "~1.1 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.1 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.1 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Fishing Adjust": { @@ -741,8 +716,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "FormerIDs": "{EntryDll: 'FlorenceMod.dll'}", "MapLocalVersions": { "1.0.1": "1.1" }, "Default | UpdateKey": "Nexus:591", - "~1.1 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.1 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.1 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Flower Color Picker": { @@ -753,8 +727,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Forage at the Farm": { "ID": "ForageAtTheFarm", "Default | UpdateKey": "Nexus:673", - "~1.5.1 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.5.1 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.5.1 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Furniture Anywhere": { @@ -812,8 +785,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Happy Animals": { "ID": "HappyAnimals", - "~1.0.3 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.0.3 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0.3 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Happy Birthday (Omegasis)": { @@ -841,8 +813,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Harvest With Scythe": { "ID": "965169fd-e1ed-47d0-9f12-b104535fb4bc", "Default | UpdateKey": "Nexus:236", - "~1.0.6 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.0.6 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0.6 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Horse Whistle (icepuente)": { @@ -858,8 +829,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Hunger for Food (Tigerle)": { "ID": "HungerForFoodByTigerle", "Default | UpdateKey": "Nexus:810", - "~0.1.2 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~0.1.2 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~0.1.2 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Hunger Mod (skn)": { @@ -882,8 +852,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Instant Geode": { "ID": "InstantGeode", - "~1.12 | Status": "AssumeBroken", // broke in SDV 1.2 - "~1.12 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.12 | Status": "AssumeBroken" // broke in SDV 1.2 }, "Instant Grow Trees": { @@ -895,8 +864,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Interaction Helper": { "ID": "HammurabiInteractionHelper", "Default | UpdateKey": "Chucklefish:4640", // added in 1.0.4-pathoschild-update - "~1.0.3 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.0.3 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0.3 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Item Auto Stacker": { @@ -926,8 +894,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "ID": "BALANCEMOD_AntiExhaustion", "MapLocalVersions": { "0.0": "1.1" }, "Default | UpdateKey": "Nexus:637", - "~1.1 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.1 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.1 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Level Extender": { @@ -1005,8 +972,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Message Box [API]? (ChatMod)": { "ID": "Kithio:ChatMod", "Default | UpdateKey": "Chucklefish:4296", - "~1.0 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.0 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Mining at the Farm": { @@ -1040,8 +1006,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "More Artifact Spots": { "ID": "451", "Default | UpdateKey": "Nexus:451", - "~1.0.1 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.0.1 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0.1 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "More Map Layers": { @@ -1070,8 +1035,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "ID": "FileLoading", "MapLocalVersions": { "1.1": "1.12" }, "Default | UpdateKey": "Nexus:1094", - "~1.12 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.12 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.12 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Museum Rearranger": { @@ -1089,8 +1053,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "New Machines": { "ID": "F70D4FAB-0AB2-4B78-9F1B-AF2CA2236A59", "Default | UpdateKey": "Chucklefish:3683", - "~4.2.1343 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~4.2.1343 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~4.2.1343 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Night Owl": { @@ -1131,8 +1094,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "No Soil Decay": { "ID": "289dee03-5f38-4d8e-8ffc-e440198e8610", "Default | UpdateKey": "Nexus:237", - "~0.5 | Status": "AssumeBroken", // broke in SDV 1.2 and uses Assembly.GetExecutingAssembly().Location - "~0.5 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~0.5 | Status": "AssumeBroken" // broke in SDV 1.2 and uses Assembly.GetExecutingAssembly().Location }, "No Soil Decay Redux": { @@ -1150,8 +1112,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "NPC Speak": { "FormerIDs": "{EntryDll: 'NpcEcho.dll'}", "Default | UpdateKey": "Nexus:694", - "~1.0 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.0 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Object Time Left": { @@ -1188,8 +1149,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "PelicanTTS": { "ID": "Platonymous.PelicanTTS", "Default | UpdateKey": "Nexus:1079", // added in 1.6.1 - "~1.6 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.6 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.6 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Persia the Mermaid - Standalone Custom NPC": { @@ -1205,8 +1165,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Persival's BundleMod": { "FormerIDs": "{EntryDll: 'BundleMod.dll'}", "Default | UpdateKey": "Nexus:438", - "~1.0 | Status": "AssumeBroken", // broke in SDV 1.1 - "~1.0 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0 | Status": "AssumeBroken" // broke in SDV 1.1 }, "Plant on Grass": { @@ -1240,8 +1199,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "ID": "Mucchan.PrairieKingMadeEasy", "FormerIDs": "{EntryDll: 'PrairieKingMadeEasy.dll'}", // changed in 1.0.1 "Default | UpdateKey": "Chucklefish:3594", - "~1.0 | Status": "AssumeBroken", // broke in SDV 1.2 - "~1.0 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0 | Status": "AssumeBroken" // broke in SDV 1.2 }, "Quest Delay": { @@ -1251,8 +1209,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Rain Randomizer": { "FormerIDs": "{EntryDll: 'RainRandomizer.dll'}", - "~1.0.3 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.0.3 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0.3 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Recatch Legendary Fish": { @@ -1274,16 +1231,14 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "RelationshipsEnhanced": { "ID": "relationshipsenhanced", "Default | UpdateKey": "Chucklefish:4435", - "~1.0 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.0 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Relationship Status": { "ID": "relationshipstatus", "MapRemoteVersions": { "1.0.5": "1.0.4" }, // not updated in manifest "Default | UpdateKey": "Nexus:751", - "~1.0.5 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.0.5 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0.5 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Rented Tools": { @@ -1312,8 +1267,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Reusable Wallpapers and Floors (Wallpaper Retain)": { "ID": "dae1b553-2e39-43e7-8400-c7c5c836134b", "Default | UpdateKey": "Nexus:356", - "~1.5 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.5 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.5 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Ring of Fire": { @@ -1395,16 +1349,14 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Shed Notifications (BuildingsNotifications)": { "ID": "TheCroak.BuildingsNotifications", "Default | UpdateKey": "Nexus:620", - "~0.4.1 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~0.4.1 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~0.4.1 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Shenandoah Project": { "ID": "Shenandoah Project", "MapRemoteVersions": { "1.1.1": "1.1" }, // not updated in manifest "Default | UpdateKey": "Nexus:756", - "~1.1.1 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.1.1 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.1.1 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Ship Anywhere": { @@ -1415,8 +1367,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Shipment Tracker": { "ID": "7e474181-e1a0-40f9-9c11-d08a3dcefaf3", "Default | UpdateKey": "Nexus:321", - "~1.1 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.1 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.1 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Shop Expander": { @@ -1430,8 +1381,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "ID": "Igorious.Showcase", "MapLocalVersions": { "0.9-500": "0.9" }, "Default | UpdateKey": "Chucklefish:4487", - "~0.9 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~0.9 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~0.9 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Shroom Spotter": { @@ -1461,8 +1411,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "ID": "6266959802", "MapLocalVersions": { "0.0": "1.4" }, "Default | UpdateKey": "Nexus:366", - "~1.2.2 | Status": "AssumeBroken", // broke in SMAPI 1.9 (has multiple Mod instances) - "~1.2.2 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.2.2 | Status": "AssumeBroken" // broke in SMAPI 1.9 (has multiple Mod instances) }, "Skill Prestige": { @@ -1506,14 +1455,12 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "ID": "Speeder.SlowerFenceDecay", "FormerIDs": "SPDSlowFenceDecay", // changed in 0.5.2-pathoschild-update "Default | UpdateKey": "Nexus:252", - "~0.5.1 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~0.5.1 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~0.5.1 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Smart Mod": { "ID": "KuroBear.SmartMod", - "~2.2 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~2.2 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~2.2 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Solar Eclipse Event": { @@ -1542,15 +1489,13 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Sprinkles": { "ID": "Platonymous.Sprinkles", "Default | UpdateKey": "Chucklefish:4592", - "~1.1.3 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.1.3 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.1.3 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Sprint and Dash": { "ID": "SPDSprintAndDash", "Default | UpdateKey": "Chucklefish:3531", - "~1.0 | Status": "AssumeBroken", // broke in SDV 1.2 - "~1.0 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0 | Status": "AssumeBroken" // broke in SDV 1.2 }, "Sprint and Dash Redux": { @@ -1563,8 +1508,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "ID": "a10d3097-b073-4185-98ba-76b586cba00c", "MapLocalVersions": { "1.0": "2.1" }, // not updated in manifest "Default | UpdateKey": "GitHub:oliverpl/SprintingMod", - "~2.1 | Status": "AssumeBroken", // broke in SDV 1.2 - "~2.1 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~2.1 | Status": "AssumeBroken" // broke in SDV 1.2 }, "StackSplitX": { @@ -1576,8 +1520,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "StaminaRegen": { "FormerIDs": "{EntryDll: 'StaminaRegen.dll'}", - "~1.0.3 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.0.3 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0.3 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Stardew Config Menu": { @@ -1599,8 +1542,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Stardew Notification": { "ID": "stardewnotification", "Default | UpdateKey": "GitHub:monopandora/StardewNotification", - "~1.7 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.7 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.7 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Stardew Symphony": { @@ -1625,8 +1567,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "StashItemsToChest": { "ID": "BlueMod_StashItemsToChest", "Default | UpdateKey": "GitHub:lambui/StardewValleyMod_StashItemsToChest", - "~1.0.1 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.0.1 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0.1 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Stephan's Lots of Crops": { @@ -1650,8 +1591,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Super Greenhouse Warp Modifier": { "ID": "SuperGreenhouse", "Default | UpdateKey": "Chucklefish:4334", - "~1.0 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.0 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Swim Almost Anywhere / Swim Suit": { @@ -1661,8 +1601,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Tainted Cellar": { "FormerIDs": "{EntryDll: 'TaintedCellar.dll'}", - "~1.0 | Status": "AssumeBroken", // broke in SDV 1.1 or 1.11 - "~1.0 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0 | Status": "AssumeBroken" // broke in SDV 1.1 or 1.11 }, "Tapper Ready": { @@ -1678,8 +1617,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Teleporter": { "ID": "Teleporter", "Default | UpdateKey": "Chucklefish:4374", - "~1.0.2 | Status": "AssumeBroken", // broke in SDV 1.2 - "~1.0.2 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0.2 | Status": "AssumeBroken" // broke in SDV 1.2 }, "The Long Night": { @@ -1738,8 +1676,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "ID": "Demiacle.UiModSuite", "MapLocalVersions": { "0.5": "1.0" }, // not updated in manifest "Default | UpdateKey": "Nexus:1023", - "~1.0 | Status": "AssumeBroken", // broke in SDV 1.2 - "~1.0 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0 | Status": "AssumeBroken" // broke in SDV 1.2 }, "Variable Grass": { @@ -1754,15 +1691,13 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "WakeUp": { "FormerIDs": "{EntryDll: 'WakeUp.dll'}", - "~1.0.2 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.0.2 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0.2 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "Wallpaper Fix": { "FormerIDs": "{EntryDll: 'WallpaperFix.dll'}", "Default | UpdateKey": "Chucklefish:4211", - "~1.1 | Status": "AssumeBroken", // broke in SMAPI 2.0 - "~1.1 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.1 | Status": "AssumeBroken" // broke in SMAPI 2.0 }, "WarpAnimals": { @@ -1772,8 +1707,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Weather Controller": { "FormerIDs": "{EntryDll: 'WeatherController.dll'}", - "~1.0.2 | Status": "AssumeBroken", // broke in SDV 1.2 - "~1.0.2 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0.2 | Status": "AssumeBroken" // broke in SDV 1.2 }, "What Farm Cave / WhatAMush": { @@ -1788,8 +1722,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Wonderful Farm Life": { "FormerIDs": "{EntryDll: 'WonderfulFarmLife.dll'}", - "~1.0 | Status": "AssumeBroken", // broke in SDV 1.1 or 1.11 - "~1.0 | AlternativeUrl": "http://stardewvalleywiki.com/Modding:SMAPI_2.0" + "~1.0 | Status": "AssumeBroken" // broke in SDV 1.1 or 1.11 }, "XmlSerializerRetool": { -- cgit From 99023f94871e1f9bad5ee5f5db0ff041a02e9ed5 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 4 Mar 2018 18:46:05 -0500 Subject: add support for mapping non-semantic remote mod versions --- docs/release-notes.md | 1 + src/SMAPI.Common/Models/ModSeachModel.cs | 7 ++++- src/SMAPI.Web/Controllers/ModsApiController.cs | 24 ++++++++++++----- src/SMAPI/Framework/ModData/ModDataRecord.cs | 11 +++++--- src/SMAPI/Framework/ModData/ParsedModDataRecord.cs | 2 +- src/SMAPI/Framework/WebApiClient.cs | 2 +- src/SMAPI/Program.cs | 31 +++++++++++----------- 7 files changed, 50 insertions(+), 28 deletions(-) (limited to 'src/SMAPI/Program.cs') diff --git a/docs/release-notes.md b/docs/release-notes.md index 93d07385..903eaf6f 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -6,6 +6,7 @@ * Fixed some incompatible-mod errors not showing the mod URL. * Fixed rare crash with a specific combination of `manifest.json` fields and internal SMAPI mod data. * Fixed update checks not working for Nexus Mods due to a change in their API. + * Fixed update checks failing for some older mods with non-standard versions. * For the [log parser][]: * Fixed mod list not including all mods if at least one has no author name. diff --git a/src/SMAPI.Common/Models/ModSeachModel.cs b/src/SMAPI.Common/Models/ModSeachModel.cs index 13b05d2d..3c33d0b6 100644 --- a/src/SMAPI.Common/Models/ModSeachModel.cs +++ b/src/SMAPI.Common/Models/ModSeachModel.cs @@ -12,6 +12,9 @@ namespace StardewModdingAPI.Common.Models /// The namespaced mod keys to search. public string[] ModKeys { get; set; } + /// Whether to allow non-semantic versions, instead of returning an error for those. + public bool AllowInvalidVersions { get; set; } + /********* ** Public methods @@ -24,9 +27,11 @@ namespace StardewModdingAPI.Common.Models /// Construct an instance. /// The namespaced mod keys to search. - public ModSearchModel(IEnumerable modKeys) + /// Whether to allow non-semantic versions, instead of returning an error for those. + public ModSearchModel(IEnumerable modKeys, bool allowInvalidVersions) { this.ModKeys = modKeys.ToArray(); + this.AllowInvalidVersions = allowInvalidVersions; } } } diff --git a/src/SMAPI.Web/Controllers/ModsApiController.cs b/src/SMAPI.Web/Controllers/ModsApiController.cs index dcb4ec52..abae7db7 100644 --- a/src/SMAPI.Web/Controllers/ModsApiController.cs +++ b/src/SMAPI.Web/Controllers/ModsApiController.cs @@ -64,14 +64,15 @@ namespace StardewModdingAPI.Web.Controllers /// Fetch version metadata for the given mods. /// The namespaced mod keys to search as a comma-delimited array. + /// Whether to allow non-semantic versions, instead of returning an error for those. [HttpGet] - public async Task> GetAsync(string modKeys) + public async Task> GetAsync(string modKeys, bool allowInvalidVersions = false) { string[] modKeysArray = modKeys?.Split(',').ToArray(); if (modKeysArray == null || !modKeysArray.Any()) return new Dictionary(); - return await this.PostAsync(new ModSearchModel(modKeysArray)); + return await this.PostAsync(new ModSearchModel(modKeysArray, allowInvalidVersions)); } /// Fetch version metadata for the given mods. @@ -79,7 +80,8 @@ namespace StardewModdingAPI.Web.Controllers [HttpPost] public async Task> PostAsync([FromBody] ModSearchModel search) { - // sort & filter keys + // parse model + bool allowInvalidVersions = search?.AllowInvalidVersions ?? false; string[] modKeys = (search?.ModKeys?.ToArray() ?? new string[0]) .Distinct(StringComparer.CurrentCultureIgnoreCase) .OrderBy(p => p, StringComparer.CurrentCultureIgnoreCase) @@ -106,12 +108,20 @@ namespace StardewModdingAPI.Web.Controllers // fetch mod info result[modKey] = await this.Cache.GetOrCreateAsync($"{repository.VendorKey}:{modID}".ToLower(), async entry => { - entry.AbsoluteExpiration = DateTimeOffset.UtcNow.AddMinutes(this.CacheMinutes); - + // fetch info ModInfoModel info = await repository.GetModInfoAsync(modID); - if (info.Error == null && (info.Version == null || !Regex.IsMatch(info.Version, this.VersionRegex, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase))) - info = new ModInfoModel(info.Name, info.Version, info.Url, info.Version == null ? "Mod has no version number." : $"Mod has invalid semantic version '{info.Version}'."); + // validate + if (info.Error == null) + { + if (info.Version == null) + info = new ModInfoModel(info.Name, info.Version, info.Url, "Mod has no version number."); + if (!allowInvalidVersions && !Regex.IsMatch(info.Version, this.VersionRegex, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase)) + info = new ModInfoModel(info.Name, info.Version, info.Url, $"Mod has invalid semantic version '{info.Version}'."); + } + + // cache & return + entry.AbsoluteExpiration = DateTimeOffset.UtcNow.AddMinutes(this.CacheMinutes); return info; }); } diff --git a/src/SMAPI/Framework/ModData/ModDataRecord.cs b/src/SMAPI/Framework/ModData/ModDataRecord.cs index 79a954f7..56275f53 100644 --- a/src/SMAPI/Framework/ModData/ModDataRecord.cs +++ b/src/SMAPI/Framework/ModData/ModDataRecord.cs @@ -106,10 +106,10 @@ namespace StardewModdingAPI.Framework.ModData /// Get a semantic local version for update checks. /// The remote version to normalise. - public string GetLocalVersionForUpdateChecks(string version) + public ISemanticVersion GetLocalVersionForUpdateChecks(ISemanticVersion version) { - return this.MapLocalVersions != null && this.MapLocalVersions.TryGetValue(version, out string newVersion) - ? newVersion + return this.MapLocalVersions != null && this.MapLocalVersions.TryGetValue(version.ToString(), out string newVersion) + ? new SemanticVersion(newVersion) : version; } @@ -117,6 +117,11 @@ namespace StardewModdingAPI.Framework.ModData /// The remote version to normalise. public string GetRemoteVersionForUpdateChecks(string version) { + // normalise version if possible + if (SemanticVersion.TryParse(version, out ISemanticVersion parsed)) + version = parsed.ToString(); + + // fetch remote version return this.MapRemoteVersions != null && this.MapRemoteVersions.TryGetValue(version, out string newVersion) ? newVersion : version; diff --git a/src/SMAPI/Framework/ModData/ParsedModDataRecord.cs b/src/SMAPI/Framework/ModData/ParsedModDataRecord.cs index 7f49790d..deb12bdc 100644 --- a/src/SMAPI/Framework/ModData/ParsedModDataRecord.cs +++ b/src/SMAPI/Framework/ModData/ParsedModDataRecord.cs @@ -33,7 +33,7 @@ namespace StardewModdingAPI.Framework.ModData *********/ /// Get a semantic local version for update checks. /// The remote version to normalise. - public string GetLocalVersionForUpdateChecks(string version) + public ISemanticVersion GetLocalVersionForUpdateChecks(ISemanticVersion version) { return this.DataRecord.GetLocalVersionForUpdateChecks(version); } diff --git a/src/SMAPI/Framework/WebApiClient.cs b/src/SMAPI/Framework/WebApiClient.cs index e78ac14b..7f0122cf 100644 --- a/src/SMAPI/Framework/WebApiClient.cs +++ b/src/SMAPI/Framework/WebApiClient.cs @@ -40,7 +40,7 @@ namespace StardewModdingAPI.Framework { return this.Post>( $"v{this.Version}/mods", - new ModSearchModel(modKeys) + new ModSearchModel(modKeys, allowInvalidVersions: true) ); } diff --git a/src/SMAPI/Program.cs b/src/SMAPI/Program.cs index 979f6328..1a1b9645 100644 --- a/src/SMAPI/Program.cs +++ b/src/SMAPI/Program.cs @@ -604,29 +604,30 @@ namespace StardewModdingAPI foreach (var result in results) { IModMetadata mod = result.Mod; - ModInfoModel info = result.Info; + ModInfoModel remoteInfo = result.Info; // handle error - if (info.Error != null) + if (remoteInfo.Error != null) { - this.Monitor.Log($" {mod.DisplayName} ({result.Key}): update error: {info.Error}", LogLevel.Trace); + this.Monitor.Log($" {mod.DisplayName} ({result.Key}): update error: {remoteInfo.Error}", LogLevel.Trace); continue; } - // track update - ISemanticVersion localVersion = mod.DataRecord != null - ? new SemanticVersion(mod.DataRecord.GetLocalVersionForUpdateChecks(mod.Manifest.Version.ToString())) - : mod.Manifest.Version; - ISemanticVersion latestVersion = new SemanticVersion(mod.DataRecord != null - ? mod.DataRecord.GetRemoteVersionForUpdateChecks(new SemanticVersion(info.Version).ToString()) - : info.Version - ); - bool isUpdate = latestVersion.IsNewerThan(localVersion); - this.VerboseLog($" {mod.DisplayName} ({result.Key}): {(isUpdate ? $"{mod.Manifest.Version}{(!localVersion.Equals(mod.Manifest.Version) ? $" [{localVersion}]" : "")} => {info.Version}{(!latestVersion.Equals(new SemanticVersion(info.Version)) ? $" [{latestVersion}]" : "")}" : "okay")}."); + // normalise versions + ISemanticVersion localVersion = mod.DataRecord?.GetLocalVersionForUpdateChecks(mod.Manifest.Version) ?? mod.Manifest.Version; + if (!SemanticVersion.TryParse(mod.DataRecord?.GetRemoteVersionForUpdateChecks(remoteInfo.Version) ?? remoteInfo.Version, out ISemanticVersion remoteVersion)) + { + this.Monitor.Log($" {mod.DisplayName} ({result.Key}): update error: Mod has invalid version {remoteInfo.Version}", LogLevel.Trace); + continue; + } + + // compare versions + bool isUpdate = remoteVersion.IsNewerThan(localVersion); + this.VerboseLog($" {mod.DisplayName} ({result.Key}): {(isUpdate ? $"{mod.Manifest.Version}{(!localVersion.Equals(mod.Manifest.Version) ? $" [{localVersion}]" : "")} => {remoteInfo.Version}{(!remoteVersion.Equals(new SemanticVersion(remoteInfo.Version)) ? $" [{remoteVersion}]" : "")}" : "okay")}."); if (isUpdate) { - if (!updatesByMod.TryGetValue(mod, out ModInfoModel other) || latestVersion.IsNewerThan(other.Version)) - updatesByMod[mod] = info; + if (!updatesByMod.TryGetValue(mod, out ModInfoModel other) || remoteVersion.IsNewerThan(other.Version)) + updatesByMod[mod] = remoteInfo; } } -- cgit From 41715cefcde3c838bb079cb37aac5a3b2dcb1004 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 11 Mar 2018 19:09:08 -0400 Subject: add initial compatibility with Stardew Valley 1.3 (#453) --- build/common.targets | 4 + docs/release-notes.md | 4 + src/SMAPI.ModBuildConfig/build/smapi.targets | 4 + src/SMAPI.ModBuildConfig/package.nuspec | 5 +- .../Framework/Commands/Player/AddCommand.cs | 4 + .../Framework/Commands/Player/SetColorCommand.cs | 10 +- .../Framework/Commands/Player/SetNameCommand.cs | 6 +- .../Commands/World/DownMineLevelCommand.cs | 6 +- .../Commands/World/SetMineLevelCommand.cs | 6 +- .../Framework/ItemRepository.cs | 83 ++- src/SMAPI/Constants.cs | 28 +- src/SMAPI/Events/EventArgsInventoryChanged.cs | 12 +- .../Events/EventArgsLocationObjectsChanged.cs | 18 +- src/SMAPI/Framework/GameVersion.cs | 4 +- src/SMAPI/Framework/SContentManager.cs | 69 ++- src/SMAPI/Framework/SGame.cs | 631 ++++++++++++++++++++- src/SMAPI/Metadata/CoreAssets.cs | 38 +- src/SMAPI/Program.cs | 1 + 18 files changed, 881 insertions(+), 52 deletions(-) (limited to 'src/SMAPI/Program.cs') diff --git a/build/common.targets b/build/common.targets index aa11344e..6773dbe4 100644 --- a/build/common.targets +++ b/build/common.targets @@ -38,6 +38,10 @@ False + + $(GamePath)\Netcode.dll + False + $(GamePath)\Stardew Valley.exe False diff --git a/docs/release-notes.md b/docs/release-notes.md index 5cac1ed8..05a95fc1 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -1,4 +1,8 @@ # Release notes +## 2.6 alpha +* For players: + * Updated for Stardew Valley 1.3 (multiplayer update); no longer compatible with earlier versions. + ## 2.5.3 * For players: * Simplified and improved skipped-incompatible-mod messages. diff --git a/src/SMAPI.ModBuildConfig/build/smapi.targets b/src/SMAPI.ModBuildConfig/build/smapi.targets index 83f0dcbd..7e8bbfc3 100644 --- a/src/SMAPI.ModBuildConfig/build/smapi.targets +++ b/src/SMAPI.ModBuildConfig/build/smapi.targets @@ -67,6 +67,10 @@ false + + $(GamePath)\Netcode.dll + False + $(GamePath)\Stardew Valley.exe false diff --git a/src/SMAPI.ModBuildConfig/package.nuspec b/src/SMAPI.ModBuildConfig/package.nuspec index 91f38a29..8393ab61 100644 --- a/src/SMAPI.ModBuildConfig/package.nuspec +++ b/src/SMAPI.ModBuildConfig/package.nuspec @@ -2,7 +2,7 @@ Pathoschild.Stardew.ModBuildConfig - 2.0.2 + 2.0.3-alpha20180307 Build package for SMAPI mods Pathoschild Pathoschild @@ -26,6 +26,9 @@ 2.0.2: - Fixed compatibility issue on Linux. + + 2.0.3: + - Added support for Stardew Valley 1.3. diff --git a/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/AddCommand.cs b/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/AddCommand.cs index 14a519fb..a6f42b98 100644 --- a/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/AddCommand.cs +++ b/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/AddCommand.cs @@ -54,7 +54,11 @@ namespace StardewModdingAPI.Mods.ConsoleCommands.Framework.Commands.Player // apply quality if (match.Item is Object obj) +#if STARDEW_VALLEY_1_3 + obj.Quality = quality; +#else obj.quality = quality; +#endif else if (match.Item is Tool tool) tool.UpgradeLevel = quality; diff --git a/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/SetColorCommand.cs b/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/SetColorCommand.cs index 5d098593..aa4fd105 100644 --- a/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/SetColorCommand.cs +++ b/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/SetColorCommand.cs @@ -1,4 +1,4 @@ -using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework; using StardewValley; namespace StardewModdingAPI.Mods.ConsoleCommands.Framework.Commands.Player @@ -36,7 +36,11 @@ namespace StardewModdingAPI.Mods.ConsoleCommands.Framework.Commands.Player switch (target) { case "hair": +#if STARDEW_VALLEY_1_3 + Game1.player.hairstyleColor.Value = color; +#else Game1.player.hairstyleColor = color; +#endif monitor.Log("OK, your hair color is updated.", LogLevel.Info); break; @@ -46,7 +50,11 @@ namespace StardewModdingAPI.Mods.ConsoleCommands.Framework.Commands.Player break; case "pants": +#if STARDEW_VALLEY_1_3 + Game1.player.pantsColor.Value = color; +#else Game1.player.pantsColor = color; +#endif monitor.Log("OK, your pants color is updated.", LogLevel.Info); break; } diff --git a/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/SetNameCommand.cs b/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/SetNameCommand.cs index 5b1225e8..71e17f71 100644 --- a/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/SetNameCommand.cs +++ b/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/SetNameCommand.cs @@ -1,4 +1,4 @@ -using StardewValley; +using StardewValley; namespace StardewModdingAPI.Mods.ConsoleCommands.Framework.Commands.Player { @@ -39,7 +39,11 @@ namespace StardewModdingAPI.Mods.ConsoleCommands.Framework.Commands.Player case "farm": if (!string.IsNullOrWhiteSpace(name)) { +#if STARDEW_VALLEY_1_3 + Game1.player.farmName.Value = args[1]; +#else Game1.player.farmName = args[1]; +#endif monitor.Log($"OK, your farm's name is now {Game1.player.farmName}.", LogLevel.Info); } else diff --git a/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/World/DownMineLevelCommand.cs b/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/World/DownMineLevelCommand.cs index da117006..c83c3b07 100644 --- a/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/World/DownMineLevelCommand.cs +++ b/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/World/DownMineLevelCommand.cs @@ -1,4 +1,4 @@ -using StardewValley; +using StardewValley; using StardewValley.Locations; namespace StardewModdingAPI.Mods.ConsoleCommands.Framework.Commands.World @@ -21,7 +21,11 @@ namespace StardewModdingAPI.Mods.ConsoleCommands.Framework.Commands.World { int level = (Game1.currentLocation as MineShaft)?.mineLevel ?? 0; monitor.Log($"OK, warping you to mine level {level + 1}.", LogLevel.Info); +#if STARDEW_VALLEY_1_3 + Game1.enterMine(level + 1); +#else Game1.enterMine(false, level + 1, ""); +#endif } } } diff --git a/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/World/SetMineLevelCommand.cs b/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/World/SetMineLevelCommand.cs index 1024b7b6..5947af1a 100644 --- a/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/World/SetMineLevelCommand.cs +++ b/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/World/SetMineLevelCommand.cs @@ -1,4 +1,4 @@ -using System; +using System; using StardewValley; namespace StardewModdingAPI.Mods.ConsoleCommands.Framework.Commands.World @@ -26,7 +26,11 @@ namespace StardewModdingAPI.Mods.ConsoleCommands.Framework.Commands.World // handle level = Math.Max(1, level); monitor.Log($"OK, warping you to mine level {level}.", LogLevel.Info); +#if STARDEW_VALLEY_1_3 + Game1.enterMine(level); +#else Game1.enterMine(true, level, ""); +#endif } } } diff --git a/src/SMAPI.Mods.ConsoleCommands/Framework/ItemRepository.cs b/src/SMAPI.Mods.ConsoleCommands/Framework/ItemRepository.cs index b5fe9f2f..9c0981c4 100644 --- a/src/SMAPI.Mods.ConsoleCommands/Framework/ItemRepository.cs +++ b/src/SMAPI.Mods.ConsoleCommands/Framework/ItemRepository.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using Microsoft.Xna.Framework; using StardewModdingAPI.Mods.ConsoleCommands.Framework.ItemData; using StardewValley; @@ -95,39 +95,90 @@ namespace StardewModdingAPI.Mods.ConsoleCommands.Framework // fruit products if (item.category == SObject.FruitsCategory) { - yield return new SearchableItem(ItemType.Object, this.CustomIDOffset + id, new SObject(348, 1) + // wine +#if STARDEW_VALLEY_1_3 + SObject wine = + new SObject(348, 1) + { + Name = $"{item.Name} Wine", + Price = item.price * 3 + }; + wine.preserve.Value = SObject.PreserveType.Wine; + wine.preservedParentSheetIndex.Value = item.parentSheetIndex; +#else + SObject wine = new SObject(348, 1) { name = $"{item.Name} Wine", price = item.price * 3, preserve = SObject.PreserveType.Wine, preservedParentSheetIndex = item.parentSheetIndex - }); - yield return new SearchableItem(ItemType.Object, this.CustomIDOffset * 2 + id, new SObject(344, 1) + }; +#endif + yield return new SearchableItem(ItemType.Object, this.CustomIDOffset + id, wine); + + // jelly +#if STARDEW_VALLEY_1_3 + SObject jelly = new SObject(344, 1) + { + Name = $"{item.Name} Jelly", + Price = 50 + item.Price * 2 + }; + jelly.preserve.Value = SObject.PreserveType.Jelly; + jelly.preservedParentSheetIndex.Value = item.parentSheetIndex; +#else + SObject jelly = new SObject(344, 1) { name = $"{item.Name} Jelly", price = 50 + item.Price * 2, preserve = SObject.PreserveType.Jelly, preservedParentSheetIndex = item.parentSheetIndex - }); + }; +#endif + yield return new SearchableItem(ItemType.Object, this.CustomIDOffset * 2 + id, jelly); } // vegetable products else if (item.category == SObject.VegetableCategory) { - yield return new SearchableItem(ItemType.Object, this.CustomIDOffset * 3 + id, new SObject(350, 1) + // juice +#if STARDEW_VALLEY_1_3 + SObject juice = new SObject(350, 1) + { + Name = $"{item.Name} Juice", + Price = (int)(item.price * 2.25d) + }; + juice.preserve.Value = SObject.PreserveType.Juice; + juice.preservedParentSheetIndex.Value = item.parentSheetIndex; +#else + SObject juice = new SObject(350, 1) { name = $"{item.Name} Juice", price = (int)(item.price * 2.25d), preserve = SObject.PreserveType.Juice, preservedParentSheetIndex = item.parentSheetIndex - }); - yield return new SearchableItem(ItemType.Object, this.CustomIDOffset * 4 + id, new SObject(342, 1) + }; +#endif + yield return new SearchableItem(ItemType.Object, this.CustomIDOffset * 3 + id, juice); + + // pickled +#if STARDEW_VALLEY_1_3 + SObject pickled = new SObject(342, 1) + { + Name = $"Pickled {item.Name}", + Price = 50 + item.Price * 2 + }; + pickled.preserve.Value = SObject.PreserveType.Pickle; + pickled.preservedParentSheetIndex.Value = item.parentSheetIndex; +#else + SObject pickled = new SObject(342, 1) { name = $"Pickled {item.Name}", price = 50 + item.Price * 2, preserve = SObject.PreserveType.Pickle, preservedParentSheetIndex = item.parentSheetIndex - }); + }; +#endif + yield return new SearchableItem(ItemType.Object, this.CustomIDOffset * 4 + id, pickled); } // flower honey @@ -160,6 +211,19 @@ namespace StardewModdingAPI.Mods.ConsoleCommands.Framework // yield honey if (type != null) { +#if STARDEW_VALLEY_1_3 + SObject honey = new SObject(Vector2.Zero, 340, item.Name + " Honey", false, true, false, false) + { + Name = "Wild Honey" + }; + honey.honeyType.Value = type; + + if (type != SObject.HoneyType.Wild) + { + honey.Name = $"{item.Name} Honey"; + honey.Price += item.Price * 2; + } +#else SObject honey = new SObject(Vector2.Zero, 340, item.Name + " Honey", false, true, false, false) { name = "Wild Honey", @@ -170,6 +234,7 @@ namespace StardewModdingAPI.Mods.ConsoleCommands.Framework honey.name = $"{item.Name} Honey"; honey.price += item.price * 2; } +#endif yield return new SearchableItem(ItemType.Object, this.CustomIDOffset * 5 + id, honey); } } diff --git a/src/SMAPI/Constants.cs b/src/SMAPI/Constants.cs index 5b2f6e6e..011762fb 100644 --- a/src/SMAPI/Constants.cs +++ b/src/SMAPI/Constants.cs @@ -37,13 +37,28 @@ namespace StardewModdingAPI ** Public ****/ /// SMAPI's current semantic version. - public static ISemanticVersion ApiVersion { get; } = new SemanticVersion("2.5.3"); + public static ISemanticVersion ApiVersion { get; } = +#if STARDEW_VALLEY_1_3 + new SemanticVersion($"2.6-alpha.{DateTime.UtcNow:yyyyMMddHHmm}"); +#else + new SemanticVersion($"2.5.3"); +#endif /// The minimum supported version of Stardew Valley. - public static ISemanticVersion MinimumGameVersion { get; } = new SemanticVersion("1.2.30"); + public static ISemanticVersion MinimumGameVersion { get; } = +#if STARDEW_VALLEY_1_3 + new GameVersion("1.3.0.2"); +#else + new SemanticVersion("1.2.33"); +#endif /// The maximum supported version of Stardew Valley. - public static ISemanticVersion MaximumGameVersion { get; } = new SemanticVersion("1.2.33"); + public static ISemanticVersion MaximumGameVersion { get; } = +#if STARDEW_VALLEY_1_3 + null; +#else + new SemanticVersion("1.2.33"); +#endif /// The path to the game folder. public static string ExecutionPath { get; } = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); @@ -169,7 +184,12 @@ namespace StardewModdingAPI /// Get the name of a save directory for the current player. private static string GetSaveFolderName() { - string prefix = new string(Game1.player.name.Where(char.IsLetterOrDigit).ToArray()); + string prefix = +#if STARDEW_VALLEY_1_3 + new string(Game1.player.name.Value.Where(char.IsLetterOrDigit).ToArray()); +#else + new string(Game1.player.name.Where(char.IsLetterOrDigit).ToArray()); +#endif return $"{prefix}_{Game1.uniqueIDForThisGame}"; } diff --git a/src/SMAPI/Events/EventArgsInventoryChanged.cs b/src/SMAPI/Events/EventArgsInventoryChanged.cs index 1ee02842..b85ae9db 100644 --- a/src/SMAPI/Events/EventArgsInventoryChanged.cs +++ b/src/SMAPI/Events/EventArgsInventoryChanged.cs @@ -12,7 +12,11 @@ namespace StardewModdingAPI.Events ** Accessors *********/ /// The player's inventory. +#if STARDEW_VALLEY_1_3 + public IList Inventory { get; } +#else public List Inventory { get; } +#endif /// The added items. public List Added { get; } @@ -30,7 +34,13 @@ namespace StardewModdingAPI.Events /// Construct an instance. /// The player's inventory. /// The inventory changes. - public EventArgsInventoryChanged(List inventory, List changedItems) + public EventArgsInventoryChanged( +#if STARDEW_VALLEY_1_3 + IList inventory, +#else + List inventory, +#endif + List changedItems) { this.Inventory = inventory; this.Added = changedItems.Where(n => n.ChangeType == ChangeType.Added).ToList(); diff --git a/src/SMAPI/Events/EventArgsLocationObjectsChanged.cs b/src/SMAPI/Events/EventArgsLocationObjectsChanged.cs index 058999e9..de3c31ea 100644 --- a/src/SMAPI/Events/EventArgsLocationObjectsChanged.cs +++ b/src/SMAPI/Events/EventArgsLocationObjectsChanged.cs @@ -1,6 +1,10 @@ -using System; +using System; using Microsoft.Xna.Framework; +#if STARDEW_VALLEY_1_3 +using Netcode; +#else using StardewValley; +#endif using Object = StardewValley.Object; namespace StardewModdingAPI.Events @@ -12,7 +16,11 @@ namespace StardewModdingAPI.Events ** Accessors *********/ /// The current list of objects in the current location. +#if STARDEW_VALLEY_1_3 + public IDictionary> NewObjects { get; } +#else public SerializableDictionary NewObjects { get; } +#endif /********* @@ -20,7 +28,13 @@ namespace StardewModdingAPI.Events *********/ /// Construct an instance. /// The current list of objects in the current location. - public EventArgsLocationObjectsChanged(SerializableDictionary newObjects) + public EventArgsLocationObjectsChanged( +#if STARDEW_VALLEY_1_3 + IDictionary> newObjects +#else + SerializableDictionary newObjects +#endif + ) { this.NewObjects = newObjects; } diff --git a/src/SMAPI/Framework/GameVersion.cs b/src/SMAPI/Framework/GameVersion.cs index 1884afe9..c347ffba 100644 --- a/src/SMAPI/Framework/GameVersion.cs +++ b/src/SMAPI/Framework/GameVersion.cs @@ -23,7 +23,9 @@ namespace StardewModdingAPI.Framework ["1.07"] = "1.0.7", ["1.07a"] = "1.0.8-prerelease1", ["1.08"] = "1.0.8", - ["1.11"] = "1.1.1" + ["1.11"] = "1.1.1", + ["1.3.0.1"] = "1.13-alpha.1", + ["1.3.0.2"] = "1.13-alpha.2" }; diff --git a/src/SMAPI/Framework/SContentManager.cs b/src/SMAPI/Framework/SContentManager.cs index fa51bd53..29c6c684 100644 --- a/src/SMAPI/Framework/SContentManager.cs +++ b/src/SMAPI/Framework/SContentManager.cs @@ -41,11 +41,11 @@ namespace StardewModdingAPI.Framework /// The underlying asset cache. private readonly ContentCache Cache; - /// The private method which generates the locale portion of an asset name. - private readonly IReflectedMethod GetKeyLocale; + /// The locale codes used in asset keys indexed by enum value. + private readonly IDictionary Locales; - /// The language codes used in asset keys. - private readonly IDictionary KeyLocales; + /// The language enum values indexed by locale code. + private readonly IDictionary LanguageCodes; /// Provides metadata for core game assets. private readonly CoreAssets CoreAssets; @@ -95,12 +95,12 @@ namespace StardewModdingAPI.Framework // init this.Monitor = monitor ?? throw new ArgumentNullException(nameof(monitor)); this.Cache = new ContentCache(this, reflection); - this.GetKeyLocale = reflection.GetMethod(this, "languageCode"); this.ModContentPrefix = this.GetAssetNameFromFilePath(Constants.ModPath); // get asset data - this.CoreAssets = new CoreAssets(this.NormaliseAssetName); - this.KeyLocales = this.GetKeyLocales(reflection); + this.CoreAssets = new CoreAssets(this.NormaliseAssetName, reflection); + this.Locales = this.GetKeyLocales(reflection); + this.LanguageCodes = this.Locales.ToDictionary(p => p.Value, p => p.Key, StringComparer.InvariantCultureIgnoreCase); } /**** @@ -153,7 +153,7 @@ namespace StardewModdingAPI.Framework /// Get the current content locale. public string GetLocale() { - return this.GetKeyLocale.Invoke(); + return this.Locales[this.GetCurrentLanguage()]; } /// Get whether the content manager has already loaded and cached the given asset. @@ -398,29 +398,48 @@ namespace StardewModdingAPI.Framework /// Get the locale codes (like ja-JP) used in asset keys. /// Simplifies access to private game code. - private IDictionary GetKeyLocales(Reflector reflection) + private IDictionary GetKeyLocales(Reflector reflection) { - // get the private code field directly to avoid changed-code logic +#if !STARDEW_VALLEY_1_3 IReflectedField codeField = reflection.GetField(typeof(LocalizedContentManager), "_currentLangCode"); - - // remember previous settings LanguageCode previousCode = codeField.GetValue(); +#endif string previousOverride = this.LanguageCodeOverride; - // create locale => code map - IDictionary map = new Dictionary(StringComparer.InvariantCultureIgnoreCase); - this.LanguageCodeOverride = null; - foreach (LanguageCode code in Enum.GetValues(typeof(LanguageCode))) + try { - codeField.SetValue(code); - map[this.GetKeyLocale.Invoke()] = code; - } + // temporarily disable language override + this.LanguageCodeOverride = null; + + // create locale => code map + IReflectedMethod languageCodeString = reflection +#if STARDEW_VALLEY_1_3 + .GetMethod(this, "languageCodeString"); +#else + .GetMethod(this, "languageCode"); +#endif + IDictionary map = new Dictionary(); + foreach (LanguageCode code in Enum.GetValues(typeof(LanguageCode))) + { +#if STARDEW_VALLEY_1_3 + map[code] = languageCodeString.Invoke(code); +#else + codeField.SetValue(code); + map[code] = languageCodeString.Invoke(); +#endif + } - // restore previous settings - codeField.SetValue(previousCode); - this.LanguageCodeOverride = previousOverride; + return map; + } + finally + { + // restore previous settings + this.LanguageCodeOverride = previousOverride; +#if !STARDEW_VALLEY_1_3 + codeField.SetValue(previousCode); +#endif - return map; + } } /// Get the asset name from a cache key. @@ -444,7 +463,7 @@ namespace StardewModdingAPI.Framework if (lastSepIndex >= 0) { string suffix = cacheKey.Substring(lastSepIndex + 1, cacheKey.Length - lastSepIndex - 1); - if (this.KeyLocales.ContainsKey(suffix)) + if (this.LanguageCodes.ContainsKey(suffix)) { assetName = cacheKey.Substring(0, lastSepIndex); localeCode = cacheKey.Substring(lastSepIndex + 1, cacheKey.Length - lastSepIndex - 1); @@ -466,7 +485,7 @@ namespace StardewModdingAPI.Framework private bool IsNormalisedKeyLoaded(string normalisedAssetName) { return this.Cache.ContainsKey(normalisedAssetName) - || this.Cache.ContainsKey($"{normalisedAssetName}.{this.GetKeyLocale.Invoke()}"); // translated asset + || this.Cache.ContainsKey($"{normalisedAssetName}.{this.Locales[this.GetCurrentLanguage()]}"); // translated asset } /// Track that a content manager loaded an asset. diff --git a/src/SMAPI/Framework/SGame.cs b/src/SMAPI/Framework/SGame.cs index 5c45edca..acb3e794 100644 --- a/src/SMAPI/Framework/SGame.cs +++ b/src/SMAPI/Framework/SGame.cs @@ -9,6 +9,9 @@ using System.Threading.Tasks; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; +#if STARDEW_VALLEY_1_3 +using Netcode; +#endif using StardewModdingAPI.Events; using StardewModdingAPI.Framework.Events; using StardewModdingAPI.Framework.Input; @@ -20,7 +23,9 @@ using StardewValley.Locations; using StardewValley.Menus; using StardewValley.Tools; using xTile.Dimensions; +#if !STARDEW_VALLEY_1_3 using xTile.Layers; + #endif namespace StardewModdingAPI.Framework { @@ -145,6 +150,9 @@ namespace StardewModdingAPI.Framework private readonly Action drawFarmBuildings = () => SGame.Reflection.GetMethod(SGame.Instance, nameof(drawFarmBuildings)).Invoke(); private readonly Action drawHUD = () => SGame.Reflection.GetMethod(SGame.Instance, nameof(drawHUD)).Invoke(); private readonly Action drawDialogueBox = () => SGame.Reflection.GetMethod(SGame.Instance, nameof(drawDialogueBox)).Invoke(); +#if STARDEW_VALLEY_1_3 + private readonly Action drawOverlays = spriteBatch => SGame.Reflection.GetMethod(SGame.Instance, nameof(SGame.drawOverlays)).Invoke(spriteBatch); +#endif private readonly Action renderScreenBuffer = () => SGame.Reflection.GetMethod(SGame.Instance, nameof(renderScreenBuffer)).Invoke(); // ReSharper restore ArrangeStaticMemberQualifier, ArrangeThisQualifier, InconsistentNaming @@ -488,6 +496,7 @@ namespace StardewModdingAPI.Framework if (Context.IsWorldReady) { // raise current location changed + // ReSharper disable once PossibleUnintendedReferenceComparison if (Game1.currentLocation != this.PreviousGameLocation) { if (this.VerboseLogging) @@ -523,7 +532,13 @@ namespace StardewModdingAPI.Framework // raise current location's object list changed if (this.GetHash(Game1.currentLocation.objects) != this.PreviousLocationObjects) - this.Events.Location_LocationObjectsChanged.Raise(new EventArgsLocationObjectsChanged(Game1.currentLocation.objects)); + this.Events.Location_LocationObjectsChanged.Raise(new EventArgsLocationObjectsChanged( +#if STARDEW_VALLEY_1_3 + Game1.currentLocation.objects.FieldDict +#else + Game1.currentLocation.objects +#endif + )); // raise time changed if (Game1.timeOfDay != this.PreviousTime) @@ -650,6 +665,619 @@ namespace StardewModdingAPI.Framework [SuppressMessage("ReSharper", "RedundantCast", Justification = "copied from game code as-is")] [SuppressMessage("ReSharper", "RedundantExplicitNullableCreation", Justification = "copied from game code as-is")] [SuppressMessage("ReSharper", "RedundantTypeArgumentsOfMethod", Justification = "copied from game code as-is")] +#if STARDEW_VALLEY_1_3 + private void DrawImpl(GameTime gameTime) + { + if (Game1.debugMode) + { + if (SGame._fpsStopwatch.IsRunning) + { + float totalSeconds = (float)SGame._fpsStopwatch.Elapsed.TotalSeconds; + SGame._fpsList.Add(totalSeconds); + while (SGame._fpsList.Count >= 120) + SGame._fpsList.RemoveAt(0); + float num = 0.0f; + foreach (float fps in SGame._fpsList) + num += fps; + SGame._fps = (float)(1.0 / ((double)num / (double)SGame._fpsList.Count)); + } + SGame._fpsStopwatch.Restart(); + } + else + { + if (SGame._fpsStopwatch.IsRunning) + SGame._fpsStopwatch.Reset(); + SGame._fps = 0.0f; + SGame._fpsList.Clear(); + } + if (SGame._newDayTask != null) + { + this.GraphicsDevice.Clear(this.bgColor); + //base.Draw(gameTime); + } + else + { + if ((double)Game1.options.zoomLevel != 1.0) + this.GraphicsDevice.SetRenderTarget(this.screenWrapper); + if (this.IsSaving) + { + this.GraphicsDevice.Clear(this.bgColor); + IClickableMenu activeClickableMenu = Game1.activeClickableMenu; + if (activeClickableMenu != null) + { + Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, (DepthStencilState)null, (RasterizerState)null); + try + { + this.Events.Graphics_OnPreRenderGuiEvent.Raise(); + activeClickableMenu.draw(Game1.spriteBatch); + this.Events.Graphics_OnPostRenderGuiEvent.Raise(); + } + catch (Exception ex) + { + this.Monitor.Log($"The {activeClickableMenu.GetType().FullName} menu crashed while drawing itself during save. SMAPI will force it to exit to avoid crashing the game.\n{ex.GetLogSummary()}", LogLevel.Error); + activeClickableMenu.exitThisMenu(); + } + this.RaisePostRender(); + Game1.spriteBatch.End(); + } + //base.Draw(gameTime); + this.renderScreenBuffer(); + } + else + { + this.GraphicsDevice.Clear(this.bgColor); + if (Game1.activeClickableMenu != null && Game1.options.showMenuBackground && Game1.activeClickableMenu.showWithoutTransparencyIfOptionIsSet()) + { + Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, (DepthStencilState)null, (RasterizerState)null); + try + { + Game1.activeClickableMenu.drawBackground(Game1.spriteBatch); + this.Events.Graphics_OnPreRenderGuiEvent.Raise(); + Game1.activeClickableMenu.draw(Game1.spriteBatch); + this.Events.Graphics_OnPostRenderGuiEvent.Raise(); + } + catch (Exception ex) + { + this.Monitor.Log($"The {Game1.activeClickableMenu.GetType().FullName} menu crashed while drawing itself. SMAPI will force it to exit to avoid crashing the game.\n{ex.GetLogSummary()}", LogLevel.Error); + Game1.activeClickableMenu.exitThisMenu(); + } + this.RaisePostRender(); + Game1.spriteBatch.End(); + if ((double)Game1.options.zoomLevel != 1.0) + { + this.GraphicsDevice.SetRenderTarget((RenderTarget2D)null); + this.GraphicsDevice.Clear(this.bgColor); + Game1.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone); + Game1.spriteBatch.Draw((Texture2D)this.screenWrapper, Vector2.Zero, new Microsoft.Xna.Framework.Rectangle?(this.screenWrapper.Bounds), Color.White, 0.0f, Vector2.Zero, Game1.options.zoomLevel, SpriteEffects.None, 1f); + Game1.spriteBatch.End(); + } + this.drawOverlays(Game1.spriteBatch); + } + else if ((int)Game1.gameMode == 11) + { + Game1.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, (DepthStencilState)null, (RasterizerState)null); + Game1.spriteBatch.DrawString(Game1.dialogueFont, Game1.content.LoadString("Strings\\StringsFromCSFiles:Game1.cs.3685"), new Vector2(16f, 16f), Color.HotPink); + Game1.spriteBatch.DrawString(Game1.dialogueFont, Game1.content.LoadString("Strings\\StringsFromCSFiles:Game1.cs.3686"), new Vector2(16f, 32f), new Color(0, (int)byte.MaxValue, 0)); + Game1.spriteBatch.DrawString(Game1.dialogueFont, Game1.parseText(Game1.errorMessage, Game1.dialogueFont, Game1.graphics.GraphicsDevice.Viewport.Width), new Vector2(16f, 48f), Color.White); + this.RaisePostRender(); + Game1.spriteBatch.End(); + } + else if (Game1.currentMinigame != null) + { + Game1.currentMinigame.draw(Game1.spriteBatch); + if (Game1.globalFade && !Game1.menuUp && (!Game1.nameSelectUp || Game1.messagePause)) + { + Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, (DepthStencilState)null, (RasterizerState)null); + Game1.spriteBatch.Draw(Game1.fadeToBlackRect, Game1.graphics.GraphicsDevice.Viewport.Bounds, Color.Black * ((int)Game1.gameMode == 0 ? 1f - Game1.fadeToBlackAlpha : Game1.fadeToBlackAlpha)); + Game1.spriteBatch.End(); + } + this.RaisePostRender(needsNewBatch: true); + if ((double)Game1.options.zoomLevel != 1.0) + { + this.GraphicsDevice.SetRenderTarget((RenderTarget2D)null); + this.GraphicsDevice.Clear(this.bgColor); + Game1.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone); + Game1.spriteBatch.Draw((Texture2D)this.screenWrapper, Vector2.Zero, new Microsoft.Xna.Framework.Rectangle?(this.screenWrapper.Bounds), Color.White, 0.0f, Vector2.Zero, Game1.options.zoomLevel, SpriteEffects.None, 1f); + Game1.spriteBatch.End(); + } + this.drawOverlays(Game1.spriteBatch); + } + else if (Game1.showingEndOfNightStuff) + { + Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, (DepthStencilState)null, (RasterizerState)null); + if (Game1.activeClickableMenu != null) + { + try + { + this.Events.Graphics_OnPreRenderGuiEvent.Raise(); + Game1.activeClickableMenu.draw(Game1.spriteBatch); + this.Events.Graphics_OnPostRenderGuiEvent.Raise(); + } + catch (Exception ex) + { + this.Monitor.Log($"The {Game1.activeClickableMenu.GetType().FullName} menu crashed while drawing itself during end-of-night-stuff. SMAPI will force it to exit to avoid crashing the game.\n{ex.GetLogSummary()}", LogLevel.Error); + Game1.activeClickableMenu.exitThisMenu(); + } + } + this.RaisePostRender(); + Game1.spriteBatch.End(); + if ((double)Game1.options.zoomLevel != 1.0) + { + this.GraphicsDevice.SetRenderTarget((RenderTarget2D)null); + this.GraphicsDevice.Clear(this.bgColor); + Game1.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone); + Game1.spriteBatch.Draw((Texture2D)this.screenWrapper, Vector2.Zero, new Microsoft.Xna.Framework.Rectangle?(this.screenWrapper.Bounds), Color.White, 0.0f, Vector2.Zero, Game1.options.zoomLevel, SpriteEffects.None, 1f); + Game1.spriteBatch.End(); + } + this.drawOverlays(Game1.spriteBatch); + } + else + { + int num1; + switch (Game1.gameMode) + { + case 3: + num1 = Game1.currentLocation == null ? 1 : 0; + break; + case 6: + num1 = 1; + break; + default: + num1 = 0; + break; + } + if (num1 != 0) + { + Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, (DepthStencilState)null, (RasterizerState)null); + string str1 = ""; + for (int index = 0; (double)index < gameTime.TotalGameTime.TotalMilliseconds % 999.0 / 333.0; ++index) + str1 += "."; + string str2 = Game1.content.LoadString("Strings\\StringsFromCSFiles:Game1.cs.3688"); + string s = str2 + str1; + string str3 = str2 + "... "; + int widthOfString = SpriteText.getWidthOfString(str3); + int height = 64; + int x = 64; + int y = Game1.graphics.GraphicsDevice.Viewport.TitleSafeArea.Bottom - height; + SpriteText.drawString(Game1.spriteBatch, s, x, y, 999999, widthOfString, height, 1f, 0.88f, false, 0, str3, -1); + Game1.spriteBatch.End(); + if ((double)Game1.options.zoomLevel != 1.0) + { + this.GraphicsDevice.SetRenderTarget((RenderTarget2D)null); + this.GraphicsDevice.Clear(this.bgColor); + Game1.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone); + Game1.spriteBatch.Draw((Texture2D)this.screenWrapper, Vector2.Zero, new Microsoft.Xna.Framework.Rectangle?(this.screenWrapper.Bounds), Color.White, 0.0f, Vector2.Zero, Game1.options.zoomLevel, SpriteEffects.None, 1f); + Game1.spriteBatch.End(); + } + this.drawOverlays(Game1.spriteBatch); + } + else + { + Viewport viewport1; + if ((int)Game1.gameMode == 0) + { + Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, (DepthStencilState)null, (RasterizerState)null); + } + else + { + Microsoft.Xna.Framework.Rectangle bounds; + if (Game1.drawLighting) + { + this.GraphicsDevice.SetRenderTarget(Game1.lightmap); + this.GraphicsDevice.Clear(Color.White * 0.0f); + Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, SamplerState.PointClamp, (DepthStencilState)null, (RasterizerState)null); + Game1.spriteBatch.Draw(Game1.staminaRect, Game1.lightmap.Bounds, Game1.currentLocation.Name.StartsWith("UndergroundMine") ? Game1.mine.getLightingColor(gameTime) : (Game1.ambientLight.Equals(Color.White) || Game1.isRaining && (bool)((NetFieldBase)Game1.currentLocation.isOutdoors) ? Game1.outdoorLight : Game1.ambientLight)); + for (int index = 0; index < Game1.currentLightSources.Count; ++index) + { + if (Utility.isOnScreen((Vector2)((NetFieldBase)Game1.currentLightSources.ElementAt(index).position), (int)((double)(float)((NetFieldBase)Game1.currentLightSources.ElementAt(index).radius) * 64.0 * 4.0))) + { + SpriteBatch spriteBatch = Game1.spriteBatch; + Texture2D lightTexture = Game1.currentLightSources.ElementAt(index).lightTexture; + Vector2 position = Game1.GlobalToLocal(Game1.viewport, (Vector2)((NetFieldBase)Game1.currentLightSources.ElementAt(index).position)) / (float)(Game1.options.lightingQuality / 2); + Microsoft.Xna.Framework.Rectangle? sourceRectangle = new Microsoft.Xna.Framework.Rectangle?(Game1.currentLightSources.ElementAt(index).lightTexture.Bounds); + Color color = (Color)((NetFieldBase)Game1.currentLightSources.ElementAt(index).color); + double num2 = 0.0; + bounds = Game1.currentLightSources.ElementAt(index).lightTexture.Bounds; + double x = (double)bounds.Center.X; + bounds = Game1.currentLightSources.ElementAt(index).lightTexture.Bounds; + double y = (double)bounds.Center.Y; + Vector2 origin = new Vector2((float)x, (float)y); + double num3 = (double)(float)((NetFieldBase)Game1.currentLightSources.ElementAt(index).radius) / (double)(Game1.options.lightingQuality / 2); + int num4 = 0; + double num5 = 0.899999976158142; + spriteBatch.Draw(lightTexture, position, sourceRectangle, color, (float)num2, origin, (float)num3, (SpriteEffects)num4, (float)num5); + } + } + Game1.spriteBatch.End(); + this.GraphicsDevice.SetRenderTarget((double)Game1.options.zoomLevel == 1.0 ? (RenderTarget2D)null : this.screenWrapper); + } + if (Game1.bloomDay && Game1.bloom != null) + Game1.bloom.BeginDraw(); + this.GraphicsDevice.Clear(this.bgColor); + Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, (DepthStencilState)null, (RasterizerState)null); + this.Events.Graphics_OnPreRenderEvent.Raise(); + if (Game1.background != null) + Game1.background.draw(Game1.spriteBatch); + Game1.mapDisplayDevice.BeginScene(Game1.spriteBatch); + Game1.currentLocation.Map.GetLayer("Back").Draw(Game1.mapDisplayDevice, Game1.viewport, Location.Origin, false, 4); + Game1.currentLocation.drawWater(Game1.spriteBatch); + if (Game1.CurrentEvent == null) + { + foreach (NPC character in Game1.currentLocation.characters) + { + if (!(bool)((NetFieldBase)character.swimming) && !character.HideShadow && !character.IsInvisible && !Game1.currentLocation.shouldShadowBeDrawnAboveBuildingsLayer(character.getTileLocation())) + { + SpriteBatch spriteBatch = Game1.spriteBatch; + Texture2D shadowTexture = Game1.shadowTexture; + Vector2 local = Game1.GlobalToLocal(Game1.viewport, character.Position + new Vector2((float)(character.Sprite.SpriteWidth * 4) / 2f, (float)(character.GetBoundingBox().Height + (character.IsMonster ? 0 : 12)))); + Microsoft.Xna.Framework.Rectangle? sourceRectangle = new Microsoft.Xna.Framework.Rectangle?(Game1.shadowTexture.Bounds); + Color white = Color.White; + double num2 = 0.0; + bounds = Game1.shadowTexture.Bounds; + double x = (double)bounds.Center.X; + bounds = Game1.shadowTexture.Bounds; + double y = (double)bounds.Center.Y; + Vector2 origin = new Vector2((float)x, (float)y); + double num3 = (4.0 + (double)character.yJumpOffset / 40.0) * (double)(float)((NetFieldBase)character.scale); + int num4 = 0; + double num5 = (double)Math.Max(0.0f, (float)character.getStandingY() / 10000f) - 9.99999997475243E-07; + spriteBatch.Draw(shadowTexture, local, sourceRectangle, white, (float)num2, origin, (float)num3, (SpriteEffects)num4, (float)num5); + } + } + } + else + { + foreach (NPC actor in Game1.CurrentEvent.actors) + { + if (!(bool)((NetFieldBase)actor.swimming) && !actor.HideShadow && !Game1.currentLocation.shouldShadowBeDrawnAboveBuildingsLayer(actor.getTileLocation())) + { + SpriteBatch spriteBatch = Game1.spriteBatch; + Texture2D shadowTexture = Game1.shadowTexture; + Vector2 local = Game1.GlobalToLocal(Game1.viewport, actor.Position + new Vector2((float)(actor.Sprite.SpriteWidth * 4) / 2f, (float)(actor.GetBoundingBox().Height + (actor.IsMonster ? 0 : (actor.Sprite.SpriteHeight <= 16 ? -4 : 12))))); + Microsoft.Xna.Framework.Rectangle? sourceRectangle = new Microsoft.Xna.Framework.Rectangle?(Game1.shadowTexture.Bounds); + Color white = Color.White; + double num2 = 0.0; + bounds = Game1.shadowTexture.Bounds; + double x = (double)bounds.Center.X; + bounds = Game1.shadowTexture.Bounds; + double y = (double)bounds.Center.Y; + Vector2 origin = new Vector2((float)x, (float)y); + double num3 = (4.0 + (double)actor.yJumpOffset / 40.0) * (double)(float)((NetFieldBase)actor.scale); + int num4 = 0; + double num5 = (double)Math.Max(0.0f, (float)actor.getStandingY() / 10000f) - 9.99999997475243E-07; + spriteBatch.Draw(shadowTexture, local, sourceRectangle, white, (float)num2, origin, (float)num3, (SpriteEffects)num4, (float)num5); + } + } + } + Game1.currentLocation.Map.GetLayer("Buildings").Draw(Game1.mapDisplayDevice, Game1.viewport, Location.Origin, false, 4); + Game1.mapDisplayDevice.EndScene(); + Game1.spriteBatch.End(); + Game1.spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend, SamplerState.PointClamp, (DepthStencilState)null, (RasterizerState)null); + if (Game1.CurrentEvent == null) + { + foreach (NPC character in Game1.currentLocation.characters) + { + if (!(bool)((NetFieldBase)character.swimming) && !character.HideShadow && Game1.currentLocation.shouldShadowBeDrawnAboveBuildingsLayer(character.getTileLocation())) + Game1.spriteBatch.Draw(Game1.shadowTexture, Game1.GlobalToLocal(Game1.viewport, character.Position + new Vector2((float)(character.Sprite.SpriteWidth * 4) / 2f, (float)(character.GetBoundingBox().Height + (character.IsMonster ? 0 : 12)))), new Microsoft.Xna.Framework.Rectangle?(Game1.shadowTexture.Bounds), Color.White, 0.0f, new Vector2((float)Game1.shadowTexture.Bounds.Center.X, (float)Game1.shadowTexture.Bounds.Center.Y), (float)(4.0 + (double)character.yJumpOffset / 40.0) * (float)((NetFieldBase)character.scale), SpriteEffects.None, Math.Max(0.0f, (float)character.getStandingY() / 10000f) - 1E-06f); + } + } + else + { + foreach (NPC actor in Game1.CurrentEvent.actors) + { + if (!(bool)((NetFieldBase)actor.swimming) && !actor.HideShadow && Game1.currentLocation.shouldShadowBeDrawnAboveBuildingsLayer(actor.getTileLocation())) + Game1.spriteBatch.Draw(Game1.shadowTexture, Game1.GlobalToLocal(Game1.viewport, actor.Position + new Vector2((float)(actor.Sprite.SpriteWidth * 4) / 2f, (float)(actor.GetBoundingBox().Height + (actor.IsMonster ? 0 : 12)))), new Microsoft.Xna.Framework.Rectangle?(Game1.shadowTexture.Bounds), Color.White, 0.0f, new Vector2((float)Game1.shadowTexture.Bounds.Center.X, (float)Game1.shadowTexture.Bounds.Center.Y), (float)(4.0 + (double)actor.yJumpOffset / 40.0) * (float)((NetFieldBase)actor.scale), SpriteEffects.None, Math.Max(0.0f, (float)actor.getStandingY() / 10000f) - 1E-06f); + } + } + if ((Game1.eventUp || Game1.killScreen) && (!Game1.killScreen && Game1.currentLocation.currentEvent != null)) + Game1.currentLocation.currentEvent.draw(Game1.spriteBatch); + if (Game1.player.currentUpgrade != null && Game1.player.currentUpgrade.daysLeftTillUpgradeDone <= 3 && Game1.currentLocation.Name.Equals("Farm")) + Game1.spriteBatch.Draw(Game1.player.currentUpgrade.workerTexture, Game1.GlobalToLocal(Game1.viewport, Game1.player.currentUpgrade.positionOfCarpenter), new Microsoft.Xna.Framework.Rectangle?(Game1.player.currentUpgrade.getSourceRectangle()), Color.White, 0.0f, Vector2.Zero, 1f, SpriteEffects.None, (float)(((double)Game1.player.currentUpgrade.positionOfCarpenter.Y + 48.0) / 10000.0)); + Game1.currentLocation.draw(Game1.spriteBatch); + if (!Game1.eventUp || Game1.currentLocation.currentEvent == null || Game1.currentLocation.currentEvent.messageToScreen == null) + ; + if (Game1.player.ActiveObject == null && ((Game1.player.UsingTool || Game1.pickingTool) && Game1.player.CurrentTool != null && (!Game1.player.CurrentTool.Name.Equals("Seeds") || Game1.pickingTool))) + Game1.drawTool(Game1.player); + if (Game1.currentLocation.Name.Equals("Farm")) + this.drawFarmBuildings(); + if (Game1.tvStation >= 0) + Game1.spriteBatch.Draw(Game1.tvStationTexture, Game1.GlobalToLocal(Game1.viewport, new Vector2(400f, 160f)), new Microsoft.Xna.Framework.Rectangle?(new Microsoft.Xna.Framework.Rectangle(Game1.tvStation * 24, 0, 24, 15)), Color.White, 0.0f, Vector2.Zero, 4f, SpriteEffects.None, 1E-08f); + if (Game1.panMode) + { + Game1.spriteBatch.Draw(Game1.fadeToBlackRect, new Microsoft.Xna.Framework.Rectangle((int)Math.Floor((double)(Game1.getOldMouseX() + Game1.viewport.X) / 64.0) * 64 - Game1.viewport.X, (int)Math.Floor((double)(Game1.getOldMouseY() + Game1.viewport.Y) / 64.0) * 64 - Game1.viewport.Y, 64, 64), Color.Lime * 0.75f); + foreach (Warp warp in (NetList>)Game1.currentLocation.warps) + Game1.spriteBatch.Draw(Game1.fadeToBlackRect, new Microsoft.Xna.Framework.Rectangle(warp.X * 64 - Game1.viewport.X, warp.Y * 64 - Game1.viewport.Y, 64, 64), Color.Red * 0.75f); + } + Game1.mapDisplayDevice.BeginScene(Game1.spriteBatch); + Game1.currentLocation.Map.GetLayer("Front").Draw(Game1.mapDisplayDevice, Game1.viewport, Location.Origin, false, 4); + Game1.mapDisplayDevice.EndScene(); + Game1.currentLocation.drawAboveFrontLayer(Game1.spriteBatch); + Game1.spriteBatch.End(); + Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, (DepthStencilState)null, (RasterizerState)null); + if (Game1.displayFarmer && Game1.player.ActiveObject != null && ((bool)((NetFieldBase)Game1.player.ActiveObject.bigCraftable) && this.checkBigCraftableBoundariesForFrontLayer()) && Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location(Game1.player.getStandingX(), Game1.player.getStandingY()), Game1.viewport.Size) == null) + Game1.drawPlayerHeldObject(Game1.player); + else if (Game1.displayFarmer && Game1.player.ActiveObject != null && (Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location((int)Game1.player.Position.X, (int)Game1.player.Position.Y - 38), Game1.viewport.Size) != null && !Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location((int)Game1.player.Position.X, (int)Game1.player.Position.Y - 38), Game1.viewport.Size).TileIndexProperties.ContainsKey("FrontAlways") || Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location(Game1.player.GetBoundingBox().Right, (int)Game1.player.Position.Y - 38), Game1.viewport.Size) != null && !Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location(Game1.player.GetBoundingBox().Right, (int)Game1.player.Position.Y - 38), Game1.viewport.Size).TileIndexProperties.ContainsKey("FrontAlways"))) + Game1.drawPlayerHeldObject(Game1.player); + if ((Game1.player.UsingTool || Game1.pickingTool) && Game1.player.CurrentTool != null && ((!Game1.player.CurrentTool.Name.Equals("Seeds") || Game1.pickingTool) && Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location(Game1.player.getStandingX(), (int)Game1.player.Position.Y - 38), Game1.viewport.Size) != null) && Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location(Game1.player.getStandingX(), Game1.player.getStandingY()), Game1.viewport.Size) == null) + Game1.drawTool(Game1.player); + if (Game1.currentLocation.Map.GetLayer("AlwaysFront") != null) + { + Game1.mapDisplayDevice.BeginScene(Game1.spriteBatch); + Game1.currentLocation.Map.GetLayer("AlwaysFront").Draw(Game1.mapDisplayDevice, Game1.viewport, Location.Origin, false, 4); + Game1.mapDisplayDevice.EndScene(); + } + if ((double)Game1.toolHold > 400.0 && Game1.player.CurrentTool.UpgradeLevel >= 1 && Game1.player.canReleaseTool) + { + Color color = Color.White; + switch ((int)((double)Game1.toolHold / 600.0) + 2) + { + case 1: + color = Tool.copperColor; + break; + case 2: + color = Tool.steelColor; + break; + case 3: + color = Tool.goldColor; + break; + case 4: + color = Tool.iridiumColor; + break; + } + Game1.spriteBatch.Draw(Game1.littleEffect, new Microsoft.Xna.Framework.Rectangle((int)Game1.player.getLocalPosition(Game1.viewport).X - 2, (int)Game1.player.getLocalPosition(Game1.viewport).Y - (Game1.player.CurrentTool.Name.Equals("Watering Can") ? 0 : 64) - 2, (int)((double)Game1.toolHold % 600.0 * 0.0799999982118607) + 4, 12), Color.Black); + Game1.spriteBatch.Draw(Game1.littleEffect, new Microsoft.Xna.Framework.Rectangle((int)Game1.player.getLocalPosition(Game1.viewport).X, (int)Game1.player.getLocalPosition(Game1.viewport).Y - (Game1.player.CurrentTool.Name.Equals("Watering Can") ? 0 : 64), (int)((double)Game1.toolHold % 600.0 * 0.0799999982118607), 8), color); + } + if (Game1.isDebrisWeather && Game1.currentLocation.IsOutdoors && (!(bool)((NetFieldBase)Game1.currentLocation.ignoreDebrisWeather) && !Game1.currentLocation.Name.Equals("Desert")) && Game1.viewport.X > -10) + { + foreach (WeatherDebris weatherDebris in Game1.debrisWeather) + weatherDebris.draw(Game1.spriteBatch); + } + if (Game1.farmEvent != null) + Game1.farmEvent.draw(Game1.spriteBatch); + if ((double)Game1.currentLocation.LightLevel > 0.0 && Game1.timeOfDay < 2000) + Game1.spriteBatch.Draw(Game1.fadeToBlackRect, Game1.graphics.GraphicsDevice.Viewport.Bounds, Color.Black * Game1.currentLocation.LightLevel); + if (Game1.screenGlow) + Game1.spriteBatch.Draw(Game1.fadeToBlackRect, Game1.graphics.GraphicsDevice.Viewport.Bounds, Game1.screenGlowColor * Game1.screenGlowAlpha); + Game1.currentLocation.drawAboveAlwaysFrontLayer(Game1.spriteBatch); + if (Game1.player.CurrentTool != null && Game1.player.CurrentTool is FishingRod && ((Game1.player.CurrentTool as FishingRod).isTimingCast || (double)(Game1.player.CurrentTool as FishingRod).castingChosenCountdown > 0.0 || (Game1.player.CurrentTool as FishingRod).fishCaught || (Game1.player.CurrentTool as FishingRod).showingTreasure)) + Game1.player.CurrentTool.draw(Game1.spriteBatch); + if (Game1.isRaining && Game1.currentLocation.IsOutdoors && (!Game1.currentLocation.Name.Equals("Desert") && !(Game1.currentLocation is Summit)) && (!Game1.eventUp || Game1.currentLocation.isTileOnMap(new Vector2((float)(Game1.viewport.X / 64), (float)(Game1.viewport.Y / 64))))) + { + for (int index = 0; index < Game1.rainDrops.Length; ++index) + Game1.spriteBatch.Draw(Game1.rainTexture, Game1.rainDrops[index].position, new Microsoft.Xna.Framework.Rectangle?(Game1.getSourceRectForStandardTileSheet(Game1.rainTexture, Game1.rainDrops[index].frame, -1, -1)), Color.White); + } + Game1.spriteBatch.End(); + //base.Draw(gameTime); + Game1.spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend, SamplerState.PointClamp, (DepthStencilState)null, (RasterizerState)null); + if (Game1.eventUp && Game1.currentLocation.currentEvent != null) + { + foreach (NPC actor in Game1.currentLocation.currentEvent.actors) + { + if (actor.isEmoting) + { + Vector2 localPosition = actor.getLocalPosition(Game1.viewport); + localPosition.Y -= 140f; + if (actor.Age == 2) + localPosition.Y += 32f; + else if (actor.Gender == 1) + localPosition.Y += 10f; + Game1.spriteBatch.Draw(Game1.emoteSpriteSheet, localPosition, new Microsoft.Xna.Framework.Rectangle?(new Microsoft.Xna.Framework.Rectangle(actor.CurrentEmoteIndex * 16 % Game1.emoteSpriteSheet.Width, actor.CurrentEmoteIndex * 16 / Game1.emoteSpriteSheet.Width * 16, 16, 16)), Color.White, 0.0f, Vector2.Zero, 4f, SpriteEffects.None, (float)actor.getStandingY() / 10000f); + } + } + } + Game1.spriteBatch.End(); + if (Game1.drawLighting) + { + Game1.spriteBatch.Begin(SpriteSortMode.Deferred, this.lightingBlend, SamplerState.LinearClamp, (DepthStencilState)null, (RasterizerState)null); + Game1.spriteBatch.Draw((Texture2D)Game1.lightmap, Vector2.Zero, new Microsoft.Xna.Framework.Rectangle?(Game1.lightmap.Bounds), Color.White, 0.0f, Vector2.Zero, (float)(Game1.options.lightingQuality / 2), SpriteEffects.None, 1f); + if (Game1.isRaining && (bool)((NetFieldBase)Game1.currentLocation.isOutdoors) && !(Game1.currentLocation is Desert)) + Game1.spriteBatch.Draw(Game1.staminaRect, Game1.graphics.GraphicsDevice.Viewport.Bounds, Color.OrangeRed * 0.45f); + Game1.spriteBatch.End(); + } + Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, (DepthStencilState)null, (RasterizerState)null); + if (Game1.drawGrid) + { + int num2 = -Game1.viewport.X % 64; + float num3 = (float)(-Game1.viewport.Y % 64); + int num4 = num2; + while (true) + { + int num5 = num4; + viewport1 = Game1.graphics.GraphicsDevice.Viewport; + int width1 = viewport1.Width; + if (num5 < width1) + { + SpriteBatch spriteBatch = Game1.spriteBatch; + Texture2D staminaRect = Game1.staminaRect; + int x = num4; + int y = (int)num3; + int width2 = 1; + viewport1 = Game1.graphics.GraphicsDevice.Viewport; + int height = viewport1.Height; + Microsoft.Xna.Framework.Rectangle destinationRectangle = new Microsoft.Xna.Framework.Rectangle(x, y, width2, height); + Color color = Color.Red * 0.5f; + spriteBatch.Draw(staminaRect, destinationRectangle, color); + num4 += 64; + } + else + break; + } + float num6 = num3; + while (true) + { + double num5 = (double)num6; + viewport1 = Game1.graphics.GraphicsDevice.Viewport; + double height1 = (double)viewport1.Height; + if (num5 < height1) + { + SpriteBatch spriteBatch = Game1.spriteBatch; + Texture2D staminaRect = Game1.staminaRect; + int x = num2; + int y = (int)num6; + viewport1 = Game1.graphics.GraphicsDevice.Viewport; + int width = viewport1.Width; + int height2 = 1; + Microsoft.Xna.Framework.Rectangle destinationRectangle = new Microsoft.Xna.Framework.Rectangle(x, y, width, height2); + Color color = Color.Red * 0.5f; + spriteBatch.Draw(staminaRect, destinationRectangle, color); + num6 += 64f; + } + else + break; + } + } + if ((uint)Game1.currentBillboard > 0U) + this.drawBillboard(); + if ((Game1.displayHUD || Game1.eventUp) && (Game1.currentBillboard == 0 && (int)Game1.gameMode == 3) && (!Game1.freezeControls && !Game1.panMode) && !Game1.HostPaused) + { + this.Events.Graphics_OnPreRenderHudEvent.Raise(); + this.drawHUD(); + this.Events.Graphics_OnPostRenderHudEvent.Raise(); + } + else if (Game1.activeClickableMenu == null && Game1.farmEvent == null) + Game1.spriteBatch.Draw(Game1.mouseCursors, new Vector2((float)Game1.getOldMouseX(), (float)Game1.getOldMouseY()), new Microsoft.Xna.Framework.Rectangle?(Game1.getSourceRectForStandardTileSheet(Game1.mouseCursors, 0, 16, 16)), Color.White, 0.0f, Vector2.Zero, (float)(4.0 + (double)Game1.dialogueButtonScale / 150.0), SpriteEffects.None, 1f); + if (Game1.hudMessages.Count > 0 && (!Game1.eventUp || Game1.isFestival())) + { + for (int i = Game1.hudMessages.Count - 1; i >= 0; --i) + Game1.hudMessages[i].draw(Game1.spriteBatch, i); + } + } + if (Game1.farmEvent != null) + Game1.farmEvent.draw(Game1.spriteBatch); + if (Game1.dialogueUp && !Game1.nameSelectUp && !Game1.messagePause && (Game1.activeClickableMenu == null || !(Game1.activeClickableMenu is DialogueBox))) + this.drawDialogueBox(); + if (Game1.progressBar) + { + SpriteBatch spriteBatch1 = Game1.spriteBatch; + Texture2D fadeToBlackRect = Game1.fadeToBlackRect; + viewport1 = Game1.graphics.GraphicsDevice.Viewport; + int x1 = (viewport1.TitleSafeArea.Width - Game1.dialogueWidth) / 2; + viewport1 = Game1.graphics.GraphicsDevice.Viewport; + Microsoft.Xna.Framework.Rectangle titleSafeArea = viewport1.TitleSafeArea; + int y1 = titleSafeArea.Bottom - 128; + int dialogueWidth = Game1.dialogueWidth; + int height1 = 32; + Microsoft.Xna.Framework.Rectangle destinationRectangle1 = new Microsoft.Xna.Framework.Rectangle(x1, y1, dialogueWidth, height1); + Color lightGray = Color.LightGray; + spriteBatch1.Draw(fadeToBlackRect, destinationRectangle1, lightGray); + SpriteBatch spriteBatch2 = Game1.spriteBatch; + Texture2D staminaRect = Game1.staminaRect; + viewport1 = Game1.graphics.GraphicsDevice.Viewport; + int x2 = (viewport1.TitleSafeArea.Width - Game1.dialogueWidth) / 2; + viewport1 = Game1.graphics.GraphicsDevice.Viewport; + titleSafeArea = viewport1.TitleSafeArea; + int y2 = titleSafeArea.Bottom - 128; + int width = (int)((double)Game1.pauseAccumulator / (double)Game1.pauseTime * (double)Game1.dialogueWidth); + int height2 = 32; + Microsoft.Xna.Framework.Rectangle destinationRectangle2 = new Microsoft.Xna.Framework.Rectangle(x2, y2, width, height2); + Color dimGray = Color.DimGray; + spriteBatch2.Draw(staminaRect, destinationRectangle2, dimGray); + } + if (Game1.eventUp && (Game1.currentLocation != null && Game1.currentLocation.currentEvent != null)) + Game1.currentLocation.currentEvent.drawAfterMap(Game1.spriteBatch); + if (Game1.isRaining && (Game1.currentLocation != null && (bool)((NetFieldBase)Game1.currentLocation.isOutdoors) && !(Game1.currentLocation is Desert))) + { + SpriteBatch spriteBatch = Game1.spriteBatch; + Texture2D staminaRect = Game1.staminaRect; + viewport1 = Game1.graphics.GraphicsDevice.Viewport; + Microsoft.Xna.Framework.Rectangle bounds = viewport1.Bounds; + Color color = Color.Blue * 0.2f; + spriteBatch.Draw(staminaRect, bounds, color); + } + if ((Game1.fadeToBlack || Game1.globalFade) && !Game1.menuUp && (!Game1.nameSelectUp || Game1.messagePause)) + { + SpriteBatch spriteBatch = Game1.spriteBatch; + Texture2D fadeToBlackRect = Game1.fadeToBlackRect; + viewport1 = Game1.graphics.GraphicsDevice.Viewport; + Microsoft.Xna.Framework.Rectangle bounds = viewport1.Bounds; + Color color = Color.Black * ((int)Game1.gameMode == 0 ? 1f - Game1.fadeToBlackAlpha : Game1.fadeToBlackAlpha); + spriteBatch.Draw(fadeToBlackRect, bounds, color); + } + else if ((double)Game1.flashAlpha > 0.0) + { + if (Game1.options.screenFlash) + { + SpriteBatch spriteBatch = Game1.spriteBatch; + Texture2D fadeToBlackRect = Game1.fadeToBlackRect; + viewport1 = Game1.graphics.GraphicsDevice.Viewport; + Microsoft.Xna.Framework.Rectangle bounds = viewport1.Bounds; + Color color = Color.White * Math.Min(1f, Game1.flashAlpha); + spriteBatch.Draw(fadeToBlackRect, bounds, color); + } + Game1.flashAlpha -= 0.1f; + } + if ((Game1.messagePause || Game1.globalFade) && Game1.dialogueUp) + this.drawDialogueBox(); + foreach (TemporaryAnimatedSprite overlayTempSprite in Game1.screenOverlayTempSprites) + overlayTempSprite.draw(Game1.spriteBatch, true, 0, 0, 1f); + if (Game1.debugMode) + { + SpriteBatch spriteBatch = Game1.spriteBatch; + SpriteFont smallFont = Game1.smallFont; + object[] objArray = new object[10]; + int index = 0; + string str; + if (!Game1.panMode) + str = "player: " + (object)(Game1.player.getStandingX() / 64) + ", " + (object)(Game1.player.getStandingY() / 64); + else + str = ((Game1.getOldMouseX() + Game1.viewport.X) / 64).ToString() + "," + (object)((Game1.getOldMouseY() + Game1.viewport.Y) / 64); + objArray[index] = (object)str; + objArray[1] = (object)" mouseTransparency: "; + objArray[2] = (object)Game1.mouseCursorTransparency; + objArray[3] = (object)" mousePosition: "; + objArray[4] = (object)Game1.getMouseX(); + objArray[5] = (object)","; + objArray[6] = (object)Game1.getMouseY(); + objArray[7] = (object)Environment.NewLine; + objArray[8] = (object)"debugOutput: "; + objArray[9] = (object)Game1.debugOutput; + string text = string.Concat(objArray); + Viewport viewport2 = this.GraphicsDevice.Viewport; + double x = (double)viewport2.TitleSafeArea.X; + viewport2 = this.GraphicsDevice.Viewport; + double y = (double)viewport2.TitleSafeArea.Y; + Vector2 position = new Vector2((float)x, (float)y); + Color red = Color.Red; + double num2 = 0.0; + Vector2 zero = Vector2.Zero; + double num3 = 1.0; + int num4 = 0; + double num5 = 0.99999988079071; + spriteBatch.DrawString(smallFont, text, position, red, (float)num2, zero, (float)num3, (SpriteEffects)num4, (float)num5); + } + if (Game1.showKeyHelp) + Game1.spriteBatch.DrawString(Game1.smallFont, Game1.keyHelpString, new Vector2(64f, (float)(Game1.viewport.Height - 64 - (Game1.dialogueUp ? 192 + (Game1.isQuestion ? Game1.questionChoices.Count * 64 : 0) : 0)) - Game1.smallFont.MeasureString(Game1.keyHelpString).Y), Color.LightGray, 0.0f, Vector2.Zero, 1f, SpriteEffects.None, 0.9999999f); + if (Game1.activeClickableMenu != null) + { + try + { + this.Events.Graphics_OnPreRenderGuiEvent.Raise(); + Game1.activeClickableMenu.draw(Game1.spriteBatch); + this.Events.Graphics_OnPostRenderGuiEvent.Raise(); + } + catch (Exception ex) + { + this.Monitor.Log($"The {Game1.activeClickableMenu.GetType().FullName} menu crashed while drawing itself. SMAPI will force it to exit to avoid crashing the game.\n{ex.GetLogSummary()}", LogLevel.Error); + Game1.activeClickableMenu.exitThisMenu(); + } + } + else if (Game1.farmEvent != null) + Game1.farmEvent.drawAboveEverything(Game1.spriteBatch); + if (Game1.HostPaused) + { + string s = Game1.content.LoadString("Strings\\StringsFromCSFiles:DayTimeMoneyBox.cs.10378"); + SpriteText.drawStringWithScrollBackground(Game1.spriteBatch, s, 96, 32, "", 1f, -1); + } + this.RaisePostRender(); + Game1.spriteBatch.End(); + this.drawOverlays(Game1.spriteBatch); + this.renderScreenBuffer(); + } + } + } + } + } +#else private void DrawImpl(GameTime gameTime) { if (Game1.debugMode) @@ -1301,6 +1929,7 @@ namespace StardewModdingAPI.Framework } } } +#endif /**** ** Methods diff --git a/src/SMAPI/Metadata/CoreAssets.cs b/src/SMAPI/Metadata/CoreAssets.cs index 5a98da4b..c027df25 100644 --- a/src/SMAPI/Metadata/CoreAssets.cs +++ b/src/SMAPI/Metadata/CoreAssets.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework.Graphics; using StardewModdingAPI.Framework; +using StardewModdingAPI.Framework.Reflection; using StardewValley; using StardewValley.BellsAndWhistles; using StardewValley.Buildings; @@ -31,7 +32,8 @@ namespace StardewModdingAPI.Metadata *********/ /// Initialise the core asset data. /// Normalises an asset key to match the cache key. - public CoreAssets(Func getNormalisedPath) + /// Simplifies access to private code. + public CoreAssets(Func getNormalisedPath, Reflector reflection) { this.GetNormalisedPath = getNormalisedPath; this.SingletonSetters = @@ -82,6 +84,25 @@ namespace StardewModdingAPI.Metadata // from Game1.ResetToolSpriteSheet ["TileSheets\\tools"] = (content, key) => Game1.ResetToolSpriteSheet(), +#if STARDEW_VALLEY_1_3 + // from Bush + ["TileSheets\\bushes"] = (content, key) => reflection.GetField>(typeof(Bush), "texture").SetValue(new Lazy(() => content.Load(key))), + + // from Farm + ["Buildings\\houses"] = (content, key) => reflection.GetField(typeof(Farm), nameof(Farm.houseTextures)).SetValue(content.Load(key)), + + // from Farmer + ["Characters\\Farmer\\farmer_base"] = (content, key) => + { + if (Game1.player != null && Game1.player.isMale) + Game1.player.FarmerRenderer = new FarmerRenderer(key); + }, + ["Characters\\Farmer\\farmer_girl_base"] = (content, key) => + { + if (Game1.player != null && !Game1.player.isMale) + Game1.player.FarmerRenderer = new FarmerRenderer(key); + }, +#else // from Bush ["TileSheets\\bushes"] = (content, key) => Bush.texture = content.Load(key), @@ -107,6 +128,7 @@ namespace StardewModdingAPI.Metadata if (Game1.player != null && !Game1.player.isMale) Game1.player.FarmerRenderer = new FarmerRenderer(content.Load(key)); }, +#endif // from Flooring ["TerrainFeatures\\Flooring"] = (content, key) => Flooring.floorsTexture = content.Load(key), @@ -144,9 +166,15 @@ namespace StardewModdingAPI.Metadata Building[] buildings = this.GetAllBuildings().Where(p => key == this.GetNormalisedPath($"Buildings\\{p.buildingType}")).ToArray(); if (buildings.Any()) { +#if STARDEW_VALLEY_1_3 + foreach (Building building in buildings) + building.texture = new Lazy(() => content.Load(key)); +#else Texture2D texture = content.Load(key); foreach (Building building in buildings) building.texture = texture; +#endif + return true; } return false; @@ -162,9 +190,11 @@ namespace StardewModdingAPI.Metadata /// Get all player-constructed buildings in the world. private IEnumerable GetAllBuildings() { - return Game1.locations - .OfType() - .SelectMany(p => p.buildings); + foreach (BuildableGameLocation location in Game1.locations.OfType()) + { + foreach (Building building in location.buildings) + yield return building; + } } } } diff --git a/src/SMAPI/Program.cs b/src/SMAPI/Program.cs index 1a1b9645..9c00e581 100644 --- a/src/SMAPI/Program.cs +++ b/src/SMAPI/Program.cs @@ -247,6 +247,7 @@ namespace StardewModdingAPI try { this.IsGameRunning = true; + StardewValley.Program.releaseBuild = true; // game's debug logic interferes with SMAPI opening the game window this.GameInstance.Run(); } catch (Exception ex) -- cgit From 9c49d090a06c96ff2c1f4978da67e864177c2a2e Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 11 Mar 2018 20:03:52 -0400 Subject: reorganise and update core content logic for Stardew Valley 1.3 (#453) --- src/SMAPI/Framework/ContentCore.cs | 864 ++++++++++++++++++++++++ src/SMAPI/Framework/ContentManagerShim.cs | 68 +- src/SMAPI/Framework/ModHelpers/ContentHelper.cs | 43 +- src/SMAPI/Framework/SContentManager.cs | 809 ---------------------- src/SMAPI/Framework/SGame.cs | 16 +- src/SMAPI/Metadata/CoreAssets.cs | 9 +- src/SMAPI/Program.cs | 36 +- src/SMAPI/StardewModdingAPI.csproj | 2 +- 8 files changed, 981 insertions(+), 866 deletions(-) create mode 100644 src/SMAPI/Framework/ContentCore.cs delete mode 100644 src/SMAPI/Framework/SContentManager.cs (limited to 'src/SMAPI/Program.cs') diff --git a/src/SMAPI/Framework/ContentCore.cs b/src/SMAPI/Framework/ContentCore.cs new file mode 100644 index 00000000..85b8db8f --- /dev/null +++ b/src/SMAPI/Framework/ContentCore.cs @@ -0,0 +1,864 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.Contracts; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Threading; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Content; +using Microsoft.Xna.Framework.Graphics; +using StardewModdingAPI.Framework.Content; +using StardewModdingAPI.Framework.Exceptions; +using StardewModdingAPI.Framework.Reflection; +using StardewModdingAPI.Framework.Utilities; +using StardewModdingAPI.Metadata; +using StardewValley; + +namespace StardewModdingAPI.Framework +{ + /// A thread-safe content handler which loads assets with support for mod injection and editing. + /// + /// This is the centralised content logic which manages all game assets. The game and mods don't use this class + /// directly; instead they use one of several instances, which proxy requests to + /// this class. That ensures that when the game disposes one content manager, the others can continue unaffected. + /// That notably requires this class to be thread-safe, since the content managers can be disposed asynchronously. + /// + /// Note that assets in the cache have two identifiers: the asset name (like "bundles") and key (like "bundles.pt-BR"). + /// For English and non-translatable assets, these have the same value. The underlying cache only knows about asset + /// keys, and the game and mods only know about asset names. The content manager handles resolving them. + /// + internal class ContentCore : IDisposable + { + /********* + ** Properties + *********/ + /// The underlying content manager. + private readonly LocalizedContentManager Content; + + /// Encapsulates monitoring and logging. + private readonly IMonitor Monitor; + + /// The underlying asset cache. + private readonly ContentCache Cache; + + /// The locale codes used in asset keys indexed by enum value. + private readonly IDictionary Locales; + + /// The language enum values indexed by locale code. + private readonly IDictionary LanguageCodes; + + /// Provides metadata for core game assets. + private readonly CoreAssets CoreAssets; + + /// The assets currently being intercepted by instances. This is used to prevent infinite loops when a loader loads a new asset. + private readonly ContextHash AssetsBeingLoaded = new ContextHash(); + + /// A lookup of the content managers which loaded each asset. + private readonly IDictionary> ContentManagersByAssetKey = new Dictionary>(); + + /// The path prefix for assets in mod folders. + private readonly string ModContentPrefix; + + /// A lock used to prevents concurrent changes to the cache while data is being read. + private readonly ReaderWriterLockSlim Lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); + + + /********* + ** Accessors + *********/ + /// The current language as a constant. + public LocalizedContentManager.LanguageCode Language => this.Content.GetCurrentLanguage(); + + /// Interceptors which provide the initial versions of matching assets. + public IDictionary> Loaders { get; } = new Dictionary>(); + + /// Interceptors which edit matching assets after they're loaded. + public IDictionary> Editors { get; } = new Dictionary>(); + + /// The absolute path to the . + public string FullRootDirectory => Path.Combine(Constants.ExecutionPath, this.Content.RootDirectory); + + /********* + ** Public methods + *********/ + /**** + ** Constructor + ****/ + /// Construct an instance. + /// The service provider to use to locate services. + /// The root directory to search for content. + /// The current culture for which to localise content. + /// The current language code for which to localise content. + /// Encapsulates monitoring and logging. + /// Simplifies access to private code. + public ContentCore(IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, string languageCodeOverride, IMonitor monitor, Reflector reflection) + { + // init + this.Monitor = monitor ?? throw new ArgumentNullException(nameof(monitor)); + this.Content = new LocalizedContentManager(serviceProvider, rootDirectory, currentCulture, languageCodeOverride); + this.Cache = new ContentCache(this.Content, reflection); + this.ModContentPrefix = this.GetAssetNameFromFilePath(Constants.ModPath); + + // get asset data + this.CoreAssets = new CoreAssets(this.NormaliseAssetName, reflection); + this.Locales = this.GetKeyLocales(reflection); + this.LanguageCodes = this.Locales.ToDictionary(p => p.Value, p => p.Key, StringComparer.InvariantCultureIgnoreCase); + } + + /// Get a new content manager which defers loading to the content core. + /// The content manager's name for logs (if any). + /// The root directory to search for content (or null. for the default) + public ContentManagerShim CreateContentManager(string name, string rootDirectory = null) + { + return new ContentManagerShim(this, name, this.Content.ServiceProvider, rootDirectory ?? this.Content.RootDirectory, this.Content.CurrentCulture, this.Content.LanguageCodeOverride); + } + + /**** + ** Asset key/name handling + ****/ + /// Normalise path separators in a file path. For asset keys, see instead. + /// The file path to normalise. + [Pure] + public string NormalisePathSeparators(string path) + { + return this.Cache.NormalisePathSeparators(path); + } + + /// Normalise an asset name so it's consistent with the underlying cache. + /// The asset key. + [Pure] + public string NormaliseAssetName(string assetName) + { + return this.Cache.NormaliseKey(assetName); + } + + /// Assert that the given key has a valid format. + /// The asset key to check. + /// The asset key is empty or contains invalid characters. + [SuppressMessage("ReSharper", "ParameterOnlyUsedForPreconditionCheck.Local", Justification = "Parameter is only used for assertion checks by design.")] + public void AssertValidAssetKeyFormat(string key) + { + if (string.IsNullOrWhiteSpace(key)) + throw new ArgumentException("The asset key or local path is empty."); + if (key.Intersect(Path.GetInvalidPathChars()).Any()) + throw new ArgumentException("The asset key or local path contains invalid characters."); + } + + /// Convert an absolute file path into a appropriate asset name. + /// The absolute path to the file. + public string GetAssetNameFromFilePath(string absolutePath) + { +#if SMAPI_FOR_WINDOWS + // XNA doesn't allow absolute asset paths, so get a path relative to the content folder + return this.GetRelativePath(absolutePath); +#else + // MonoGame is weird about relative paths on Mac, but allows absolute paths + return absolutePath; +#endif + } + + /**** + ** Content loading + ****/ + /// Get the current content locale. + public string GetLocale() + { + return this.GetLocale(this.Content.GetCurrentLanguage()); + } + + /// The locale for a language. + /// The language. + public string GetLocale(LocalizedContentManager.LanguageCode language) + { + return this.Locales[language]; + } + + /// Get whether the content manager has already loaded and cached the given asset. + /// The asset path relative to the loader root directory, not including the .xnb extension. + public bool IsLoaded(string assetName) + { + assetName = this.Cache.NormaliseKey(assetName); + return this.WithReadLock(() => this.IsNormalisedKeyLoaded(assetName)); + } + + /// Get the cached asset keys. + public IEnumerable GetAssetKeys() + { + return this.WithReadLock(() => + this.Cache.Keys + .Select(this.GetAssetName) + .Distinct() + ); + } + + /// Load an asset through the content pipeline. When loading a .png file, this must be called outside the game's draw loop. + /// The expected asset type. + /// The asset path relative to the content directory. + /// The content manager instance for which to load the asset. + /// The language code for which to load content. + /// The is empty or contains invalid characters. + /// The content asset couldn't be loaded (e.g. because it doesn't exist). + public T Load(string assetName, ContentManager instance +#if STARDEW_VALLEY_1_3 + , LocalizedContentManager.LanguageCode language +#endif + ) + { + // normalise asset key + this.AssertValidAssetKeyFormat(assetName); + assetName = this.NormaliseAssetName(assetName); + + // load game content + if (!assetName.StartsWith(this.ModContentPrefix)) +#if STARDEW_VALLEY_1_3 + return this.LoadImpl(assetName, instance, language); +#else + return this.LoadImpl(assetName, instance); +#endif + + // load mod content + SContentLoadException GetContentError(string reasonPhrase) => new SContentLoadException($"Failed loading content asset '{assetName}': {reasonPhrase}"); + try + { + return this.WithWriteLock(() => + { + // try cache + if (this.IsLoaded(assetName)) +#if STARDEW_VALLEY_1_3 + return this.LoadImpl(assetName, instance, language); +#else + return this.LoadImpl(assetName, instance); +#endif + + // get file + FileInfo file = this.GetModFile(assetName); + if (!file.Exists) + throw GetContentError("the specified path doesn't exist."); + + // load content + switch (file.Extension.ToLower()) + { + // XNB file + case ".xnb": +#if STARDEW_VALLEY_1_3 + return this.LoadImpl(assetName, instance, language); +#else + return this.LoadImpl(assetName, instance); +#endif + + // unpacked map + case ".tbin": + throw GetContentError($"can't read unpacked map file '{assetName}' directly from the underlying content manager. It must be loaded through the mod's {typeof(IModHelper)}.{nameof(IModHelper.Content)} helper."); + + // unpacked image + case ".png": + // validate + if (typeof(T) != typeof(Texture2D)) + throw GetContentError($"can't read file with extension '{file.Extension}' as type '{typeof(T)}'; must be type '{typeof(Texture2D)}'."); + + // fetch & cache + using (FileStream stream = File.OpenRead(file.FullName)) + { + Texture2D texture = Texture2D.FromStream(Game1.graphics.GraphicsDevice, stream); + texture = this.PremultiplyTransparency(texture); + this.InjectWithoutLock(assetName, texture, instance); + return (T)(object)texture; + } + + default: + throw GetContentError($"unknown file extension '{file.Extension}'; must be one of '.png', '.tbin', or '.xnb'."); + } + }); + } + catch (Exception ex) when (!(ex is SContentLoadException)) + { + if (ex.GetInnermostException() is DllNotFoundException dllEx && dllEx.Message == "libgdiplus.dylib") + throw GetContentError("couldn't find libgdiplus, which is needed to load mod images. Make sure Mono is installed and you're running the game through the normal launcher."); + throw new SContentLoadException($"The content manager failed loading content asset '{assetName}'.", ex); + } + } + + /// Inject an asset into the cache. + /// The type of asset to inject. + /// The asset path relative to the loader root directory, not including the .xnb extension. + /// The asset value. + /// The content manager instance for which to load the asset. + public void Inject(string assetName, T value, ContentManager instance) + { + this.WithWriteLock(() => this.InjectWithoutLock(assetName, value, instance)); + } + + /**** + ** Cache invalidation + ****/ + /// Purge assets from the cache that match one of the interceptors. + /// The asset editors for which to purge matching assets. + /// The asset loaders for which to purge matching assets. + /// Returns whether any cache entries were invalidated. + public bool InvalidateCacheFor(IAssetEditor[] editors, IAssetLoader[] loaders) + { + if (!editors.Any() && !loaders.Any()) + return false; + + // get CanEdit/Load methods + MethodInfo canEdit = typeof(IAssetEditor).GetMethod(nameof(IAssetEditor.CanEdit)); + MethodInfo canLoad = typeof(IAssetLoader).GetMethod(nameof(IAssetLoader.CanLoad)); + if (canEdit == null || canLoad == null) + throw new InvalidOperationException("SMAPI could not access the interceptor methods."); // should never happen + + // invalidate matching keys + return this.InvalidateCache(asset => + { + // check loaders + MethodInfo canLoadGeneric = canLoad.MakeGenericMethod(asset.DataType); + if (loaders.Any(loader => (bool)canLoadGeneric.Invoke(loader, new object[] { asset }))) + return true; + + // check editors + MethodInfo canEditGeneric = canEdit.MakeGenericMethod(asset.DataType); + return editors.Any(editor => (bool)canEditGeneric.Invoke(editor, new object[] { asset })); + }); + } + + /// Purge matched assets from the cache. + /// Matches the asset keys to invalidate. + /// Whether to dispose invalidated assets. This should only be true when they're being invalidated as part of a dispose, to avoid crashing the game. + /// Returns whether any cache entries were invalidated. + public bool InvalidateCache(Func predicate, bool dispose = false) + { + string locale = this.GetLocale(); + return this.InvalidateCache((assetName, type) => + { + IAssetInfo info = new AssetInfo(locale, assetName, type, this.NormaliseAssetName); + return predicate(info); + }); + } + + /// Purge matched assets from the cache. + /// Matches the asset keys to invalidate. + /// Whether to dispose invalidated assets. This should only be true when they're being invalidated as part of a dispose, to avoid crashing the game. + /// Returns whether any cache entries were invalidated. + public bool InvalidateCache(Func predicate, bool dispose = false) + { + return this.WithWriteLock(() => + { + // invalidate matching keys + HashSet removeKeys = new HashSet(StringComparer.InvariantCultureIgnoreCase); + HashSet removeAssetNames = new HashSet(StringComparer.InvariantCultureIgnoreCase); + this.Cache.Remove((key, type) => + { + this.ParseCacheKey(key, out string assetName, out _); + if (removeAssetNames.Contains(assetName) || predicate(assetName, type)) + { + removeAssetNames.Add(assetName); + removeKeys.Add(key); + return true; + } + return false; + }); + + // update reference tracking + foreach (string key in removeKeys) + this.ContentManagersByAssetKey.Remove(key); + + // reload core game assets + int reloaded = 0; + foreach (string key in removeAssetNames) + { + if (this.CoreAssets.ReloadForKey(Game1.content, key)) // use an intercepted content manager + reloaded++; + } + + // report result + if (removeKeys.Any()) + { + this.Monitor.Log($"Invalidated {removeAssetNames.Count} asset names: {string.Join(", ", removeKeys.OrderBy(p => p, StringComparer.InvariantCultureIgnoreCase))}. Reloaded {reloaded} core assets.", LogLevel.Trace); + return true; + } + this.Monitor.Log("Invalidated 0 cache entries.", LogLevel.Trace); + return false; + }); + } + + /**** + ** Disposal + ****/ + /// Dispose assets for the given content manager shim. + /// The content manager whose assets to dispose. + internal void DisposeFor(ContentManagerShim shim) + { + this.Monitor.Log($"Content manager '{shim.Name}' disposed, disposing assets that aren't needed by any other asset loader.", LogLevel.Trace); + + this.WithWriteLock(() => + { + foreach (var entry in this.ContentManagersByAssetKey) + entry.Value.Remove(shim); + this.InvalidateCache((key, type) => !this.ContentManagersByAssetKey[key].Any(), dispose: true); + }); + } + + + /********* + ** Private methods + *********/ + /**** + ** Disposal + ****/ + /// Dispose held resources. + public void Dispose() + { + this.Monitor.Log("Disposing SMAPI's main content manager. It will no longer be usable after this point.", LogLevel.Trace); + this.Content.Dispose(); + } + + /**** + ** Asset name/key handling + ****/ + /// Get a directory or file path relative to the content root. + /// The target file path. + private string GetRelativePath(string targetPath) + { + return PathUtilities.GetRelativePath(this.FullRootDirectory, targetPath); + } + + /// Get the locale codes (like ja-JP) used in asset keys. + /// Simplifies access to private game code. + private IDictionary GetKeyLocales(Reflector reflection) + { +#if !STARDEW_VALLEY_1_3 + IReflectedField codeField = reflection.GetField(typeof(LocalizedContentManager), "_currentLangCode"); + LocalizedContentManager.LanguageCode previousCode = codeField.GetValue(); +#endif + string previousOverride = this.Content.LanguageCodeOverride; + + try + { + // temporarily disable language override + this.Content.LanguageCodeOverride = null; + + // create locale => code map + IReflectedMethod languageCodeString = reflection +#if STARDEW_VALLEY_1_3 + .GetMethod(this.Content, "languageCodeString"); +#else + .GetMethod(this.Content, "languageCode"); +#endif + IDictionary map = new Dictionary(); + foreach (LocalizedContentManager.LanguageCode code in Enum.GetValues(typeof(LocalizedContentManager.LanguageCode))) + { +#if STARDEW_VALLEY_1_3 + map[code] = languageCodeString.Invoke(code); +#else + codeField.SetValue(code); + map[code] = languageCodeString.Invoke(); +#endif + } + + return map; + } + finally + { + // restore previous settings + this.Content.LanguageCodeOverride = previousOverride; +#if !STARDEW_VALLEY_1_3 + codeField.SetValue(previousCode); +#endif + + } + } + + /// Get the asset name from a cache key. + /// The input cache key. + private string GetAssetName(string cacheKey) + { + this.ParseCacheKey(cacheKey, out string assetName, out string _); + return assetName; + } + + /// Parse a cache key into its component parts. + /// The input cache key. + /// The original asset name. + /// The asset locale code (or null if not localised). + private void ParseCacheKey(string cacheKey, out string assetName, out string localeCode) + { + // handle localised key + if (!string.IsNullOrWhiteSpace(cacheKey)) + { + int lastSepIndex = cacheKey.LastIndexOf(".", StringComparison.InvariantCulture); + if (lastSepIndex >= 0) + { + string suffix = cacheKey.Substring(lastSepIndex + 1, cacheKey.Length - lastSepIndex - 1); + if (this.LanguageCodes.ContainsKey(suffix)) + { + assetName = cacheKey.Substring(0, lastSepIndex); + localeCode = cacheKey.Substring(lastSepIndex + 1, cacheKey.Length - lastSepIndex - 1); + return; + } + } + } + + // handle simple key + assetName = cacheKey; + localeCode = null; + } + + /**** + ** Cache handling + ****/ + /// Get whether an asset has already been loaded. + /// The normalised asset name. + private bool IsNormalisedKeyLoaded(string normalisedAssetName) + { + return this.Cache.ContainsKey(normalisedAssetName) + || this.Cache.ContainsKey($"{normalisedAssetName}.{this.Locales[this.Content.GetCurrentLanguage()]}"); // translated asset + } + + /// Track that a content manager loaded an asset. + /// The asset key that was loaded. + /// The content manager that loaded the asset. + private void TrackAssetLoader(string key, ContentManager manager) + { + if (!this.ContentManagersByAssetKey.TryGetValue(key, out HashSet hash)) + hash = this.ContentManagersByAssetKey[key] = new HashSet(); + hash.Add(manager); + } + + /**** + ** Content loading + ****/ + /// Load an asset name without heuristics to support mod content. + /// The type of asset to load. + /// The asset path relative to the loader root directory, not including the .xnb extension. + /// The content manager instance for which to load the asset. + /// The language code for which to load content. + private T LoadImpl(string assetName, ContentManager instance +#if STARDEW_VALLEY_1_3 + , LocalizedContentManager.LanguageCode language +#endif + ) + { + return this.WithWriteLock(() => + { + // skip if already loaded + if (this.IsNormalisedKeyLoaded(assetName)) + { + this.TrackAssetLoader(assetName, instance); + return this.Content + +#if STARDEW_VALLEY_1_3 + .Load(assetName, language); +#else + .Load(assetName); +#endif + } + + // load asset + T data; + if (this.AssetsBeingLoaded.Contains(assetName)) + { + this.Monitor.Log($"Broke loop while loading asset '{assetName}'.", LogLevel.Warn); + this.Monitor.Log($"Bypassing mod loaders for this asset. Stack trace:\n{Environment.StackTrace}", LogLevel.Trace); + data = this.Content +#if STARDEW_VALLEY_1_3 + .Load(assetName, language); +#else + .Load(assetName); +#endif + } + else + { + data = this.AssetsBeingLoaded.Track(assetName, () => + { + string locale = +#if STARDEW_VALLEY_1_3 + this.GetLocale(language); +#else + this.GetLocale(); +#endif + IAssetInfo info = new AssetInfo(locale, assetName, typeof(T), this.NormaliseAssetName); + IAssetData asset = this.ApplyLoader(info) +#if STARDEW_VALLEY_1_3 + ?? new AssetDataForObject(info, this.Content.Load(assetName, language), this.NormaliseAssetName); +#else + ?? new AssetDataForObject(info, this.Content.Load(assetName), this.NormaliseAssetName); +#endif + asset = this.ApplyEditors(info, asset); + return (T)asset.Data; + }); + } + + // update cache & return data + this.InjectWithoutLock(assetName, data, instance); + return data; + }); + } + + /// Inject an asset into the cache without acquiring a write lock. This should only be called from within a write lock. + /// The type of asset to inject. + /// The asset path relative to the loader root directory, not including the .xnb extension. + /// The asset value. + /// The content manager instance for which to load the asset. + private void InjectWithoutLock(string assetName, T value, ContentManager instance) + { + assetName = this.NormaliseAssetName(assetName); + this.Cache[assetName] = value; + this.TrackAssetLoader(assetName, instance); + } + + /// Get a file from the mod folder. + /// The asset path relative to the content folder. + private FileInfo GetModFile(string path) + { + // try exact match + FileInfo file = new FileInfo(Path.Combine(this.FullRootDirectory, path)); + + // try with default extension + if (!file.Exists && file.Extension.ToLower() != ".xnb") + { + FileInfo result = new FileInfo(file.FullName + ".xnb"); + if (result.Exists) + file = result; + } + + return file; + } + + /// Load the initial asset from the registered . + /// The basic asset metadata. + /// Returns the loaded asset metadata, or null if no loader matched. + private IAssetData ApplyLoader(IAssetInfo info) + { + // find matching loaders + var loaders = this.GetInterceptors(this.Loaders) + .Where(entry => + { + try + { + return entry.Value.CanLoad(info); + } + catch (Exception ex) + { + entry.Key.LogAsMod($"Mod failed when checking whether it could load asset '{info.AssetName}', and will be ignored. Error details:\n{ex.GetLogSummary()}", LogLevel.Error); + return false; + } + }) + .ToArray(); + + // validate loaders + if (!loaders.Any()) + return null; + if (loaders.Length > 1) + { + string[] loaderNames = loaders.Select(p => p.Key.DisplayName).ToArray(); + this.Monitor.Log($"Multiple mods want to provide the '{info.AssetName}' asset ({string.Join(", ", loaderNames)}), but an asset can't be loaded multiple times. SMAPI will use the default asset instead; uninstall one of the mods to fix this. (Message for modders: you should usually use {typeof(IAssetEditor)} instead to avoid conflicts.)", LogLevel.Warn); + return null; + } + + // fetch asset from loader + IModMetadata mod = loaders[0].Key; + IAssetLoader loader = loaders[0].Value; + T data; + try + { + data = loader.Load(info); + this.Monitor.Log($"{mod.DisplayName} loaded asset '{info.AssetName}'.", LogLevel.Trace); + } + catch (Exception ex) + { + mod.LogAsMod($"Mod crashed when loading asset '{info.AssetName}'. SMAPI will use the default asset instead. Error details:\n{ex.GetLogSummary()}", LogLevel.Error); + 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.NormaliseAssetName); + } + + /// Apply any to a loaded asset. + /// The asset type. + /// The basic asset metadata. + /// The loaded asset. + private IAssetData ApplyEditors(IAssetInfo info, IAssetData asset) + { + IAssetData GetNewData(object data) => new AssetDataForObject(info, data, this.NormaliseAssetName); + + // edit asset + foreach (var entry in this.GetInterceptors(this.Editors)) + { + // check for match + IModMetadata mod = entry.Key; + IAssetEditor editor = entry.Value; + try + { + if (!editor.CanEdit(info)) + continue; + } + catch (Exception ex) + { + mod.LogAsMod($"Mod crashed when checking whether it could edit asset '{info.AssetName}', and will be ignored. Error details:\n{ex.GetLogSummary()}", LogLevel.Error); + continue; + } + + // try edit + object prevAsset = asset.Data; + try + { + editor.Edit(asset); + this.Monitor.Log($"{mod.DisplayName} intercepted {info.AssetName}.", LogLevel.Trace); + } + catch (Exception ex) + { + mod.LogAsMod($"Mod crashed when editing asset '{info.AssetName}', which may cause errors in-game. Error details:\n{ex.GetLogSummary()}", LogLevel.Error); + } + + // validate edit + if (asset.Data == null) + { + mod.LogAsMod($"Mod incorrectly set asset '{info.AssetName}' to a null value; ignoring override.", LogLevel.Warn); + asset = GetNewData(prevAsset); + } + else if (!(asset.Data is T)) + { + mod.LogAsMod($"Mod incorrectly set asset '{asset.AssetName}' to incompatible type '{asset.Data.GetType()}', expected '{typeof(T)}'; ignoring override.", LogLevel.Warn); + asset = GetNewData(prevAsset); + } + } + + // return result + return asset; + } + + /// Get all registered interceptors from a list. + private IEnumerable> GetInterceptors(IDictionary> entries) + { + foreach (var entry in entries) + { + IModMetadata mod = entry.Key; + IList interceptors = entry.Value; + + // registered editors + foreach (T interceptor in interceptors) + yield return new KeyValuePair(mod, interceptor); + } + } + + /// Premultiply a texture's alpha values to avoid transparency issues in the game. This is only possible if the game isn't currently drawing. + /// The texture to premultiply. + /// Returns a premultiplied texture. + /// Based on code by Layoric. + private Texture2D PremultiplyTransparency(Texture2D texture) + { + // validate + if (Context.IsInDrawLoop) + throw new NotSupportedException("Can't load a PNG file while the game is drawing to the screen. Make sure you load content outside the draw loop."); + + // process texture + SpriteBatch spriteBatch = Game1.spriteBatch; + GraphicsDevice gpu = Game1.graphics.GraphicsDevice; + using (RenderTarget2D renderTarget = new RenderTarget2D(Game1.graphics.GraphicsDevice, texture.Width, texture.Height)) + { + // create blank render target to premultiply + gpu.SetRenderTarget(renderTarget); + gpu.Clear(Color.Black); + + // multiply each color by the source alpha, and write just the color values into the final texture + spriteBatch.Begin(SpriteSortMode.Immediate, new BlendState + { + ColorDestinationBlend = Blend.Zero, + ColorWriteChannels = ColorWriteChannels.Red | ColorWriteChannels.Green | ColorWriteChannels.Blue, + AlphaDestinationBlend = Blend.Zero, + AlphaSourceBlend = Blend.SourceAlpha, + ColorSourceBlend = Blend.SourceAlpha + }); + spriteBatch.Draw(texture, texture.Bounds, Color.White); + spriteBatch.End(); + + // copy the alpha values from the source texture into the final one without multiplying them + spriteBatch.Begin(SpriteSortMode.Immediate, new BlendState + { + ColorWriteChannels = ColorWriteChannels.Alpha, + AlphaDestinationBlend = Blend.Zero, + ColorDestinationBlend = Blend.Zero, + AlphaSourceBlend = Blend.One, + ColorSourceBlend = Blend.One + }); + spriteBatch.Draw(texture, texture.Bounds, Color.White); + spriteBatch.End(); + + // release GPU + gpu.SetRenderTarget(null); + + // extract premultiplied data + Color[] data = new Color[texture.Width * texture.Height]; + renderTarget.GetData(data); + + // unset texture from GPU to regain control + gpu.Textures[0] = null; + + // update texture with premultiplied data + texture.SetData(data); + } + + return texture; + } + + /**** + ** Concurrency logic + ****/ + /// Acquire a read lock which prevents concurrent writes to the cache while it's open. + /// The action's return value. + /// The action to perform. + private T WithReadLock(Func action) + { + try + { + this.Lock.EnterReadLock(); + return action(); + } + finally + { + this.Lock.ExitReadLock(); + } + } + + /// Acquire a write lock which prevents concurrent reads or writes to the cache while it's open. + /// The action to perform. + private void WithWriteLock(Action action) + { + try + { + this.Lock.EnterWriteLock(); + action(); + } + finally + { + this.Lock.ExitWriteLock(); + } + } + + /// Acquire a write lock which prevents concurrent reads or writes to the cache while it's open. + /// The action's return value. + /// The action to perform. + private T WithWriteLock(Func action) + { + try + { + this.Lock.EnterWriteLock(); + return action(); + } + finally + { + this.Lock.ExitWriteLock(); + } + } + } +} diff --git a/src/SMAPI/Framework/ContentManagerShim.cs b/src/SMAPI/Framework/ContentManagerShim.cs index d46f23a3..8f88fc2d 100644 --- a/src/SMAPI/Framework/ContentManagerShim.cs +++ b/src/SMAPI/Framework/ContentManagerShim.cs @@ -1,15 +1,17 @@ +using System; +using System.Globalization; using StardewValley; namespace StardewModdingAPI.Framework { - /// A minimal content manager which defers to SMAPI's main content manager. + /// A minimal content manager which defers to SMAPI's core content logic. internal class ContentManagerShim : LocalizedContentManager { /********* ** Properties *********/ - /// SMAPI's underlying content manager. - private readonly SContentManager ContentManager; + /// SMAPI's core content logic. + private readonly ContentCore ContentCore; /********* @@ -23,12 +25,16 @@ namespace StardewModdingAPI.Framework ** Public methods *********/ /// Construct an instance. - /// SMAPI's underlying content manager. + /// SMAPI's core content logic. /// The content manager's name for logs (if any). - public ContentManagerShim(SContentManager contentManager, string name) - : base(contentManager.ServiceProvider, contentManager.RootDirectory, contentManager.CurrentCulture, contentManager.LanguageCodeOverride) + /// The service provider to use to locate services. + /// The root directory to search for content. + /// The current culture for which to localise content. + /// The current language code for which to localise content. + public ContentManagerShim(ContentCore contentCore, string name, IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, string languageCodeOverride) + : base(serviceProvider, rootDirectory, currentCulture, languageCodeOverride) { - this.ContentManager = contentManager; + this.ContentCore = contentCore; this.Name = name; } @@ -37,14 +43,58 @@ namespace StardewModdingAPI.Framework /// The asset path relative to the loader root directory, not including the .xnb extension. public override T Load(string assetName) { - return this.ContentManager.LoadFor(assetName, this); +#if STARDEW_VALLEY_1_3 + return this.Load(assetName, LocalizedContentManager.CurrentLanguageCode); +#else + return this.ContentCore.Load(assetName, this); +#endif } +#if STARDEW_VALLEY_1_3 + /// Load an asset that has been processed by the content pipeline. + /// The type of asset to load. + /// The asset path relative to the loader root directory, not including the .xnb extension. + /// The language code for which to load content. + public override T Load(string assetName, LanguageCode language) + { + return this.ContentCore.Load(assetName, this, language); + } + + /// Load the base asset without localisation. + /// The type of asset to load. + /// The asset path relative to the loader root directory, not including the .xnb extension. + public override T LoadBase(string assetName) + { + return this.Load(assetName, LanguageCode.en); + } +#endif + + /// Inject an asset into the cache. + /// The type of asset to inject. + /// The asset path relative to the loader root directory, not including the .xnb extension. + /// The asset value. + public void Inject(string assetName, T value) + { + this.ContentCore.Inject(assetName, value, this); + } + +#if STARDEW_VALLEY_1_3 + /// Create a new content manager for temporary use. + public override LocalizedContentManager CreateTemporary() + { + return this.ContentCore.CreateContentManager("(temporary)"); + } +#endif + + + /********* + ** Protected methods + *********/ /// Dispose held resources. /// Whether the content manager is disposing (rather than finalising). protected override void Dispose(bool disposing) { - this.ContentManager.DisposeFor(this); + this.ContentCore.DisposeFor(this); } } } diff --git a/src/SMAPI/Framework/ModHelpers/ContentHelper.cs b/src/SMAPI/Framework/ModHelpers/ContentHelper.cs index 7d8bec1e..c7d4c39e 100644 --- a/src/SMAPI/Framework/ModHelpers/ContentHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/ContentHelper.cs @@ -22,8 +22,11 @@ namespace StardewModdingAPI.Framework.ModHelpers /********* ** Properties *********/ - /// SMAPI's underlying content manager. - private readonly SContentManager ContentManager; + /// SMAPI's core content logic. + private readonly ContentCore ContentCore; + + /// The content manager for this mod. + private readonly ContentManagerShim ContentManager; /// The absolute path to the mod folder. private readonly string ModFolderPath; @@ -39,10 +42,10 @@ namespace StardewModdingAPI.Framework.ModHelpers ** Accessors *********/ /// The game's current locale code (like pt-BR). - public string CurrentLocale => this.ContentManager.GetLocale(); + public string CurrentLocale => this.ContentCore.GetLocale(); /// The game's current locale as an enum value. - public LocalizedContentManager.LanguageCode CurrentLocaleConstant => this.ContentManager.GetCurrentLanguage(); + public LocalizedContentManager.LanguageCode CurrentLocaleConstant => this.ContentCore.Language; /// The observable implementation of . internal ObservableCollection ObservableAssetEditors { get; } = new ObservableCollection(); @@ -61,14 +64,16 @@ namespace StardewModdingAPI.Framework.ModHelpers ** Public methods *********/ /// Construct an instance. - /// SMAPI's underlying content manager. + /// SMAPI's core content logic. + /// The content manager for this mod. /// The absolute path to the mod folder. /// The unique ID of the relevant mod. /// The friendly mod name for use in errors. /// Encapsulates monitoring and logging. - public ContentHelper(SContentManager contentManager, string modFolderPath, string modID, string modName, IMonitor monitor) + public ContentHelper(ContentCore contentCore, ContentManagerShim contentManager, string modFolderPath, string modID, string modName, IMonitor monitor) : base(modID) { + this.ContentCore = contentCore; this.ContentManager = contentManager; this.ModFolderPath = modFolderPath; this.ModName = modName; @@ -100,10 +105,10 @@ namespace StardewModdingAPI.Framework.ModHelpers throw GetContentError($"there's no matching file at path '{file.FullName}'."); // get asset path - string assetName = this.ContentManager.GetAssetNameFromFilePath(file.FullName); + string assetName = this.ContentCore.GetAssetNameFromFilePath(file.FullName); // try cache - if (this.ContentManager.IsLoaded(assetName)) + if (this.ContentCore.IsLoaded(assetName)) return this.ContentManager.Load(assetName); // fix map tilesheets @@ -119,7 +124,7 @@ namespace StardewModdingAPI.Framework.ModHelpers this.FixCustomTilesheetPaths(map, key); // inject map - this.ContentManager.Inject(assetName, map, this.ContentManager); + this.ContentManager.Inject(assetName, map); return (T)(object)map; } @@ -141,7 +146,7 @@ namespace StardewModdingAPI.Framework.ModHelpers [Pure] public string NormaliseAssetName(string assetName) { - return this.ContentManager.NormaliseAssetName(assetName); + return this.ContentCore.NormaliseAssetName(assetName); } /// Get the underlying key in the game's content cache for an asset. This can be used to load custom map tilesheets, but should be avoided when you can use the content API instead. This does not validate whether the asset exists. @@ -153,11 +158,11 @@ namespace StardewModdingAPI.Framework.ModHelpers switch (source) { case ContentSource.GameContent: - return this.ContentManager.NormaliseAssetName(key); + return this.ContentCore.NormaliseAssetName(key); case ContentSource.ModFolder: FileInfo file = this.GetModFile(key); - return this.ContentManager.NormaliseAssetName(this.ContentManager.GetAssetNameFromFilePath(file.FullName)); + return this.ContentCore.NormaliseAssetName(this.ContentCore.GetAssetNameFromFilePath(file.FullName)); default: throw new NotSupportedException($"Unknown content source '{source}'."); @@ -172,7 +177,7 @@ namespace StardewModdingAPI.Framework.ModHelpers { string actualKey = this.GetActualAssetKey(key, ContentSource.GameContent); this.Monitor.Log($"Requested cache invalidation for '{actualKey}'.", LogLevel.Trace); - return this.ContentManager.InvalidateCache(asset => asset.AssetNameEquals(actualKey)); + return this.ContentCore.InvalidateCache(asset => asset.AssetNameEquals(actualKey)); } /// Remove all assets of the given type from the cache so they're reloaded on the next request. This can be a very expensive operation and should only be used in very specific cases. This will reload core game assets if needed, but references to the former assets will still show the previous content. @@ -181,7 +186,7 @@ namespace StardewModdingAPI.Framework.ModHelpers public bool InvalidateCache() { this.Monitor.Log($"Requested cache invalidation for all assets of type {typeof(T)}. This is an expensive operation and should be avoided if possible.", LogLevel.Trace); - return this.ContentManager.InvalidateCache((key, type) => typeof(T).IsAssignableFrom(type)); + return this.ContentCore.InvalidateCache((key, type) => typeof(T).IsAssignableFrom(type)); } /// Remove matching assets from the content cache so they're reloaded on the next request. This will reload core game assets if needed, but references to the former asset will still show the previous content. @@ -190,7 +195,7 @@ namespace StardewModdingAPI.Framework.ModHelpers public bool InvalidateCache(Func predicate) { this.Monitor.Log("Requested cache invalidation for all assets matching a predicate.", LogLevel.Trace); - return this.ContentManager.InvalidateCache(predicate); + return this.ContentCore.InvalidateCache(predicate); } /********* @@ -202,7 +207,7 @@ namespace StardewModdingAPI.Framework.ModHelpers [SuppressMessage("ReSharper", "ParameterOnlyUsedForPreconditionCheck.Local", Justification = "Parameter is only used for assertion checks by design.")] private void AssertValidAssetKeyFormat(string key) { - this.ContentManager.AssertValidAssetKeyFormat(key); + this.ContentCore.AssertValidAssetKeyFormat(key); if (Path.IsPathRooted(key)) throw new ArgumentException("The asset key must not be an absolute path."); } @@ -230,7 +235,7 @@ namespace StardewModdingAPI.Framework.ModHelpers // get map info if (!map.TileSheets.Any()) return; - mapKey = this.ContentManager.NormaliseAssetName(mapKey); // Mono's Path.GetDirectoryName doesn't handle Windows dir separators + mapKey = this.ContentCore.NormaliseAssetName(mapKey); // Mono's Path.GetDirectoryName doesn't handle Windows dir separators string relativeMapFolder = Path.GetDirectoryName(mapKey) ?? ""; // folder path containing the map, relative to the mod folder // fix tilesheets @@ -336,7 +341,7 @@ namespace StardewModdingAPI.Framework.ModHelpers private FileInfo GetModFile(string path) { // try exact match - path = Path.Combine(this.ModFolderPath, this.ContentManager.NormalisePathSeparators(path)); + path = Path.Combine(this.ModFolderPath, this.ContentCore.NormalisePathSeparators(path)); FileInfo file = new FileInfo(path); // try with default extension @@ -355,7 +360,7 @@ namespace StardewModdingAPI.Framework.ModHelpers private FileInfo GetContentFolderFile(string key) { // get file path - string path = Path.Combine(this.ContentManager.FullRootDirectory, key); + string path = Path.Combine(this.ContentCore.FullRootDirectory, key); if (!path.EndsWith(".xnb")) path += ".xnb"; diff --git a/src/SMAPI/Framework/SContentManager.cs b/src/SMAPI/Framework/SContentManager.cs deleted file mode 100644 index 29c6c684..00000000 --- a/src/SMAPI/Framework/SContentManager.cs +++ /dev/null @@ -1,809 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.Contracts; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Threading; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Content; -using Microsoft.Xna.Framework.Graphics; -using StardewModdingAPI.Framework.Content; -using StardewModdingAPI.Framework.Exceptions; -using StardewModdingAPI.Framework.Reflection; -using StardewModdingAPI.Framework.Utilities; -using StardewModdingAPI.Metadata; -using StardewValley; - -namespace StardewModdingAPI.Framework -{ - /// A thread-safe content manager which intercepts assets being loaded to let SMAPI mods inject or edit them. - /// - /// This is the centralised content manager which manages all game assets. The game and mods don't use this class - /// directly; instead they use one of several instances, which proxy requests to - /// this class. That ensures that when the game disposes one content manager, the others can continue unaffected. - /// That notably requires this class to be thread-safe, since the content managers can be disposed asynchronously. - /// - /// Note that assets in the cache have two identifiers: the asset name (like "bundles") and key (like "bundles.pt-BR"). - /// For English and non-translatable assets, these have the same value. The underlying cache only knows about asset - /// keys, and the game and mods only know about asset names. The content manager handles resolving them. - /// - internal class SContentManager : LocalizedContentManager - { - /********* - ** Properties - *********/ - /// Encapsulates monitoring and logging. - private readonly IMonitor Monitor; - - /// The underlying asset cache. - private readonly ContentCache Cache; - - /// The locale codes used in asset keys indexed by enum value. - private readonly IDictionary Locales; - - /// The language enum values indexed by locale code. - private readonly IDictionary LanguageCodes; - - /// Provides metadata for core game assets. - private readonly CoreAssets CoreAssets; - - /// The assets currently being intercepted by instances. This is used to prevent infinite loops when a loader loads a new asset. - private readonly ContextHash AssetsBeingLoaded = new ContextHash(); - - /// A lookup of the content managers which loaded each asset. - private readonly IDictionary> ContentManagersByAssetKey = new Dictionary>(); - - /// The path prefix for assets in mod folders. - private readonly string ModContentPrefix; - - /// A lock used to prevents concurrent changes to the cache while data is being read. - private readonly ReaderWriterLockSlim Lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); - - - /********* - ** Accessors - *********/ - /// Interceptors which provide the initial versions of matching assets. - internal IDictionary> Loaders { get; } = new Dictionary>(); - - /// Interceptors which edit matching assets after they're loaded. - internal IDictionary> Editors { get; } = new Dictionary>(); - - /// The absolute path to the . - internal string FullRootDirectory => Path.Combine(Constants.ExecutionPath, this.RootDirectory); - - - /********* - ** Public methods - *********/ - /**** - ** Constructor - ****/ - /// Construct an instance. - /// The service provider to use to locate services. - /// The root directory to search for content. - /// The current culture for which to localise content. - /// The current language code for which to localise content. - /// Encapsulates monitoring and logging. - /// Simplifies access to private code. - public SContentManager(IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, string languageCodeOverride, IMonitor monitor, Reflector reflection) - : base(serviceProvider, rootDirectory, currentCulture, languageCodeOverride) - { - // init - this.Monitor = monitor ?? throw new ArgumentNullException(nameof(monitor)); - this.Cache = new ContentCache(this, reflection); - this.ModContentPrefix = this.GetAssetNameFromFilePath(Constants.ModPath); - - // get asset data - this.CoreAssets = new CoreAssets(this.NormaliseAssetName, reflection); - this.Locales = this.GetKeyLocales(reflection); - this.LanguageCodes = this.Locales.ToDictionary(p => p.Value, p => p.Key, StringComparer.InvariantCultureIgnoreCase); - } - - /**** - ** Asset key/name handling - ****/ - /// Normalise path separators in a file path. For asset keys, see instead. - /// The file path to normalise. - [Pure] - public string NormalisePathSeparators(string path) - { - return this.Cache.NormalisePathSeparators(path); - } - - /// Normalise an asset name so it's consistent with the underlying cache. - /// The asset key. - [Pure] - public string NormaliseAssetName(string assetName) - { - return this.Cache.NormaliseKey(assetName); - } - - /// Assert that the given key has a valid format. - /// The asset key to check. - /// The asset key is empty or contains invalid characters. - [SuppressMessage("ReSharper", "ParameterOnlyUsedForPreconditionCheck.Local", Justification = "Parameter is only used for assertion checks by design.")] - public void AssertValidAssetKeyFormat(string key) - { - if (string.IsNullOrWhiteSpace(key)) - throw new ArgumentException("The asset key or local path is empty."); - if (key.Intersect(Path.GetInvalidPathChars()).Any()) - throw new ArgumentException("The asset key or local path contains invalid characters."); - } - - /// Convert an absolute file path into a appropriate asset name. - /// The absolute path to the file. - public string GetAssetNameFromFilePath(string absolutePath) - { -#if SMAPI_FOR_WINDOWS - // XNA doesn't allow absolute asset paths, so get a path relative to the content folder - return this.GetRelativePath(absolutePath); -#else - // MonoGame is weird about relative paths on Mac, but allows absolute paths - return absolutePath; -#endif - } - - /**** - ** Content loading - ****/ - /// Get the current content locale. - public string GetLocale() - { - return this.Locales[this.GetCurrentLanguage()]; - } - - /// Get whether the content manager has already loaded and cached the given asset. - /// The asset path relative to the loader root directory, not including the .xnb extension. - public bool IsLoaded(string assetName) - { - assetName = this.Cache.NormaliseKey(assetName); - return this.WithReadLock(() => this.IsNormalisedKeyLoaded(assetName)); - } - - /// Get the cached asset keys. - public IEnumerable GetAssetKeys() - { - return this.WithReadLock(() => - this.Cache.Keys - .Select(this.GetAssetName) - .Distinct() - ); - } - - /// Load an asset through the content pipeline. When loading a .png file, this must be called outside the game's draw loop. - /// The expected asset type. - /// The asset path relative to the content directory. - public override T Load(string assetName) - { - return this.LoadFor(assetName, this); - } - - /// Load an asset through the content pipeline. When loading a .png file, this must be called outside the game's draw loop. - /// The expected asset type. - /// The asset path relative to the content directory. - /// The content manager instance for which to load the asset. - /// The is empty or contains invalid characters. - /// The content asset couldn't be loaded (e.g. because it doesn't exist). - public T LoadFor(string assetName, ContentManager instance) - { - // normalise asset key - this.AssertValidAssetKeyFormat(assetName); - assetName = this.NormaliseAssetName(assetName); - - // load game content - if (!assetName.StartsWith(this.ModContentPrefix)) - return this.LoadImpl(assetName, instance); - - // load mod content - SContentLoadException GetContentError(string reasonPhrase) => new SContentLoadException($"Failed loading content asset '{assetName}': {reasonPhrase}"); - try - { - return this.WithWriteLock(() => - { - // try cache - if (this.IsLoaded(assetName)) - return this.LoadImpl(assetName, instance); - - // get file - FileInfo file = this.GetModFile(assetName); - if (!file.Exists) - throw GetContentError("the specified path doesn't exist."); - - // load content - switch (file.Extension.ToLower()) - { - // XNB file - case ".xnb": - return this.LoadImpl(assetName, instance); - - // unpacked map - case ".tbin": - throw GetContentError($"can't read unpacked map file '{assetName}' directly from the underlying content manager. It must be loaded through the mod's {typeof(IModHelper)}.{nameof(IModHelper.Content)} helper."); - - // unpacked image - case ".png": - // validate - if (typeof(T) != typeof(Texture2D)) - throw GetContentError($"can't read file with extension '{file.Extension}' as type '{typeof(T)}'; must be type '{typeof(Texture2D)}'."); - - // fetch & cache - using (FileStream stream = File.OpenRead(file.FullName)) - { - Texture2D texture = Texture2D.FromStream(Game1.graphics.GraphicsDevice, stream); - texture = this.PremultiplyTransparency(texture); - this.InjectWithoutLock(assetName, texture, instance); - return (T)(object)texture; - } - - default: - throw GetContentError($"unknown file extension '{file.Extension}'; must be one of '.png', '.tbin', or '.xnb'."); - } - }); - } - catch (Exception ex) when (!(ex is SContentLoadException)) - { - if (ex.GetInnermostException() is DllNotFoundException dllEx && dllEx.Message == "libgdiplus.dylib") - throw GetContentError("couldn't find libgdiplus, which is needed to load mod images. Make sure Mono is installed and you're running the game through the normal launcher."); - throw new SContentLoadException($"The content manager failed loading content asset '{assetName}'.", ex); - } - } - - /// Inject an asset into the cache. - /// The type of asset to inject. - /// The asset path relative to the loader root directory, not including the .xnb extension. - /// The asset value. - /// The content manager instance for which to load the asset. - public void Inject(string assetName, T value, ContentManager instance) - { - this.WithWriteLock(() => this.InjectWithoutLock(assetName, value, instance)); - } - - /**** - ** Cache invalidation - ****/ - /// Purge assets from the cache that match one of the interceptors. - /// The asset editors for which to purge matching assets. - /// The asset loaders for which to purge matching assets. - /// Returns whether any cache entries were invalidated. - public bool InvalidateCacheFor(IAssetEditor[] editors, IAssetLoader[] loaders) - { - if (!editors.Any() && !loaders.Any()) - return false; - - // get CanEdit/Load methods - MethodInfo canEdit = typeof(IAssetEditor).GetMethod(nameof(IAssetEditor.CanEdit)); - MethodInfo canLoad = typeof(IAssetLoader).GetMethod(nameof(IAssetLoader.CanLoad)); - if (canEdit == null || canLoad == null) - throw new InvalidOperationException("SMAPI could not access the interceptor methods."); // should never happen - - // invalidate matching keys - return this.InvalidateCache(asset => - { - // check loaders - MethodInfo canLoadGeneric = canLoad.MakeGenericMethod(asset.DataType); - if (loaders.Any(loader => (bool)canLoadGeneric.Invoke(loader, new object[] { asset }))) - return true; - - // check editors - MethodInfo canEditGeneric = canEdit.MakeGenericMethod(asset.DataType); - return editors.Any(editor => (bool)canEditGeneric.Invoke(editor, new object[] { asset })); - }); - } - - /// Purge matched assets from the cache. - /// Matches the asset keys to invalidate. - /// Whether to dispose invalidated assets. This should only be true when they're being invalidated as part of a dispose, to avoid crashing the game. - /// Returns whether any cache entries were invalidated. - public bool InvalidateCache(Func predicate, bool dispose = false) - { - string locale = this.GetLocale(); - return this.InvalidateCache((assetName, type) => - { - IAssetInfo info = new AssetInfo(locale, assetName, type, this.NormaliseAssetName); - return predicate(info); - }); - } - - /// Purge matched assets from the cache. - /// Matches the asset keys to invalidate. - /// Whether to dispose invalidated assets. This should only be true when they're being invalidated as part of a dispose, to avoid crashing the game. - /// Returns whether any cache entries were invalidated. - public bool InvalidateCache(Func predicate, bool dispose = false) - { - return this.WithWriteLock(() => - { - // invalidate matching keys - HashSet removeKeys = new HashSet(StringComparer.InvariantCultureIgnoreCase); - HashSet removeAssetNames = new HashSet(StringComparer.InvariantCultureIgnoreCase); - this.Cache.Remove((key, type) => - { - this.ParseCacheKey(key, out string assetName, out _); - if (removeAssetNames.Contains(assetName) || predicate(assetName, type)) - { - removeAssetNames.Add(assetName); - removeKeys.Add(key); - return true; - } - return false; - }); - - // update reference tracking - foreach (string key in removeKeys) - this.ContentManagersByAssetKey.Remove(key); - - // reload core game assets - int reloaded = 0; - foreach (string key in removeAssetNames) - { - if (this.CoreAssets.ReloadForKey(this, key)) - reloaded++; - } - - // report result - if (removeKeys.Any()) - { - this.Monitor.Log($"Invalidated {removeAssetNames.Count} asset names: {string.Join(", ", removeKeys.OrderBy(p => p, StringComparer.InvariantCultureIgnoreCase))}. Reloaded {reloaded} core assets.", LogLevel.Trace); - return true; - } - this.Monitor.Log("Invalidated 0 cache entries.", LogLevel.Trace); - return false; - }); - } - - /**** - ** Disposal - ****/ - /// Dispose assets for the given content manager shim. - /// The content manager whose assets to dispose. - internal void DisposeFor(ContentManagerShim shim) - { - this.Monitor.Log($"Content manager '{shim.Name}' disposed, disposing assets that aren't needed by any other asset loader.", LogLevel.Trace); - - this.WithWriteLock(() => - { - foreach (var entry in this.ContentManagersByAssetKey) - entry.Value.Remove(shim); - this.InvalidateCache((key, type) => !this.ContentManagersByAssetKey[key].Any(), dispose: true); - }); - } - - - /********* - ** Private methods - *********/ - /**** - ** Disposal - ****/ - /// Dispose held resources. - /// Whether the content manager is disposing (rather than finalising). - protected override void Dispose(bool disposing) - { - this.Monitor.Log("Disposing SMAPI's main content manager. It will no longer be usable after this point.", LogLevel.Trace); - base.Dispose(disposing); - } - - /**** - ** Asset name/key handling - ****/ - /// Get a directory or file path relative to the content root. - /// The target file path. - private string GetRelativePath(string targetPath) - { - return PathUtilities.GetRelativePath(this.FullRootDirectory, targetPath); - } - - /// Get the locale codes (like ja-JP) used in asset keys. - /// Simplifies access to private game code. - private IDictionary GetKeyLocales(Reflector reflection) - { -#if !STARDEW_VALLEY_1_3 - IReflectedField codeField = reflection.GetField(typeof(LocalizedContentManager), "_currentLangCode"); - LanguageCode previousCode = codeField.GetValue(); -#endif - string previousOverride = this.LanguageCodeOverride; - - try - { - // temporarily disable language override - this.LanguageCodeOverride = null; - - // create locale => code map - IReflectedMethod languageCodeString = reflection -#if STARDEW_VALLEY_1_3 - .GetMethod(this, "languageCodeString"); -#else - .GetMethod(this, "languageCode"); -#endif - IDictionary map = new Dictionary(); - foreach (LanguageCode code in Enum.GetValues(typeof(LanguageCode))) - { -#if STARDEW_VALLEY_1_3 - map[code] = languageCodeString.Invoke(code); -#else - codeField.SetValue(code); - map[code] = languageCodeString.Invoke(); -#endif - } - - return map; - } - finally - { - // restore previous settings - this.LanguageCodeOverride = previousOverride; -#if !STARDEW_VALLEY_1_3 - codeField.SetValue(previousCode); -#endif - - } - } - - /// Get the asset name from a cache key. - /// The input cache key. - private string GetAssetName(string cacheKey) - { - this.ParseCacheKey(cacheKey, out string assetName, out string _); - return assetName; - } - - /// Parse a cache key into its component parts. - /// The input cache key. - /// The original asset name. - /// The asset locale code (or null if not localised). - private void ParseCacheKey(string cacheKey, out string assetName, out string localeCode) - { - // handle localised key - if (!string.IsNullOrWhiteSpace(cacheKey)) - { - int lastSepIndex = cacheKey.LastIndexOf(".", StringComparison.InvariantCulture); - if (lastSepIndex >= 0) - { - string suffix = cacheKey.Substring(lastSepIndex + 1, cacheKey.Length - lastSepIndex - 1); - if (this.LanguageCodes.ContainsKey(suffix)) - { - assetName = cacheKey.Substring(0, lastSepIndex); - localeCode = cacheKey.Substring(lastSepIndex + 1, cacheKey.Length - lastSepIndex - 1); - return; - } - } - } - - // handle simple key - assetName = cacheKey; - localeCode = null; - } - - /**** - ** Cache handling - ****/ - /// Get whether an asset has already been loaded. - /// The normalised asset name. - private bool IsNormalisedKeyLoaded(string normalisedAssetName) - { - return this.Cache.ContainsKey(normalisedAssetName) - || this.Cache.ContainsKey($"{normalisedAssetName}.{this.Locales[this.GetCurrentLanguage()]}"); // translated asset - } - - /// Track that a content manager loaded an asset. - /// The asset key that was loaded. - /// The content manager that loaded the asset. - private void TrackAssetLoader(string key, ContentManager manager) - { - if (!this.ContentManagersByAssetKey.TryGetValue(key, out HashSet hash)) - hash = this.ContentManagersByAssetKey[key] = new HashSet(); - hash.Add(manager); - } - - /**** - ** Content loading - ****/ - /// Load an asset name without heuristics to support mod content. - /// The type of asset to load. - /// The asset path relative to the loader root directory, not including the .xnb extension. - /// The content manager instance for which to load the asset. - private T LoadImpl(string assetName, ContentManager instance) - { - return this.WithWriteLock(() => - { - // skip if already loaded - if (this.IsNormalisedKeyLoaded(assetName)) - { - this.TrackAssetLoader(assetName, instance); - return base.Load(assetName); - } - - // load asset - T data; - if (this.AssetsBeingLoaded.Contains(assetName)) - { - this.Monitor.Log($"Broke loop while loading asset '{assetName}'.", LogLevel.Warn); - this.Monitor.Log($"Bypassing mod loaders for this asset. Stack trace:\n{Environment.StackTrace}", LogLevel.Trace); - data = base.Load(assetName); - } - else - { - data = this.AssetsBeingLoaded.Track(assetName, () => - { - IAssetInfo info = new AssetInfo(this.GetLocale(), assetName, typeof(T), this.NormaliseAssetName); - IAssetData asset = this.ApplyLoader(info) ?? new AssetDataForObject(info, base.Load(assetName), this.NormaliseAssetName); - asset = this.ApplyEditors(info, asset); - return (T)asset.Data; - }); - } - - // update cache & return data - this.InjectWithoutLock(assetName, data, instance); - return data; - }); - } - - /// Inject an asset into the cache without acquiring a write lock. This should only be called from within a write lock. - /// The type of asset to inject. - /// The asset path relative to the loader root directory, not including the .xnb extension. - /// The asset value. - /// The content manager instance for which to load the asset. - private void InjectWithoutLock(string assetName, T value, ContentManager instance) - { - assetName = this.NormaliseAssetName(assetName); - this.Cache[assetName] = value; - this.TrackAssetLoader(assetName, instance); - } - - /// Get a file from the mod folder. - /// The asset path relative to the content folder. - private FileInfo GetModFile(string path) - { - // try exact match - FileInfo file = new FileInfo(Path.Combine(this.FullRootDirectory, path)); - - // try with default extension - if (!file.Exists && file.Extension.ToLower() != ".xnb") - { - FileInfo result = new FileInfo(file.FullName + ".xnb"); - if (result.Exists) - file = result; - } - - return file; - } - - /// Load the initial asset from the registered . - /// The basic asset metadata. - /// Returns the loaded asset metadata, or null if no loader matched. - private IAssetData ApplyLoader(IAssetInfo info) - { - // find matching loaders - var loaders = this.GetInterceptors(this.Loaders) - .Where(entry => - { - try - { - return entry.Value.CanLoad(info); - } - catch (Exception ex) - { - entry.Key.LogAsMod($"Mod failed when checking whether it could load asset '{info.AssetName}', and will be ignored. Error details:\n{ex.GetLogSummary()}", LogLevel.Error); - return false; - } - }) - .ToArray(); - - // validate loaders - if (!loaders.Any()) - return null; - if (loaders.Length > 1) - { - string[] loaderNames = loaders.Select(p => p.Key.DisplayName).ToArray(); - this.Monitor.Log($"Multiple mods want to provide the '{info.AssetName}' asset ({string.Join(", ", loaderNames)}), but an asset can't be loaded multiple times. SMAPI will use the default asset instead; uninstall one of the mods to fix this. (Message for modders: you should usually use {typeof(IAssetEditor)} instead to avoid conflicts.)", LogLevel.Warn); - return null; - } - - // fetch asset from loader - IModMetadata mod = loaders[0].Key; - IAssetLoader loader = loaders[0].Value; - T data; - try - { - data = loader.Load(info); - this.Monitor.Log($"{mod.DisplayName} loaded asset '{info.AssetName}'.", LogLevel.Trace); - } - catch (Exception ex) - { - mod.LogAsMod($"Mod crashed when loading asset '{info.AssetName}'. SMAPI will use the default asset instead. Error details:\n{ex.GetLogSummary()}", LogLevel.Error); - 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.NormaliseAssetName); - } - - /// Apply any to a loaded asset. - /// The asset type. - /// The basic asset metadata. - /// The loaded asset. - private IAssetData ApplyEditors(IAssetInfo info, IAssetData asset) - { - IAssetData GetNewData(object data) => new AssetDataForObject(info, data, this.NormaliseAssetName); - - // edit asset - foreach (var entry in this.GetInterceptors(this.Editors)) - { - // check for match - IModMetadata mod = entry.Key; - IAssetEditor editor = entry.Value; - try - { - if (!editor.CanEdit(info)) - continue; - } - catch (Exception ex) - { - mod.LogAsMod($"Mod crashed when checking whether it could edit asset '{info.AssetName}', and will be ignored. Error details:\n{ex.GetLogSummary()}", LogLevel.Error); - continue; - } - - // try edit - object prevAsset = asset.Data; - try - { - editor.Edit(asset); - this.Monitor.Log($"{mod.DisplayName} intercepted {info.AssetName}.", LogLevel.Trace); - } - catch (Exception ex) - { - mod.LogAsMod($"Mod crashed when editing asset '{info.AssetName}', which may cause errors in-game. Error details:\n{ex.GetLogSummary()}", LogLevel.Error); - } - - // validate edit - if (asset.Data == null) - { - mod.LogAsMod($"Mod incorrectly set asset '{info.AssetName}' to a null value; ignoring override.", LogLevel.Warn); - asset = GetNewData(prevAsset); - } - else if (!(asset.Data is T)) - { - mod.LogAsMod($"Mod incorrectly set asset '{asset.AssetName}' to incompatible type '{asset.Data.GetType()}', expected '{typeof(T)}'; ignoring override.", LogLevel.Warn); - asset = GetNewData(prevAsset); - } - } - - // return result - return asset; - } - - /// Get all registered interceptors from a list. - private IEnumerable> GetInterceptors(IDictionary> entries) - { - foreach (var entry in entries) - { - IModMetadata mod = entry.Key; - IList interceptors = entry.Value; - - // registered editors - foreach (T interceptor in interceptors) - yield return new KeyValuePair(mod, interceptor); - } - } - - /// Premultiply a texture's alpha values to avoid transparency issues in the game. This is only possible if the game isn't currently drawing. - /// The texture to premultiply. - /// Returns a premultiplied texture. - /// Based on code by Layoric. - private Texture2D PremultiplyTransparency(Texture2D texture) - { - // validate - if (Context.IsInDrawLoop) - throw new NotSupportedException("Can't load a PNG file while the game is drawing to the screen. Make sure you load content outside the draw loop."); - - // process texture - SpriteBatch spriteBatch = Game1.spriteBatch; - GraphicsDevice gpu = Game1.graphics.GraphicsDevice; - using (RenderTarget2D renderTarget = new RenderTarget2D(Game1.graphics.GraphicsDevice, texture.Width, texture.Height)) - { - // create blank render target to premultiply - gpu.SetRenderTarget(renderTarget); - gpu.Clear(Color.Black); - - // multiply each color by the source alpha, and write just the color values into the final texture - spriteBatch.Begin(SpriteSortMode.Immediate, new BlendState - { - ColorDestinationBlend = Blend.Zero, - ColorWriteChannels = ColorWriteChannels.Red | ColorWriteChannels.Green | ColorWriteChannels.Blue, - AlphaDestinationBlend = Blend.Zero, - AlphaSourceBlend = Blend.SourceAlpha, - ColorSourceBlend = Blend.SourceAlpha - }); - spriteBatch.Draw(texture, texture.Bounds, Color.White); - spriteBatch.End(); - - // copy the alpha values from the source texture into the final one without multiplying them - spriteBatch.Begin(SpriteSortMode.Immediate, new BlendState - { - ColorWriteChannels = ColorWriteChannels.Alpha, - AlphaDestinationBlend = Blend.Zero, - ColorDestinationBlend = Blend.Zero, - AlphaSourceBlend = Blend.One, - ColorSourceBlend = Blend.One - }); - spriteBatch.Draw(texture, texture.Bounds, Color.White); - spriteBatch.End(); - - // release GPU - gpu.SetRenderTarget(null); - - // extract premultiplied data - Color[] data = new Color[texture.Width * texture.Height]; - renderTarget.GetData(data); - - // unset texture from GPU to regain control - gpu.Textures[0] = null; - - // update texture with premultiplied data - texture.SetData(data); - } - - return texture; - } - - /**** - ** Concurrency logic - ****/ - /// Acquire a read lock which prevents concurrent writes to the cache while it's open. - /// The action's return value. - /// The action to perform. - private T WithReadLock(Func action) - { - try - { - this.Lock.EnterReadLock(); - return action(); - } - finally - { - this.Lock.ExitReadLock(); - } - } - - /// Acquire a write lock which prevents concurrent reads or writes to the cache while it's open. - /// The action to perform. - private void WithWriteLock(Action action) - { - try - { - this.Lock.EnterWriteLock(); - action(); - } - finally - { - this.Lock.ExitWriteLock(); - } - } - - /// Acquire a write lock which prevents concurrent reads or writes to the cache while it's open. - /// The action's return value. - /// The action to perform. - private T WithWriteLock(Func action) - { - try - { - this.Lock.EnterWriteLock(); - return action(); - } - finally - { - this.Lock.ExitWriteLock(); - } - } - } -} diff --git a/src/SMAPI/Framework/SGame.cs b/src/SMAPI/Framework/SGame.cs index acb3e794..aeaab9ea 100644 --- a/src/SMAPI/Framework/SGame.cs +++ b/src/SMAPI/Framework/SGame.cs @@ -161,7 +161,7 @@ namespace StardewModdingAPI.Framework ** Accessors *********/ /// SMAPI's content manager. - public SContentManager SContentManager { get; } + public ContentCore ContentCore { get; } /// Whether SMAPI should log more information about the game context. public bool VerboseLogging { get; set; } @@ -190,10 +190,12 @@ namespace StardewModdingAPI.Framework // override content manager this.Monitor?.Log("Overriding content manager...", LogLevel.Trace); - this.SContentManager = new SContentManager(this.Content.ServiceProvider, this.Content.RootDirectory, Thread.CurrentThread.CurrentUICulture, null, this.Monitor, reflection); - this.Content = new ContentManagerShim(this.SContentManager, "SGame.Content"); - Game1.content = new ContentManagerShim(this.SContentManager, "Game1.content"); - reflection.GetField(typeof(Game1), "_temporaryContent").SetValue(new ContentManagerShim(this.SContentManager, "Game1._temporaryContent")); // regenerate value with new content manager + this.ContentCore = new ContentCore(this.Content.ServiceProvider, this.Content.RootDirectory, Thread.CurrentThread.CurrentUICulture, null, this.Monitor, reflection); + this.Content = this.ContentCore.CreateContentManager("SGame.Content"); + Game1.content = this.ContentCore.CreateContentManager("Game1.content"); + + // replace already-created temporary content managers + reflection.GetField(typeof(Game1), "_temporaryContent").SetValue(this.ContentCore.CreateContentManager("Game1._temporaryContent")); // regenerate value with new content manager } /**** @@ -205,7 +207,7 @@ namespace StardewModdingAPI.Framework protected override LocalizedContentManager CreateContentManager(IServiceProvider serviceProvider, string rootDirectory) { // return default if SMAPI's content manager isn't initialised yet - if (this.SContentManager == null) + if (this.ContentCore == null) { this.Monitor?.Log("SMAPI's content manager isn't initialised; skipping content manager interception.", LogLevel.Trace); return base.CreateContentManager(serviceProvider, rootDirectory); @@ -216,7 +218,7 @@ namespace StardewModdingAPI.Framework throw new InvalidOperationException("SMAPI uses a single content manager internally. You can't get a new content manager with a different service provider."); if (rootDirectory != this.Content.RootDirectory) throw new InvalidOperationException($"SMAPI uses a single content manager internally. You can't get a new content manager with a different root directory (current is {this.Content.RootDirectory}, requested {rootDirectory})."); - return new ContentManagerShim(this.SContentManager, "(generated instance)"); + return this.ContentCore.CreateContentManager("(generated instance)"); } /// The method called when the game is updating its state. This happens roughly 60 times per second. diff --git a/src/SMAPI/Metadata/CoreAssets.cs b/src/SMAPI/Metadata/CoreAssets.cs index c027df25..378117a8 100644 --- a/src/SMAPI/Metadata/CoreAssets.cs +++ b/src/SMAPI/Metadata/CoreAssets.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework.Graphics; -using StardewModdingAPI.Framework; using StardewModdingAPI.Framework.Reflection; using StardewValley; using StardewValley.BellsAndWhistles; @@ -24,7 +23,7 @@ namespace StardewModdingAPI.Metadata protected readonly Func GetNormalisedPath; /// Setters which update static or singleton texture fields indexed by normalised asset key. - private readonly IDictionary> SingletonSetters; + private readonly IDictionary> SingletonSetters; /********* @@ -37,7 +36,7 @@ namespace StardewModdingAPI.Metadata { this.GetNormalisedPath = getNormalisedPath; this.SingletonSetters = - new Dictionary> + new Dictionary> { // from CraftingRecipe.InitShared ["Data\\CraftingRecipes"] = (content, key) => CraftingRecipe.craftingRecipes = content.Load>(key), @@ -151,10 +150,10 @@ namespace StardewModdingAPI.Metadata /// The content manager through which to reload the asset. /// The asset key to reload. /// Returns whether an asset was reloaded. - public bool ReloadForKey(SContentManager content, string key) + public bool ReloadForKey(LocalizedContentManager content, string key) { // static assets - if (this.SingletonSetters.TryGetValue(key, out Action reload)) + if (this.SingletonSetters.TryGetValue(key, out Action reload)) { reload(content, key); return true; diff --git a/src/SMAPI/Program.cs b/src/SMAPI/Program.cs index 9c00e581..39a5754b 100644 --- a/src/SMAPI/Program.cs +++ b/src/SMAPI/Program.cs @@ -58,7 +58,7 @@ namespace StardewModdingAPI private SGame GameInstance; /// The underlying content manager. - private SContentManager ContentManager => this.GameInstance.SContentManager; + private ContentCore ContentCore => this.GameInstance.ContentCore; /// The SMAPI configuration settings. /// This is initialised after the game starts. @@ -286,10 +286,11 @@ namespace StardewModdingAPI // dispose core components this.IsGameRunning = false; - this.LogFile?.Dispose(); this.ConsoleManager?.Dispose(); + this.ContentCore?.Dispose(); this.CancellationTokenSource?.Dispose(); this.GameInstance?.Dispose(); + this.LogFile?.Dispose(); } @@ -389,7 +390,7 @@ namespace StardewModdingAPI mods = resolver.ProcessDependencies(mods, modDatabase).ToArray(); // load mods - this.LoadMods(mods, this.JsonHelper, this.ContentManager, modDatabase); + this.LoadMods(mods, this.JsonHelper, this.ContentCore, modDatabase); // check for updates this.CheckForUpdatesAsync(mods); @@ -413,8 +414,8 @@ namespace StardewModdingAPI private void OnLocaleChanged() { // get locale - string locale = this.ContentManager.GetLocale(); - LocalizedContentManager.LanguageCode languageCode = this.ContentManager.GetCurrentLanguage(); + string locale = this.ContentCore.GetLocale(); + LocalizedContentManager.LanguageCode languageCode = this.ContentCore.Language; // update mod translation helpers foreach (IModMetadata mod in this.ModRegistry.GetAll(contentPacks: false)) @@ -671,9 +672,9 @@ namespace StardewModdingAPI /// Load and hook up the given mods. /// The mods to load. /// The JSON helper with which to read mods' JSON files. - /// The content manager to use for mod content. + /// The content manager to use for mod content. /// Handles access to SMAPI's internal mod metadata list. - private void LoadMods(IModMetadata[] mods, JsonHelper jsonHelper, SContentManager contentManager, ModDatabase modDatabase) + private void LoadMods(IModMetadata[] mods, JsonHelper jsonHelper, ContentCore contentCore, ModDatabase modDatabase) { this.Monitor.Log("Loading mods...", LogLevel.Trace); @@ -697,7 +698,8 @@ namespace StardewModdingAPI // load mod as content pack IMonitor monitor = this.GetSecondaryMonitor(metadata.DisplayName); - IContentHelper contentHelper = new ContentHelper(contentManager, metadata.DirectoryPath, manifest.UniqueID, metadata.DisplayName, monitor); + ContentManagerShim contentManager = this.ContentCore.CreateContentManager($"Mods.{metadata.Manifest.UniqueID}", metadata.DirectoryPath); + IContentHelper contentHelper = new ContentHelper(this.ContentCore, contentManager, metadata.DirectoryPath, manifest.UniqueID, metadata.DisplayName, monitor); IContentPack contentPack = new ContentPack(metadata.DirectoryPath, manifest, contentHelper, jsonHelper); metadata.SetMod(contentPack, monitor); this.ModRegistry.Add(metadata); @@ -777,15 +779,17 @@ namespace StardewModdingAPI IModHelper modHelper; { ICommandHelper commandHelper = new CommandHelper(manifest.UniqueID, metadata.DisplayName, this.CommandManager); - IContentHelper contentHelper = new ContentHelper(contentManager, metadata.DirectoryPath, manifest.UniqueID, metadata.DisplayName, monitor); + ContentManagerShim contentManager = this.ContentCore.CreateContentManager($"Mods.{metadata.Manifest.UniqueID}", metadata.DirectoryPath); + IContentHelper contentHelper = new ContentHelper(contentCore, contentManager, metadata.DirectoryPath, manifest.UniqueID, metadata.DisplayName, monitor); IReflectionHelper reflectionHelper = new ReflectionHelper(manifest.UniqueID, metadata.DisplayName, this.Reflection, this.DeprecationManager); IModRegistry modRegistryHelper = new ModRegistryHelper(manifest.UniqueID, this.ModRegistry, proxyFactory, monitor); - ITranslationHelper translationHelper = new TranslationHelper(manifest.UniqueID, manifest.Name, contentManager.GetLocale(), contentManager.GetCurrentLanguage()); + ITranslationHelper translationHelper = new TranslationHelper(manifest.UniqueID, manifest.Name, contentCore.GetLocale(), contentCore.Language); IContentPack CreateTransitionalContentPack(string packDirPath, IManifest packManifest) { IMonitor packMonitor = this.GetSecondaryMonitor(packManifest.Name); - IContentHelper packContentHelper = new ContentHelper(contentManager, packDirPath, packManifest.UniqueID, packManifest.Name, packMonitor); + ContentManagerShim packContentManager = this.ContentCore.CreateContentManager($"Mods.{packManifest.UniqueID}", packDirPath); + IContentHelper packContentHelper = new ContentHelper(contentCore, packContentManager, packDirPath, packManifest.UniqueID, packManifest.Name, packMonitor); return new ContentPack(packDirPath, packManifest, packContentHelper, this.JsonHelper); } @@ -881,8 +885,8 @@ namespace StardewModdingAPI helper.ObservableAssetLoaders.Add(loader); // ReSharper restore SuspiciousTypeConversion.Global - this.ContentManager.Editors[metadata] = helper.ObservableAssetEditors; - this.ContentManager.Loaders[metadata] = helper.ObservableAssetLoaders; + this.ContentCore.Editors[metadata] = helper.ObservableAssetEditors; + this.ContentCore.Loaders[metadata] = helper.ObservableAssetLoaders; } // call entry method @@ -927,7 +931,7 @@ namespace StardewModdingAPI if (e.NewItems.Count > 0) { this.Monitor.Log("Invalidating cache entries for new asset editors...", LogLevel.Trace); - this.ContentManager.InvalidateCacheFor(e.NewItems.Cast().ToArray(), new IAssetLoader[0]); + this.ContentCore.InvalidateCacheFor(e.NewItems.Cast().ToArray(), new IAssetLoader[0]); } }; helper.ObservableAssetLoaders.CollectionChanged += (sender, e) => @@ -935,7 +939,7 @@ namespace StardewModdingAPI if (e.NewItems.Count > 0) { this.Monitor.Log("Invalidating cache entries for new asset loaders...", LogLevel.Trace); - this.ContentManager.InvalidateCacheFor(new IAssetEditor[0], e.NewItems.Cast().ToArray()); + this.ContentCore.InvalidateCacheFor(new IAssetEditor[0], e.NewItems.Cast().ToArray()); } }; } @@ -947,7 +951,7 @@ namespace StardewModdingAPI if (editors.Any() || loaders.Any()) { this.Monitor.Log("Invalidating cached assets for new editors & loaders...", LogLevel.Trace); - this.ContentManager.InvalidateCacheFor(editors, loaders); + this.ContentCore.InvalidateCacheFor(editors, loaders); } // unlock mod integrations diff --git a/src/SMAPI/StardewModdingAPI.csproj b/src/SMAPI/StardewModdingAPI.csproj index 1dc7740e..bffb96e2 100644 --- a/src/SMAPI/StardewModdingAPI.csproj +++ b/src/SMAPI/StardewModdingAPI.csproj @@ -196,7 +196,7 @@ - + -- cgit From 588d4d94fa63198fec2a7b861ecea17cf2085cee Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 11 Mar 2018 20:30:57 -0400 Subject: fix some content managers not replaced early enough (#453, #413) --- src/SMAPI/Framework/SGame.cs | 39 ++++++++++++++++++++++----------------- src/SMAPI/Program.cs | 2 ++ 2 files changed, 24 insertions(+), 17 deletions(-) (limited to 'src/SMAPI/Program.cs') diff --git a/src/SMAPI/Framework/SGame.cs b/src/SMAPI/Framework/SGame.cs index aeaab9ea..47bc40e6 100644 --- a/src/SMAPI/Framework/SGame.cs +++ b/src/SMAPI/Framework/SGame.cs @@ -25,7 +25,7 @@ using StardewValley.Tools; using xTile.Dimensions; #if !STARDEW_VALLEY_1_3 using xTile.Layers; - #endif +#endif namespace StardewModdingAPI.Framework { @@ -35,6 +35,16 @@ namespace StardewModdingAPI.Framework /********* ** Properties *********/ + /**** + ** Constructor hack + ****/ + /// A static instance of to use while is initialising, which happens before the constructor runs. + internal static IMonitor MonitorDuringInitialisation; + + /// A static instance of to use while is initialising, which happens before the constructor runs. + internal static Reflector ReflectorDuringInitialisation; + + /**** ** SMAPI state ****/ @@ -161,7 +171,7 @@ namespace StardewModdingAPI.Framework ** Accessors *********/ /// SMAPI's content manager. - public ContentCore ContentCore { get; } + public ContentCore ContentCore { get; private set; } /// Whether SMAPI should log more information about the game context. public bool VerboseLogging { get; set; } @@ -184,18 +194,18 @@ namespace StardewModdingAPI.Framework SGame.Instance = this; SGame.Reflection = reflection; this.OnGameInitialised = onGameInitialised; + if (this.ContentCore == null) // shouldn't happen since CreateContentManager is called first, but let's init here just in case + this.ContentCore = new ContentCore(this.Content.ServiceProvider, this.Content.RootDirectory, Thread.CurrentThread.CurrentUICulture, null, this.Monitor, reflection); // set XNA option required by Stardew Valley Game1.graphics.GraphicsProfile = GraphicsProfile.HiDef; - // override content manager +#if !STARDEW_VALLEY_1_3 + // replace already-created content managers this.Monitor?.Log("Overriding content manager...", LogLevel.Trace); - this.ContentCore = new ContentCore(this.Content.ServiceProvider, this.Content.RootDirectory, Thread.CurrentThread.CurrentUICulture, null, this.Monitor, reflection); this.Content = this.ContentCore.CreateContentManager("SGame.Content"); - Game1.content = this.ContentCore.CreateContentManager("Game1.content"); - - // replace already-created temporary content managers reflection.GetField(typeof(Game1), "_temporaryContent").SetValue(this.ContentCore.CreateContentManager("Game1._temporaryContent")); // regenerate value with new content manager +#endif } /**** @@ -206,19 +216,14 @@ namespace StardewModdingAPI.Framework /// The root directory to search for content. protected override LocalizedContentManager CreateContentManager(IServiceProvider serviceProvider, string rootDirectory) { - // return default if SMAPI's content manager isn't initialised yet + // NOTE: this method is called from the Game1 constructor, before the SGame constructor runs. + // Don't depend on anything being initialised at this point. if (this.ContentCore == null) { - this.Monitor?.Log("SMAPI's content manager isn't initialised; skipping content manager interception.", LogLevel.Trace); - return base.CreateContentManager(serviceProvider, rootDirectory); + this.ContentCore = new ContentCore(serviceProvider, rootDirectory, Thread.CurrentThread.CurrentUICulture, null, SGame.MonitorDuringInitialisation, SGame.ReflectorDuringInitialisation); + SGame.MonitorDuringInitialisation = null; } - - // return single instance if valid - if (serviceProvider != this.Content.ServiceProvider) - throw new InvalidOperationException("SMAPI uses a single content manager internally. You can't get a new content manager with a different service provider."); - if (rootDirectory != this.Content.RootDirectory) - throw new InvalidOperationException($"SMAPI uses a single content manager internally. You can't get a new content manager with a different root directory (current is {this.Content.RootDirectory}, requested {rootDirectory})."); - return this.ContentCore.CreateContentManager("(generated instance)"); + return this.ContentCore.CreateContentManager("(generated)", rootDirectory); } /// The method called when the game is updating its state. This happens roughly 60 times per second. diff --git a/src/SMAPI/Program.cs b/src/SMAPI/Program.cs index 39a5754b..e713add5 100644 --- a/src/SMAPI/Program.cs +++ b/src/SMAPI/Program.cs @@ -190,6 +190,8 @@ namespace StardewModdingAPI AppDomain.CurrentDomain.UnhandledException += (sender, e) => this.Monitor.Log($"Critical app domain exception: {e.ExceptionObject}", LogLevel.Error); // override game + SGame.MonitorDuringInitialisation = this.Monitor; + SGame.ReflectorDuringInitialisation = this.Reflection; this.GameInstance = new SGame(this.Monitor, this.Reflection, this.EventManager, this.InitialiseAfterGameStart); StardewValley.Program.gamePtr = this.GameInstance; -- cgit From f0e1a46f0fa52b4365c8ccb64c7fe4784002257b Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 11 Mar 2018 21:07:45 -0400 Subject: fix error when content pack needs a mod that couldn't be loaded --- docs/release-notes.md | 1 + src/SMAPI/Program.cs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) (limited to 'src/SMAPI/Program.cs') diff --git a/docs/release-notes.md b/docs/release-notes.md index 7297fb59..1e32eb8d 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -14,6 +14,7 @@ * Fixed rare crash with some combinations of manifest fields and internal mod data. * Fixed update checks failing for Nexus Mods due to a change in their API. * Fixed update checks failing for some older mods with non-standard versions. + * Fixed error when a content pack needs a mod that couldn't be loaded. * Updated compatibility list and added update checks for more mods. * For the [log parser][]: diff --git a/src/SMAPI/Program.cs b/src/SMAPI/Program.cs index e713add5..4bd40710 100644 --- a/src/SMAPI/Program.cs +++ b/src/SMAPI/Program.cs @@ -854,7 +854,7 @@ namespace StardewModdingAPI // log loaded content packs if (loadedContentPacks.Any()) { - string GetModDisplayName(string id) => loadedMods.First(p => id != null && id.Equals(p.Manifest?.UniqueID, StringComparison.InvariantCultureIgnoreCase))?.DisplayName; + string GetModDisplayName(string id) => loadedMods.FirstOrDefault(p => id != null && id.Equals(p.Manifest?.UniqueID, StringComparison.InvariantCultureIgnoreCase))?.DisplayName; this.Monitor.Log($"Loaded {loadedContentPacks.Length} content packs:", LogLevel.Info); foreach (IModMetadata metadata in loadedContentPacks.OrderBy(p => p.DisplayName)) -- cgit