add prototype content event + helper to manipulate XNB data (#173)

This commit is contained in:
Jesse Plamondon-Willard 2017-02-25 15:22:45 -05:00
parent 2151625898
commit 9c53a254d5
6 changed files with 297 additions and 7 deletions

View File

@ -0,0 +1,69 @@
using System;
using System.Collections.Generic;
using StardewModdingAPI.Framework;
namespace StardewModdingAPI.Events
{
/// <summary>Events raised when the game loads content.</summary>
[Obsolete("This is an undocumented experimental API and may change without warning.")]
public static class ContentEvents
{
/*********
** Properties
*********/
/// <summary>Tracks the installed mods.</summary>
private static ModRegistry ModRegistry;
/// <summary>Encapsulates monitoring and logging.</summary>
private static IMonitor Monitor;
/// <summary>The mods using the experimental API for which a warning has been raised.</summary>
private static readonly HashSet<string> WarnedMods = new HashSet<string>();
/*********
** Events
*********/
/// <summary>Raised when an XNB file is being read into the cache. Mods can change the data here before it's cached.</summary>
public static event EventHandler<IContentEventHelper> AssetLoading;
/*********
** Internal methods
*********/
/// <summary>Injects types required for backwards compatibility.</summary>
/// <param name="modRegistry">Tracks the installed mods.</param>
/// <param name="monitor">Encapsulates monitoring and logging.</param>
internal static void Shim(ModRegistry modRegistry, IMonitor monitor)
{
ContentEvents.ModRegistry = modRegistry;
ContentEvents.Monitor = monitor;
}
/// <summary>Raise an <see cref="AssetLoading"/> event.</summary>
/// <param name="monitor">Encapsulates monitoring and logging.</param>
/// <param name="contentHelper">Encapsulates access and changes to content being read from a data file.</param>
internal static void InvokeAssetLoading(IMonitor monitor, IContentEventHelper contentHelper)
{
// raise warning about experimental API
foreach (Delegate handler in ContentEvents.AssetLoading.GetInvocationList())
{
string modName = ContentEvents.ModRegistry.GetModFrom(handler) ?? "An unknown mod";
if (!ContentEvents.WarnedMods.Contains(modName))
{
ContentEvents.WarnedMods.Add(modName);
ContentEvents.Monitor.Log($"{modName} used the undocumented and experimental content API, which may change or be removed without warning.", LogLevel.Warn);
}
}
// raise event
monitor.SafelyRaiseGenericEvent($"{nameof(ContentEvents)}.{nameof(ContentEvents.AssetLoading)}", ContentEvents.AssetLoading?.GetInvocationList(), null, contentHelper);
}
/// <summary>Get whether there are any <see cref="AssetLoading"/> listeners.</summary>
internal static bool HasAssetLoadingListeners()
{
return ContentEvents.AssetLoading != null;
}
}
}

View File

@ -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;
}
}
}

View File

@ -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);
// 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;
}

View File

@ -0,0 +1,53 @@
using System;
namespace StardewModdingAPI
{
/// <summary>Encapsulates access and changes to content being read from a data file.</summary>
public interface IContentEventHelper
{
/*********
** 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>
string Path { get; }
/// <summary>The content data being read.</summary>
object Data { get; }
/*********
** Public methods
*********/
/// <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>
bool IsPath(string path, bool matchLocalisedVersion = true);
/// <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>
TData GetData<TData>();
/// <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>
void SetDictionaryEntry<TKey, TValue>(TKey key, TValue 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>
void SetDictionaryEntry<TKey, TValue>(TKey key, Func<TValue, TValue> value);
/// <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>
void ReplaceWith(object value);
}
}

View File

@ -97,6 +97,7 @@ namespace StardewModdingAPI
InternalExtensions.Shim(this.ModRegistry);
Log.Shim(this.DeprecationManager, this.GetSecondaryMonitor("legacy mod"), this.ModRegistry);
Mod.Shim(this.DeprecationManager);
ContentEvents.Shim(this.ModRegistry, this.Monitor);
PlayerEvents.Shim(this.DeprecationManager);
TimeEvents.Shim(this.DeprecationManager);
#pragma warning restore 618

View File

@ -117,6 +117,7 @@
<Compile Include="Advanced\ConfigFile.cs" />
<Compile Include="Advanced\IConfigFile.cs" />
<Compile Include="Command.cs" />
<Compile Include="Events\ContentEvents.cs" />
<Compile Include="Framework\Command.cs" />
<Compile Include="Config.cs" />
<Compile Include="Constants.cs" />
@ -147,6 +148,7 @@
<Compile Include="Framework\AssemblyDefinitionResolver.cs" />
<Compile Include="Framework\AssemblyParseResult.cs" />
<Compile Include="Framework\CommandManager.cs" />
<Compile Include="Framework\ContentEventHelper.cs" />
<Compile Include="Framework\Logging\ConsoleInterceptionManager.cs" />
<Compile Include="Framework\Logging\InterceptingTextWriter.cs" />
<Compile Include="Framework\CommandHelper.cs" />
@ -158,6 +160,7 @@
<Compile Include="Framework\Serialisation\SelectiveStringEnumConverter.cs" />
<Compile Include="Framework\Serialisation\SemanticVersionConverter.cs" />
<Compile Include="ICommandHelper.cs" />
<Compile Include="IContentEventHelper.cs" />
<Compile Include="IModRegistry.cs" />
<Compile Include="Events\LocationEvents.cs" />
<Compile Include="Events\MenuEvents.cs" />