diff options
author | Jesse Plamondon-Willard <github@jplamondonw.com> | 2017-02-25 15:22:45 -0500 |
---|---|---|
committer | Jesse Plamondon-Willard <github@jplamondonw.com> | 2017-02-25 15:22:45 -0500 |
commit | 9c53a254d50718fee3b8043bb0b8bb840557e82f (patch) | |
tree | 7308d7a4b5c3fb80f60614c935b968f848b240f4 /src/StardewModdingAPI/Framework | |
parent | 2151625898fcad388a29c17f92de4bf26c2c091d (diff) | |
download | SMAPI-9c53a254d50718fee3b8043bb0b8bb840557e82f.tar.gz SMAPI-9c53a254d50718fee3b8043bb0b8bb840557e82f.tar.bz2 SMAPI-9c53a254d50718fee3b8043bb0b8bb840557e82f.zip |
add prototype content event + helper to manipulate XNB data (#173)
Diffstat (limited to 'src/StardewModdingAPI/Framework')
-rw-r--r-- | src/StardewModdingAPI/Framework/ContentEventHelper.cs | 142 | ||||
-rw-r--r-- | src/StardewModdingAPI/Framework/SContentManager.cs | 36 |
2 files changed, 171 insertions, 7 deletions
diff --git a/src/StardewModdingAPI/Framework/ContentEventHelper.cs b/src/StardewModdingAPI/Framework/ContentEventHelper.cs new file mode 100644 index 00000000..d4a9bbb8 --- /dev/null +++ b/src/StardewModdingAPI/Framework/ContentEventHelper.cs @@ -0,0 +1,142 @@ +using System; +using System.Collections.Generic; +using System.Text.RegularExpressions; +using Microsoft.Xna.Framework.Graphics; + +namespace StardewModdingAPI.Framework +{ + /// <summary>Encapsulates access and changes to content being read from a data file.</summary> + internal class ContentEventHelper : EventArgs, IContentEventHelper + { + /********* + ** Properties + *********/ + /// <summary>Normalises an asset key to match the cache key.</summary> + private readonly Func<string, string> GetNormalisedPath; + + + /********* + ** Accessors + *********/ + /// <summary>The normalised asset path being read. The format may change between platforms; see <see cref="IsPath"/> to compare with a known path.</summary> + public string Path { get; } + + /// <summary>The content data being read.</summary> + public object Data { get; private set; } + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="path">The file path being read.</param> + /// <param name="data">The content data being read.</param> + /// <param name="getNormalisedPath">Normalises an asset key to match the cache key.</param> + public ContentEventHelper(string path, object data, Func<string, string> getNormalisedPath) + { + this.Path = path; + this.Data = data; + this.GetNormalisedPath = getNormalisedPath; + } + + /// <summary>Get whether the asset path being loaded matches a given path after normalisation.</summary> + /// <param name="path">The expected asset path, relative to the game folder and without the .xnb extension (like 'Data\ObjectInformation').</param> + /// <param name="matchLocalisedVersion">Whether to match a localised version of the asset file (like 'Data\ObjectInformation.ja-JP').</param> + public bool IsPath(string path, bool matchLocalisedVersion = true) + { + path = this.GetNormalisedPath(path); + + // equivalent + if (this.Path.Equals(path, StringComparison.InvariantCultureIgnoreCase)) + return true; + + // localised version + if (matchLocalisedVersion) + { + return + this.Path.StartsWith($"{path}.", StringComparison.InvariantCultureIgnoreCase) // starts with given path + && Regex.IsMatch(this.Path.Substring(path.Length + 1), "^[a-z]+-[A-Z]+$"); // ends with locale (e.g. pt-BR) + } + + // no match + return false; + } + + /// <summary>Get the data as a given type.</summary> + /// <typeparam name="TData">The expected data type.</typeparam> + /// <exception cref="InvalidCastException">The data can't be converted to <typeparamref name="TData"/>.</exception> + public TData GetData<TData>() + { + if (!(this.Data is TData)) + throw new InvalidCastException($"The content data of type {this.Data.GetType().FullName} can't be converted to the requested {typeof(TData).FullName}."); + return (TData)this.Data; + } + + /// <summary>Add or replace an entry in the dictionary data.</summary> + /// <typeparam name="TKey">The entry key type.</typeparam> + /// <typeparam name="TValue">The entry value type.</typeparam> + /// <param name="key">The entry key.</param> + /// <param name="value">The entry value.</param> + /// <exception cref="InvalidOperationException">The content being read isn't a dictionary.</exception> + public void SetDictionaryEntry<TKey, TValue>(TKey key, TValue value) + { + IDictionary<TKey, TValue> data = this.GetData<Dictionary<TKey, TValue>>(); + data[key] = value; + } + + /// <summary>Add or replace an entry in the dictionary data.</summary> + /// <typeparam name="TKey">The entry key type.</typeparam> + /// <typeparam name="TValue">The entry value type.</typeparam> + /// <param name="key">The entry key.</param> + /// <param name="value">A callback which accepts the current value and returns the new value.</param> + /// <exception cref="InvalidOperationException">The content being read isn't a dictionary.</exception> + public void SetDictionaryEntry<TKey, TValue>(TKey key, Func<TValue, TValue> value) + { + IDictionary<TKey, TValue> data = this.GetData<Dictionary<TKey, TValue>>(); + data[key] = value(data[key]); + } + + /// <summary>Replace the entire content value with the given value. This is generally not recommended, since it may break compatibility with other mods or different versions of the game.</summary> + /// <param name="value">The new content value.</param> + /// <exception cref="ArgumentNullException">The <paramref name="value"/> is null.</exception> + /// <exception cref="InvalidCastException">The <paramref name="value"/>'s type is not compatible with the loaded asset's type.</exception> + public void ReplaceWith(object value) + { + if (value == null) + throw new ArgumentNullException(nameof(value), "Can't set a loaded asset to a null value."); + if (!this.Data.GetType().IsInstanceOfType(value)) + throw new InvalidCastException($"Can't replace loaded asset of type {this.GetFriendlyTypeName(this.Data.GetType())} with value of type {this.GetFriendlyTypeName(value.GetType())}. The new type must be compatible to prevent game errors."); + + this.Data = value; + } + + + /********* + ** Private methods + *********/ + /// <summary>Get a human-readable type name.</summary> + /// <param name="type">The type to name.</param> + private string GetFriendlyTypeName(Type type) + { + // dictionary + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>)) + { + Type[] genericArgs = type.GetGenericArguments(); + return $"Dictionary<{this.GetFriendlyTypeName(genericArgs[0])}, {this.GetFriendlyTypeName(genericArgs[1])}>"; + } + + // texture + if (type == typeof(Texture2D)) + return type.Name; + + // native type + if (type == typeof(int)) + return "int"; + if (type == typeof(string)) + return "string"; + + // default + return type.FullName; + } + } +} diff --git a/src/StardewModdingAPI/Framework/SContentManager.cs b/src/StardewModdingAPI/Framework/SContentManager.cs index 2a876d72..344d3ed9 100644 --- a/src/StardewModdingAPI/Framework/SContentManager.cs +++ b/src/StardewModdingAPI/Framework/SContentManager.cs @@ -4,6 +4,7 @@ using System.Globalization; using System.Threading; using Microsoft.Xna.Framework; using StardewModdingAPI.AssemblyRewriters; +using StardewModdingAPI.Events; using StardewModdingAPI.Framework.Reflection; using StardewValley; @@ -22,7 +23,7 @@ namespace StardewModdingAPI.Framework private readonly IDictionary<string, object> Cache; /// <summary>Normalises an asset key to match the cache key.</summary> - private readonly IPrivateMethod NormaliseAssetKey; + private readonly Func<string, string> NormaliseAssetKey; /********* @@ -44,15 +45,23 @@ namespace StardewModdingAPI.Framework public SContentManager(IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, string languageCodeOverride, IMonitor monitor) : base(serviceProvider, rootDirectory, currentCulture, languageCodeOverride) { + // initialise this.Monitor = monitor; - IReflectionHelper reflection = new ReflectionHelper(); + + // get underlying asset cache this.Cache = reflection .GetPrivateField<Dictionary<string, object>>(this, "loadedAssets") .GetValue(); - this.NormaliseAssetKey = Constants.TargetPlatform == Platform.Windows - ? reflection.GetPrivateMethod(typeof(TitleContainer), "GetCleanPath") - : reflection.GetPrivateMethod(this, nameof(this.NormaliseKeyForMono)); + + // get asset key normalisation logic + if (Constants.TargetPlatform == Platform.Windows) + { + IPrivateMethod method = reflection.GetPrivateMethod(typeof(TitleContainer), "GetCleanPath"); + this.NormaliseAssetKey = path => method.Invoke<string>(path); + } + else + this.NormaliseAssetKey = this.NormaliseKeyForMono; } /// <summary>Load an asset that has been processed by the content pipeline.</summary> @@ -60,8 +69,21 @@ namespace StardewModdingAPI.Framework /// <param name="assetName">The asset path relative to the loader root directory, not including the <c>.xnb</c> extension.</param> public override T Load<T>(string assetName) { - assetName = this.NormaliseAssetKey.Invoke<string>(assetName); - return base.Load<T>(assetName); + // pass through if no event handlers + if (!ContentEvents.HasAssetLoadingListeners()) + return base.Load<T>(assetName); + + // skip if already loaded + string key = this.NormaliseAssetKey(assetName); + if (this.Cache.ContainsKey(key)) + return base.Load<T>(assetName); + + // intercept load + T data = base.Load<T>(assetName); + IContentEventHelper helper = new ContentEventHelper(assetName, data, this.NormaliseAssetKey); + ContentEvents.InvokeAssetLoading(this.Monitor, helper); + this.Cache[key] = helper.Data; + return (T)helper.Data; } |