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') 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