From 9b615fadaa3bb8fbf4fe011320aa1cc709113f3f Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 29 Apr 2017 14:13:55 -0400 Subject: add initial content API (#257) --- src/StardewModdingAPI/Framework/SContentManager.cs | 33 ++++++++++++++++++++-- 1 file changed, 30 insertions(+), 3 deletions(-) (limited to 'src/StardewModdingAPI/Framework/SContentManager.cs') diff --git a/src/StardewModdingAPI/Framework/SContentManager.cs b/src/StardewModdingAPI/Framework/SContentManager.cs index ef5855b2..e363e6b4 100644 --- a/src/StardewModdingAPI/Framework/SContentManager.cs +++ b/src/StardewModdingAPI/Framework/SContentManager.cs @@ -5,6 +5,7 @@ using System.IO; using System.Linq; using System.Threading; using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Content; using StardewModdingAPI.AssemblyRewriters; using StardewModdingAPI.Events; using StardewModdingAPI.Framework.Content; @@ -17,7 +18,7 @@ namespace StardewModdingAPI.Framework internal class SContentManager : LocalizedContentManager { /********* - ** Accessors + ** Properties *********/ /// The possible directory separator characters in an asset key. private static readonly char[] PossiblePathSeparators = new[] { '/', '\\', Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }.Distinct().ToArray(); @@ -38,6 +39,13 @@ namespace StardewModdingAPI.Framework private readonly IPrivateMethod GetKeyLocale; + /********* + ** Accessors + *********/ + /// The absolute path to the . + public string FullRootDirectory => Path.Combine(Constants.ExecutionPath, this.RootDirectory); + + /********* ** Public methods *********/ @@ -85,7 +93,7 @@ namespace StardewModdingAPI.Framework string cacheLocale = this.GetCacheLocale(assetName); // skip if already loaded - if (this.IsLoaded(assetName)) + if (this.IsNormalisedKeyLoaded(assetName)) return base.Load(assetName); // load data @@ -98,6 +106,25 @@ namespace StardewModdingAPI.Framework return (T)helper.Data; } + /// 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) + { + assetName = this.NormaliseAssetName(assetName); + this.Cache[assetName] = value; + } + + /// 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.NormaliseAssetName(assetName); + return this.IsNormalisedKeyLoaded(assetName); + + } + /********* ** Private methods @@ -116,7 +143,7 @@ namespace StardewModdingAPI.Framework /// Get whether an asset has already been loaded. /// The normalised asset name. - private bool IsLoaded(string normalisedAssetName) + private bool IsNormalisedKeyLoaded(string normalisedAssetName) { return this.Cache.ContainsKey(normalisedAssetName) || this.Cache.ContainsKey($"{normalisedAssetName}.{this.GetKeyLocale.Invoke()}"); // translated asset -- cgit From 3cfe14d27946518c1cd631607f878f7d2f4a2cdb Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 29 Apr 2017 22:44:57 -0400 Subject: add contentHelper.GetActualAssetKey(..) to support custom map tilesheets (#257) --- src/StardewModdingAPI/Framework/ContentHelper.cs | 65 +++++++++++++++------- src/StardewModdingAPI/Framework/SContentManager.cs | 42 +++++++------- src/StardewModdingAPI/IContentHelper.cs | 6 ++ 3 files changed, 72 insertions(+), 41 deletions(-) (limited to 'src/StardewModdingAPI/Framework/SContentManager.cs') diff --git a/src/StardewModdingAPI/Framework/ContentHelper.cs b/src/StardewModdingAPI/Framework/ContentHelper.cs index 04317a84..4d116b54 100644 --- a/src/StardewModdingAPI/Framework/ContentHelper.cs +++ b/src/StardewModdingAPI/Framework/ContentHelper.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using Microsoft.Xna.Framework; @@ -21,7 +22,7 @@ namespace StardewModdingAPI.Framework private readonly string ModFolderPath; /// The path to the mod's folder, relative to the game's content folder (e.g. "../Mods/ModName"). - private readonly string RelativeContentFolder; + private readonly string ModFolderPathFromContent; /// The friendly mod name for use in errors. private readonly string ModName; @@ -39,7 +40,7 @@ namespace StardewModdingAPI.Framework this.ContentManager = contentManager; this.ModFolderPath = modFolderPath; this.ModName = modName; - this.RelativeContentFolder = this.GetRelativePath(contentManager.FullRootDirectory, modFolderPath); + this.ModFolderPathFromContent = this.GetRelativePath(contentManager.FullRootDirectory, modFolderPath); } /// Load content from the game folder or mod folder (if not already cached), and return it. When loading a .png file, this must be called outside the game's draw loop. @@ -50,13 +51,7 @@ namespace StardewModdingAPI.Framework /// The content asset couldn't be loaded (e.g. because it doesn't exist). public T Load(string key, ContentSource source) { - // validate - 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."); - - // load content + this.AssertValidAssetKeyFormat(key); try { switch (source) @@ -72,16 +67,14 @@ namespace StardewModdingAPI.Framework if (!file.Exists) throw new ContentLoadException($"There is no file at path '{file.FullName}'."); - // get content-relative path - string contentPath = Path.Combine(this.RelativeContentFolder, key); - if (contentPath.EndsWith(".xnb")) - contentPath = contentPath.Substring(0, contentPath.Length - 4); + // get underlying asset key + string actualKey = this.GetActualAssetKey(key, source); // load content switch (file.Extension.ToLower()) { case ".xnb": - return this.ContentManager.Load(contentPath); + return this.ContentManager.Load(actualKey); case ".png": // validate @@ -89,15 +82,15 @@ namespace StardewModdingAPI.Framework throw new ContentLoadException($"Can't read file with extension '{file.Extension}' as type '{typeof(T)}'; must be type '{typeof(Texture2D)}'."); // try cache - if (this.ContentManager.IsLoaded(contentPath)) - return this.ContentManager.Load(contentPath); + if (this.ContentManager.IsLoaded(actualKey)) + return this.ContentManager.Load(actualKey); // fetch & cache using (FileStream stream = File.OpenRead(file.FullName)) { - var texture = Texture2D.FromStream(Game1.graphics.GraphicsDevice, stream); + Texture2D texture = Texture2D.FromStream(Game1.graphics.GraphicsDevice, stream); texture = this.PremultiplyTransparency(texture); - this.ContentManager.Inject(contentPath, texture); + this.ContentManager.Inject(actualKey, texture); return (T)(object)texture; } @@ -115,10 +108,44 @@ namespace StardewModdingAPI.Framework } } + /// 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. + /// The asset key to fetch (if the is ), or the local path to an XNB file relative to the mod folder. + /// Where to search for a matching content asset. + /// The is empty or contains invalid characters. + public string GetActualAssetKey(string key, ContentSource source) + { + switch (source) + { + case ContentSource.GameContent: + return this.ContentManager.NormaliseAssetName(key); + + case ContentSource.ModFolder: + string contentPath = Path.Combine(this.ModFolderPathFromContent, key); + if (contentPath.EndsWith(".xnb")) + contentPath = contentPath.Substring(0, contentPath.Length - 4); + return this.ContentManager.NormaliseAssetName(contentPath); + + default: + throw new NotSupportedException($"Unknown content source '{source}'."); + } + } + /********* ** Private methods *********/ + /// 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", "UnusedParameter.Local", Justification = "Parameter is only used for assertion checks by design.")] + private 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."); + } + /// Get a directory path relative to a given root. /// The root path from which the path should be relative. /// The target file path. @@ -184,7 +211,7 @@ namespace StardewModdingAPI.Framework //Game1.graphics.GraphicsDevice.Viewport = originalViewport; // store data from render target because the RenderTarget2D is volatile - var data = new Color[texture.Width * texture.Height]; + Color[] data = new Color[texture.Width * texture.Height]; renderTarget.GetData(data); // unset texture from graphic device and set modified data back to it diff --git a/src/StardewModdingAPI/Framework/SContentManager.cs b/src/StardewModdingAPI/Framework/SContentManager.cs index e363e6b4..99814c94 100644 --- a/src/StardewModdingAPI/Framework/SContentManager.cs +++ b/src/StardewModdingAPI/Framework/SContentManager.cs @@ -83,6 +83,26 @@ namespace StardewModdingAPI.Framework this.NormaliseAssetNameForPlatform = key => key.Replace('\\', '/'); // based on MonoGame's ContentManager.Load logic } + /// Normalise an asset name so it's consistent with the underlying cache. + /// The asset key. + public string NormaliseAssetName(string assetName) + { + // ensure name format is consistent + string[] parts = assetName.Split(SContentManager.PossiblePathSeparators, StringSplitOptions.RemoveEmptyEntries); + assetName = string.Join(SContentManager.PreferredPathSeparator, parts); + + // apply platform normalisation logic + return this.NormaliseAssetNameForPlatform(assetName); + } + + /// 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.NormaliseAssetName(assetName); + return this.IsNormalisedKeyLoaded(assetName); + } + /// 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. @@ -116,31 +136,9 @@ namespace StardewModdingAPI.Framework this.Cache[assetName] = value; } - /// 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.NormaliseAssetName(assetName); - return this.IsNormalisedKeyLoaded(assetName); - - } - - /********* ** Private methods *********/ - /// Normalise an asset name so it's consistent with the underlying cache. - /// The asset key. - private string NormaliseAssetName(string assetName) - { - // ensure name format is consistent - string[] parts = assetName.Split(SContentManager.PossiblePathSeparators, StringSplitOptions.RemoveEmptyEntries); - assetName = string.Join(SContentManager.PreferredPathSeparator, parts); - - // apply platform normalisation logic - return this.NormaliseAssetNameForPlatform(assetName); - } - /// Get whether an asset has already been loaded. /// The normalised asset name. private bool IsNormalisedKeyLoaded(string normalisedAssetName) diff --git a/src/StardewModdingAPI/IContentHelper.cs b/src/StardewModdingAPI/IContentHelper.cs index b878dfe5..7cde413b 100644 --- a/src/StardewModdingAPI/IContentHelper.cs +++ b/src/StardewModdingAPI/IContentHelper.cs @@ -14,5 +14,11 @@ namespace StardewModdingAPI /// The is empty or contains invalid characters. /// The content asset couldn't be loaded (e.g. because it doesn't exist). T Load(string key, ContentSource source); + + /// 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. + /// The asset key to fetch (if the is ), or the local path to an XNB file relative to the mod folder. + /// Where to search for a matching content asset. + /// The is empty or contains invalid characters. + string GetActualAssetKey(string key, ContentSource source); } } -- cgit From d21f8d6b22d500ec627f0448f132b37d516e3830 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 30 Apr 2017 01:06:57 -0400 Subject: fix crossplatform compatibility (#257) --- src/StardewModdingAPI/Framework/ContentHelper.cs | 1 + src/StardewModdingAPI/Framework/SContentManager.cs | 17 ++++++++++++----- 2 files changed, 13 insertions(+), 5 deletions(-) (limited to 'src/StardewModdingAPI/Framework/SContentManager.cs') diff --git a/src/StardewModdingAPI/Framework/ContentHelper.cs b/src/StardewModdingAPI/Framework/ContentHelper.cs index 7cf726e1..762b7e35 100644 --- a/src/StardewModdingAPI/Framework/ContentHelper.cs +++ b/src/StardewModdingAPI/Framework/ContentHelper.cs @@ -61,6 +61,7 @@ namespace StardewModdingAPI.Framework case ContentSource.ModFolder: // find content file + key = this.ContentManager.NormalisePathSeparators(key); FileInfo file = new FileInfo(Path.Combine(this.ModFolderPath, key)); if (!file.Exists && file.Extension == "") file = new FileInfo(Path.Combine(this.ModFolderPath, key + ".xnb")); diff --git a/src/StardewModdingAPI/Framework/SContentManager.cs b/src/StardewModdingAPI/Framework/SContentManager.cs index 99814c94..88e1df2b 100644 --- a/src/StardewModdingAPI/Framework/SContentManager.cs +++ b/src/StardewModdingAPI/Framework/SContentManager.cs @@ -83,15 +83,22 @@ namespace StardewModdingAPI.Framework this.NormaliseAssetNameForPlatform = key => key.Replace('\\', '/'); // based on MonoGame's ContentManager.Load logic } + /// Normalise path separators in a file path. For asset keys, see instead. + /// The file path to normalise. + public string NormalisePathSeparators(string path) + { + string[] parts = path.Split(SContentManager.PossiblePathSeparators, StringSplitOptions.RemoveEmptyEntries); + string normalised = string.Join(SContentManager.PreferredPathSeparator, parts); + if (path.StartsWith(SContentManager.PreferredPathSeparator)) + normalised = SContentManager.PreferredPathSeparator + normalised; // keep root slash + return normalised; + } + /// Normalise an asset name so it's consistent with the underlying cache. /// The asset key. public string NormaliseAssetName(string assetName) { - // ensure name format is consistent - string[] parts = assetName.Split(SContentManager.PossiblePathSeparators, StringSplitOptions.RemoveEmptyEntries); - assetName = string.Join(SContentManager.PreferredPathSeparator, parts); - - // apply platform normalisation logic + assetName = this.NormalisePathSeparators(assetName); return this.NormaliseAssetNameForPlatform(assetName); } -- cgit