diff options
Diffstat (limited to 'src/SMAPI/Framework/ContentManagers')
5 files changed, 464 insertions, 453 deletions
diff --git a/src/SMAPI/Framework/ContentManagers/BaseContentManager.cs b/src/SMAPI/Framework/ContentManagers/BaseContentManager.cs index 5645c0fa..b2e3ec0f 100644 --- a/src/SMAPI/Framework/ContentManagers/BaseContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/BaseContentManager.cs @@ -5,6 +5,7 @@ using System.Diagnostics.Contracts; using System.Globalization; using System.IO; using System.Linq; +using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using StardewModdingAPI.Framework.Content; using StardewModdingAPI.Framework.Exceptions; @@ -29,9 +30,15 @@ namespace StardewModdingAPI.Framework.ContentManagers /// <summary>Encapsulates monitoring and logging.</summary> protected readonly IMonitor Monitor; + /// <summary>Simplifies access to private code.</summary> + protected readonly Reflector Reflection; + /// <summary>Whether to enable more aggressive memory optimizations.</summary> protected readonly bool AggressiveMemoryOptimizations; + /// <summary>Whether to automatically try resolving keys to a localized form if available.</summary> + protected bool TryLocalizeKeys = true; + /// <summary>Whether the content coordinator has been disposed.</summary> private bool IsDisposed; @@ -39,7 +46,7 @@ namespace StardewModdingAPI.Framework.ContentManagers private readonly Action<BaseContentManager> OnDisposing; /// <summary>A list of disposable assets.</summary> - private readonly List<WeakReference<IDisposable>> Disposables = new List<WeakReference<IDisposable>>(); + private readonly List<WeakReference<IDisposable>> Disposables = new(); /// <summary>The disposable assets tracked by the base content manager.</summary> /// <remarks>This should be kept empty to avoid keeping disposable assets referenced forever, which prevents garbage collection when they're unused. Disposable assets are tracked by <see cref="Disposables"/> instead, which avoids a hard reference.</remarks> @@ -56,7 +63,7 @@ namespace StardewModdingAPI.Framework.ContentManagers public LanguageCode Language => this.GetCurrentLanguage(); /// <inheritdoc /> - public string FullRootDirectory => Path.Combine(Constants.ExecutionPath, this.RootDirectory); + public string FullRootDirectory => Path.Combine(Constants.GamePath, this.RootDirectory); /// <inheritdoc /> public bool IsNamespaced { get; } @@ -82,51 +89,97 @@ namespace StardewModdingAPI.Framework.ContentManagers // init this.Name = name; this.Coordinator = coordinator ?? throw new ArgumentNullException(nameof(coordinator)); - this.Cache = new ContentCache(this, reflection); + // ReSharper disable once VirtualMemberCallInConstructor -- LoadedAssets isn't overridden by SMAPI or Stardew Valley + this.Cache = new ContentCache(this.LoadedAssets); this.Monitor = monitor ?? throw new ArgumentNullException(nameof(monitor)); + this.Reflection = reflection; this.OnDisposing = onDisposing; this.IsNamespaced = isNamespaced; this.AggressiveMemoryOptimizations = aggressiveMemoryOptimizations; // get asset data - this.BaseDisposableReferences = reflection.GetField<List<IDisposable>>(this, "disposableAssets").GetValue(); + this.BaseDisposableReferences = reflection.GetField<List<IDisposable>?>(this, "disposableAssets").GetValue() + ?? throw new InvalidOperationException("Can't initialize content manager: the required 'disposableAssets' field wasn't found."); } /// <inheritdoc /> - public override T Load<T>(string assetName) + public virtual bool DoesAssetExist<T>(IAssetName assetName) + where T : notnull { - return this.Load<T>(assetName, this.Language, useCache: true); + return this.Cache.ContainsKey(assetName.Name); } /// <inheritdoc /> - public override T Load<T>(string assetName, LanguageCode language) + [Obsolete("This method is implemented for the base game and should not be used directly. To load an asset from the underlying content manager directly, use " + nameof(BaseContentManager.RawLoad) + " instead.")] + public sealed override T LoadBase<T>(string assetName) { - return this.Load<T>(assetName, language, useCache: true); + return this.Load<T>(assetName, LanguageCode.en); } /// <inheritdoc /> - public abstract T Load<T>(string assetName, LocalizedContentManager.LanguageCode language, bool useCache); - - /// <inheritdoc /> - [Obsolete("This method is implemented for the base game and should not be used directly. To load an asset from the underlying content manager directly, use " + nameof(BaseContentManager.RawLoad) + " instead.")] - public override T LoadBase<T>(string assetName) + public sealed override T Load<T>(string assetName) { - return this.Load<T>(assetName, LanguageCode.en, useCache: true); + return this.Load<T>(assetName, this.Language); } /// <inheritdoc /> - public virtual void OnLocaleChanged() { } + public sealed override T Load<T>(string assetName, LanguageCode language) + { + assetName = this.PrenormalizeRawAssetName(assetName); + IAssetName parsedName = this.Coordinator.ParseAssetName(assetName, allowLocales: this.TryLocalizeKeys); + return this.LoadLocalized<T>(parsedName, language, useCache: true); + } /// <inheritdoc /> - [Pure] - public string NormalizePathSeparators(string path) + public T LoadLocalized<T>(IAssetName assetName, LanguageCode language, bool useCache) + where T : notnull { - return this.Cache.NormalizePathSeparators(path); + // ignore locale in English (or if disabled) + if (!this.TryLocalizeKeys || language == LocalizedContentManager.LanguageCode.en) + return this.LoadExact<T>(assetName, useCache: useCache); + + // check for localized asset + if (!LocalizedContentManager.localizedAssetNames.TryGetValue(assetName.Name, out _)) + { + string localeCode = this.LanguageCodeString(language); + IAssetName localizedName = new AssetName(baseName: assetName.BaseName, localeCode: localeCode, languageCode: language); + + try + { + T data = this.LoadExact<T>(localizedName, useCache: useCache); + LocalizedContentManager.localizedAssetNames[assetName.Name] = localizedName.Name; + return data; + } + catch (ContentLoadException) + { + localizedName = new AssetName(assetName.BaseName + "_international", null, null); + try + { + T data = this.LoadExact<T>(localizedName, useCache: useCache); + LocalizedContentManager.localizedAssetNames[assetName.Name] = localizedName.Name; + return data; + } + catch (ContentLoadException) + { + LocalizedContentManager.localizedAssetNames[assetName.Name] = assetName.Name; + } + } + } + + // use cached key + string rawName = LocalizedContentManager.localizedAssetNames[assetName.Name]; + if (assetName.Name != rawName) + assetName = this.Coordinator.ParseAssetName(rawName, allowLocales: this.TryLocalizeKeys); + return this.LoadExact<T>(assetName, useCache: useCache); } /// <inheritdoc /> + public abstract T LoadExact<T>(IAssetName assetName, bool useCache) + where T : notnull; + + /// <inheritdoc /> [SuppressMessage("ReSharper", "ParameterOnlyUsedForPreconditionCheck.Local", Justification = "Parameter is only used for assertion checks by design.")] - public string AssertAndNormalizeAssetName(string assetName) + public string AssertAndNormalizeAssetName(string? assetName) { // NOTE: the game checks for ContentLoadException to handle invalid keys, so avoid // throwing other types like ArgumentException here. @@ -154,19 +207,11 @@ namespace StardewModdingAPI.Framework.ContentManagers } /// <inheritdoc /> - public bool IsLoaded(string assetName, LanguageCode language) + public bool IsLoaded(IAssetName assetName) { - assetName = this.Cache.NormalizeKey(assetName); - return this.IsNormalizedKeyLoaded(assetName, language); + return this.Cache.ContainsKey(assetName.Name); } - /// <inheritdoc /> - public IEnumerable<string> GetAssetKeys() - { - return this.Cache.Keys - .Select(this.GetAssetName) - .Distinct(); - } /**** ** Cache invalidation @@ -177,13 +222,13 @@ namespace StardewModdingAPI.Framework.ContentManagers IDictionary<string, object> removeAssets = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); this.Cache.Remove((key, asset) => { - this.ParseCacheKey(key, out string assetName, out _); + string baseAssetName = this.Coordinator.ParseAssetName(key, allowLocales: this.TryLocalizeKeys).BaseName; // check if asset should be removed - bool remove = removeAssets.ContainsKey(assetName); - if (!remove && predicate(assetName, asset.GetType())) + bool remove = removeAssets.ContainsKey(baseAssetName); + if (!remove && predicate(baseAssetName, asset.GetType())) { - removeAssets[assetName] = asset; + removeAssets[baseAssetName] = asset; remove = true; } @@ -211,7 +256,7 @@ namespace StardewModdingAPI.Framework.ContentManagers // dispose uncached assets foreach (WeakReference<IDisposable> reference in this.Disposables) { - if (reference.TryGetTarget(out IDisposable disposable)) + if (reference.TryGetTarget(out IDisposable? disposable)) { try { @@ -241,78 +286,64 @@ namespace StardewModdingAPI.Framework.ContentManagers /********* ** Private methods *********/ + /// <summary>Apply initial normalization to a raw asset name before it's parsed.</summary> + /// <param name="assetName">The asset name to normalize.</param> + [return: NotNullIfNotNull("assetName")] + private string? PrenormalizeRawAssetName(string? assetName) + { + // trim + assetName = assetName?.Trim(); + + // For legacy reasons, mods can pass .xnb file extensions to the content pipeline which + // are then stripped. This will be re-added as needed when reading from raw files. + if (assetName?.EndsWith(".xnb") == true) + assetName = assetName[..^".xnb".Length]; + + return assetName; + } + + /// <summary>Normalize path separators in a file path. For asset keys, see <see cref="AssertAndNormalizeAssetName"/> instead.</summary> + /// <param name="path">The file path to normalize.</param> + [Pure] + [return: NotNullIfNotNull("path")] + protected string? NormalizePathSeparators(string? path) + { + return this.Cache.NormalizePathSeparators(path); + } + /// <summary>Load an asset file directly from the underlying content manager.</summary> /// <typeparam name="T">The type of asset to load.</typeparam> /// <param name="assetName">The normalized asset key.</param> /// <param name="useCache">Whether to read/write the loaded asset to the asset cache.</param> - protected virtual T RawLoad<T>(string assetName, bool useCache) + protected virtual T RawLoad<T>(IAssetName assetName, bool useCache) { return useCache - ? base.LoadBase<T>(assetName) - : base.ReadAsset<T>(assetName, disposable => this.Disposables.Add(new WeakReference<IDisposable>(disposable))); + ? base.LoadBase<T>(assetName.Name) + : this.ReadAsset<T>(assetName.Name, disposable => this.Disposables.Add(new WeakReference<IDisposable>(disposable))); } /// <summary>Add tracking data to an asset and add it to the cache.</summary> /// <typeparam name="T">The type of asset to inject.</typeparam> /// <param name="assetName">The asset path relative to the loader root directory, not including the <c>.xnb</c> extension.</param> /// <param name="value">The asset value.</param> - /// <param name="language">The language code for which to inject the asset.</param> /// <param name="useCache">Whether to save the asset to the asset cache.</param> - protected virtual void TrackAsset<T>(string assetName, T value, LanguageCode language, bool useCache) + protected virtual void TrackAsset<T>(IAssetName assetName, T value, bool useCache) + where T : notnull { // track asset key if (value is Texture2D texture) - texture.Name = assetName; + texture.Name = assetName.Name; - // cache asset + // save to cache + // Note: even if the asset was loaded and cached right before this method was called, + // we need to fully re-inject it because a mod editor may have changed the asset in a + // way that doesn't change the instance stored in the cache, e.g. using + // `asset.ReplaceWith`. if (useCache) - { - assetName = this.AssertAndNormalizeAssetName(assetName); - this.Cache[assetName] = value; - } + this.Cache[assetName.Name] = value; // avoid hard disposable references; see remarks on the field this.BaseDisposableReferences.Clear(); } - - /// <summary>Parse a cache key into its component parts.</summary> - /// <param name="cacheKey">The input cache key.</param> - /// <param name="assetName">The original asset name.</param> - /// <param name="localeCode">The asset locale code (or <c>null</c> if not localized).</param> - protected void ParseCacheKey(string cacheKey, out string assetName, out string localeCode) - { - // handle localized key - if (!string.IsNullOrWhiteSpace(cacheKey)) - { - int lastSepIndex = cacheKey.LastIndexOf(".", StringComparison.Ordinal); - if (lastSepIndex >= 0) - { - string suffix = cacheKey.Substring(lastSepIndex + 1, cacheKey.Length - lastSepIndex - 1); - if (this.Coordinator.TryGetLanguageEnum(suffix, out _)) - { - assetName = cacheKey.Substring(0, lastSepIndex); - localeCode = cacheKey.Substring(lastSepIndex + 1, cacheKey.Length - lastSepIndex - 1); - return; - } - } - } - - // handle simple key - assetName = cacheKey; - localeCode = null; - } - - /// <summary>Get whether an asset has already been loaded.</summary> - /// <param name="normalizedAssetName">The normalized asset name.</param> - /// <param name="language">The language to check.</param> - protected abstract bool IsNormalizedKeyLoaded(string normalizedAssetName, LanguageCode language); - - /// <summary>Get the asset name from a cache key.</summary> - /// <param name="cacheKey">The input cache key.</param> - private string GetAssetName(string cacheKey) - { - this.ParseCacheKey(cacheKey, out string assetName, out string _); - return assetName; - } } } diff --git a/src/SMAPI/Framework/ContentManagers/GameContentManager.cs b/src/SMAPI/Framework/ContentManagers/GameContentManager.cs index ab198076..083df454 100644 --- a/src/SMAPI/Framework/ContentManagers/GameContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/GameContentManager.cs @@ -1,13 +1,14 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; -using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; +using StardewModdingAPI.Events; using StardewModdingAPI.Framework.Content; -using StardewModdingAPI.Framework.Exceptions; +using StardewModdingAPI.Framework.Deprecations; using StardewModdingAPI.Framework.Reflection; using StardewModdingAPI.Framework.Utilities; using StardewModdingAPI.Internal; @@ -24,16 +25,7 @@ namespace StardewModdingAPI.Framework.ContentManagers ** Fields *********/ /// <summary>The assets currently being intercepted by <see cref="IAssetLoader"/> instances. This is used to prevent infinite loops when a loader loads a new asset.</summary> - private readonly ContextHash<string> AssetsBeingLoaded = new ContextHash<string>(); - - /// <summary>Interceptors which provide the initial versions of matching assets.</summary> - private IList<ModLinked<IAssetLoader>> Loaders => this.Coordinator.Loaders; - - /// <summary>Interceptors which edit matching assets after they're loaded.</summary> - private IList<ModLinked<IAssetEditor>> Editors => this.Coordinator.Editors; - - /// <summary>Maps asset names to their localized form, like <c>LooseSprites\Billboard => LooseSprites\Billboard.fr-FR</c> (localized) or <c>Maps\AnimalShop => Maps\AnimalShop</c> (not localized).</summary> - private IDictionary<string, string> LocalizedAssetNames => LocalizedContentManager.localizedAssetNames; + private readonly ContextHash<string> AssetsBeingLoaded = new(); /// <summary>Whether the next load is the first for any game content manager.</summary> private static bool IsFirstLoad = true; @@ -41,6 +33,9 @@ namespace StardewModdingAPI.Framework.ContentManagers /// <summary>A callback to invoke the first time *any* game content manager loads an asset.</summary> private readonly Action OnLoadingFirstAsset; + /// <summary>A callback to invoke when an asset is fully loaded.</summary> + private readonly Action<BaseContentManager, IAssetName> OnAssetLoaded; + /********* ** Public methods @@ -55,15 +50,45 @@ namespace StardewModdingAPI.Framework.ContentManagers /// <param name="reflection">Simplifies access to private code.</param> /// <param name="onDisposing">A callback to invoke when the content manager is being disposed.</param> /// <param name="onLoadingFirstAsset">A callback to invoke the first time *any* game content manager loads an asset.</param> + /// <param name="onAssetLoaded">A callback to invoke when an asset is fully loaded.</param> /// <param name="aggressiveMemoryOptimizations">Whether to enable more aggressive memory optimizations.</param> - public GameContentManager(string name, IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, ContentCoordinator coordinator, IMonitor monitor, Reflector reflection, Action<BaseContentManager> onDisposing, Action onLoadingFirstAsset, bool aggressiveMemoryOptimizations) + public GameContentManager(string name, IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, ContentCoordinator coordinator, IMonitor monitor, Reflector reflection, Action<BaseContentManager> onDisposing, Action onLoadingFirstAsset, Action<BaseContentManager, IAssetName> onAssetLoaded, bool aggressiveMemoryOptimizations) : base(name, serviceProvider, rootDirectory, currentCulture, coordinator, monitor, reflection, onDisposing, isNamespaced: false, aggressiveMemoryOptimizations: aggressiveMemoryOptimizations) { this.OnLoadingFirstAsset = onLoadingFirstAsset; + this.OnAssetLoaded = onAssetLoaded; } /// <inheritdoc /> - public override T Load<T>(string assetName, LocalizedContentManager.LanguageCode language, bool useCache) + public override bool DoesAssetExist<T>(IAssetName assetName) + { + if (base.DoesAssetExist<T>(assetName)) + return true; + + // vanilla asset + if (File.Exists(Path.Combine(this.RootDirectory, $"{assetName.Name}.xnb"))) + return true; + + // managed asset + if (this.Coordinator.TryParseManagedAssetKey(assetName.Name, out string? contentManagerID, out IAssetName? relativePath)) + return this.Coordinator.DoesManagedAssetExist<T>(contentManagerID, relativePath); + + // custom asset from a loader + string locale = this.GetLocale(); + IAssetInfo info = new AssetInfo(locale, assetName, typeof(T), this.AssertAndNormalizeAssetName); + AssetLoadOperation[] loaders = this.GetLoaders<object>(info).ToArray(); + + if (!this.AssertMaxOneRequiredLoader(info, loaders, out string? error)) + { + this.Monitor.Log(error, LogLevel.Warn); + return false; + } + + return loaders.Any(); + } + + /// <inheritdoc /> + public override T LoadExact<T>(IAssetName assetName, bool useCache) { // raise first-load callback if (GameContentManager.IsFirstLoad) @@ -72,71 +97,45 @@ namespace StardewModdingAPI.Framework.ContentManagers this.OnLoadingFirstAsset(); } - // normalize asset name - assetName = this.AssertAndNormalizeAssetName(assetName); - if (this.TryParseExplicitLanguageAssetKey(assetName, out string newAssetName, out LanguageCode newLanguage)) - return this.Load<T>(newAssetName, newLanguage, useCache); - // get from cache - if (useCache && this.IsLoaded(assetName, language)) - return this.RawLoad<T>(assetName, language, useCache: true); + if (useCache && this.IsLoaded(assetName)) + return this.RawLoad<T>(assetName, useCache: true); // get managed asset - if (this.Coordinator.TryParseManagedAssetKey(assetName, out string contentManagerID, out string relativePath)) + if (this.Coordinator.TryParseManagedAssetKey(assetName.Name, out string? contentManagerID, out IAssetName? relativePath)) { T managedAsset = this.Coordinator.LoadManagedAsset<T>(contentManagerID, relativePath); - this.TrackAsset(assetName, managedAsset, language, useCache); + this.TrackAsset(assetName, managedAsset, useCache); return managedAsset; } // load asset T data; - if (this.AssetsBeingLoaded.Contains(assetName)) + if (this.AssetsBeingLoaded.Contains(assetName.Name)) { 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}"); - data = this.RawLoad<T>(assetName, language, useCache); + data = this.RawLoad<T>(assetName, useCache); } else { - data = this.AssetsBeingLoaded.Track(assetName, () => + data = this.AssetsBeingLoaded.Track(assetName.Name, () => { - string locale = this.GetLocale(language); - IAssetInfo info = new AssetInfo(locale, assetName, typeof(T), this.AssertAndNormalizeAssetName); + IAssetInfo info = new AssetInfo(assetName.LocaleCode, assetName, typeof(T), this.AssertAndNormalizeAssetName); IAssetData asset = this.ApplyLoader<T>(info) - ?? new AssetDataForObject(info, this.RawLoad<T>(assetName, language, useCache), this.AssertAndNormalizeAssetName); + ?? new AssetDataForObject(info, this.RawLoad<T>(assetName, useCache), this.AssertAndNormalizeAssetName, this.Reflection); asset = this.ApplyEditors<T>(info, asset); return (T)asset.Data; }); } - // update cache & return data - this.TrackAsset(assetName, data, language, useCache); - return data; - } + // update cache + this.TrackAsset(assetName, data, useCache); - /// <inheritdoc /> - public override void OnLocaleChanged() - { - base.OnLocaleChanged(); - - // find assets for which a translatable version was loaded - HashSet<string> removeAssetNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); - foreach (string key in this.LocalizedAssetNames.Where(p => p.Key != p.Value).Select(p => p.Key)) - removeAssetNames.Add(this.TryParseExplicitLanguageAssetKey(key, out string assetName, out _) ? assetName : key); - - // invalidate translatable assets - string[] invalidated = this - .InvalidateCache((key, type) => - removeAssetNames.Contains(key) - || (this.TryParseExplicitLanguageAssetKey(key, out string assetName, out _) && removeAssetNames.Contains(assetName)) - ) - .Select(p => p.Key) - .OrderBy(p => p, StringComparer.OrdinalIgnoreCase) - .ToArray(); - if (invalidated.Any()) - this.Monitor.Log($"Invalidated {invalidated.Length} asset names: {string.Join(", ", invalidated)} for locale change."); + // raise event & return data + this.OnAssetLoaded(this, assetName); + return data; } /// <inheritdoc /> @@ -149,231 +148,101 @@ namespace StardewModdingAPI.Framework.ContentManagers /********* ** Private methods *********/ - /// <inheritdoc /> - protected override bool IsNormalizedKeyLoaded(string normalizedAssetName, LanguageCode language) - { - string cachedKey = null; - bool localized = - language != LocalizedContentManager.LanguageCode.en - && !this.Coordinator.IsManagedAssetKey(normalizedAssetName) - && this.LocalizedAssetNames.TryGetValue(normalizedAssetName, out cachedKey); - - return localized - ? this.Cache.ContainsKey(cachedKey) - : this.Cache.ContainsKey(normalizedAssetName); - } - - /// <inheritdoc /> - protected override void TrackAsset<T>(string assetName, T value, LanguageCode language, bool useCache) - { - // handle explicit language in asset name - { - if (this.TryParseExplicitLanguageAssetKey(assetName, out string newAssetName, out LanguageCode newLanguage)) - { - this.TrackAsset(newAssetName, value, newLanguage, useCache); - return; - } - } - - // save to cache - // Note: even if the asset was loaded and cached right before this method was called, - // we need to fully re-inject it here for two reasons: - // 1. So we can look up an asset by its base or localized key (the game/XNA logic - // only caches by the most specific key). - // 2. Because a mod asset loader/editor may have changed the asset in a way that - // doesn't change the instance stored in the cache, e.g. using `asset.ReplaceWith`. - if (useCache) - { - string translatedKey = $"{assetName}.{this.GetLocale(language)}"; - base.TrackAsset(assetName, value, language, useCache: true); - if (this.Cache.ContainsKey(translatedKey)) - base.TrackAsset(translatedKey, value, language, useCache: true); - - // track whether the injected asset is translatable for is-loaded lookups - if (this.Cache.ContainsKey(translatedKey)) - this.LocalizedAssetNames[assetName] = translatedKey; - else if (this.Cache.ContainsKey(assetName)) - this.LocalizedAssetNames[assetName] = assetName; - else - this.Monitor.Log($"Asset '{assetName}' could not be found in the cache immediately after injection.", LogLevel.Error); - } - } - - /// <summary>Load an asset file directly from the underlying content manager.</summary> - /// <typeparam name="T">The type of asset to load.</typeparam> - /// <param name="assetName">The normalized asset key.</param> - /// <param name="language">The language code for which to load content.</param> - /// <param name="useCache">Whether to read/write the loaded asset to the asset cache.</param> - /// <remarks>Derived from <see cref="LocalizedContentManager.Load{T}(string, LocalizedContentManager.LanguageCode)"/>.</remarks> - private T RawLoad<T>(string assetName, LanguageCode language, bool useCache) + /// <summary>Load the initial asset from the registered loaders.</summary> + /// <param name="info">The basic asset metadata.</param> + /// <returns>Returns the loaded asset metadata, or <c>null</c> if no loader matched.</returns> + private IAssetData? ApplyLoader<T>(IAssetInfo info) + where T : notnull { - try + // find matching loader + AssetLoadOperation? loader; { - // use cached key - if (language == this.Language && this.LocalizedAssetNames.TryGetValue(assetName, out string cachedKey)) - return base.RawLoad<T>(cachedKey, useCache); + AssetLoadOperation[] loaders = this.GetLoaders<T>(info).OrderByDescending(p => p.Priority).ToArray(); - // try translated key - if (language != LocalizedContentManager.LanguageCode.en) + if (!this.AssertMaxOneRequiredLoader(info, loaders, out string? error)) { - string translatedKey = $"{assetName}.{this.GetLocale(language)}"; - try - { - T obj = base.RawLoad<T>(translatedKey, useCache); - this.LocalizedAssetNames[assetName] = translatedKey; - return obj; - } - catch (ContentLoadException) - { - this.LocalizedAssetNames[assetName] = assetName; - } + this.Monitor.Log(error, LogLevel.Warn); + return null; } - // try base asset - return base.RawLoad<T>(assetName, useCache); + loader = loaders.FirstOrDefault(); } - catch (ContentLoadException ex) when (ex.InnerException is FileNotFoundException innerEx && innerEx.InnerException == null) - { - throw new SContentLoadException($"Error loading \"{assetName}\": it isn't in the Content folder and no mod provided it."); - } - } - /// <summary>Parse an asset key that contains an explicit language into its asset name and language, if applicable.</summary> - /// <param name="rawAsset">The asset key to parse.</param> - /// <param name="assetName">The asset name without the language code.</param> - /// <param name="language">The language code removed from the asset name.</param> - /// <returns>Returns whether the asset key contains an explicit language and was successfully parsed.</returns> - private bool TryParseExplicitLanguageAssetKey(string rawAsset, out string assetName, out LanguageCode language) - { - if (string.IsNullOrWhiteSpace(rawAsset)) - throw new SContentLoadException("The asset key is empty."); - - // extract language code - int splitIndex = rawAsset.LastIndexOf('.'); - if (splitIndex != -1 && this.Coordinator.TryGetLanguageEnum(rawAsset.Substring(splitIndex + 1), out language)) - { - assetName = rawAsset.Substring(0, splitIndex); - return true; - } - - // no explicit language code found - assetName = rawAsset; - language = this.Language; - return false; - } - - /// <summary>Load the initial asset from the registered <see cref="Loaders"/>.</summary> - /// <param name="info">The basic asset metadata.</param> - /// <returns>Returns the loaded asset metadata, or <c>null</c> if no loader matched.</returns> - private IAssetData ApplyLoader<T>(IAssetInfo info) - { - // find matching loaders - var loaders = this.Loaders - .Where(entry => - { - try - { - return entry.Data.CanLoad<T>(info); - } - catch (Exception ex) - { - entry.Mod.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()) + // no loader found + if (loader == null) return null; - if (loaders.Length > 1) - { - string[] loaderNames = loaders.Select(p => p.Mod.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].Mod; - IAssetLoader loader = loaders[0].Data; + IModMetadata mod = loader.Mod; T data; try { - data = loader.Load<T>(info); - this.Monitor.Log($"{mod.DisplayName} loaded asset '{info.AssetName}'.", LogLevel.Trace); + data = (T)loader.GetData(info); + this.Monitor.Log($"{mod.DisplayName} loaded asset '{info.Name}'{this.GetOnBehalfOfLabel(loader.OnBehalfOf)}."); } 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); + mod.LogAsMod($"Mod crashed when loading asset '{info.Name}'{this.GetOnBehalfOfLabel(loader.OnBehalfOf)}. SMAPI will use the default asset instead. Error details:\n{ex.GetLogSummary()}", LogLevel.Error); return null; } // return matched asset - return this.TryFixAndValidateLoadedAsset(info, data, mod) - ? new AssetDataForObject(info, data, this.AssertAndNormalizeAssetName) + return this.TryFixAndValidateLoadedAsset(info, data, loader) + ? new AssetDataForObject(info, data, this.AssertAndNormalizeAssetName, this.Reflection) : null; } - /// <summary>Apply any <see cref="Editors"/> to a loaded asset.</summary> + /// <summary>Apply any editors to a loaded asset.</summary> /// <typeparam name="T">The asset type.</typeparam> /// <param name="info">The basic asset metadata.</param> /// <param name="asset">The loaded asset.</param> private IAssetData ApplyEditors<T>(IAssetInfo info, IAssetData asset) + where T : notnull { - IAssetData GetNewData(object data) => new AssetDataForObject(info, data, this.AssertAndNormalizeAssetName); + IAssetData GetNewData(object data) => new AssetDataForObject(info, data, this.AssertAndNormalizeAssetName, this.Reflection); // special case: if the asset was loaded with a more general type like 'object', call editors with the actual type instead. { Type actualType = asset.Data.GetType(); - Type actualOpenType = actualType.IsGenericType ? actualType.GetGenericTypeDefinition() : null; + Type? actualOpenType = actualType.IsGenericType ? actualType.GetGenericTypeDefinition() : null; if (typeof(T) != actualType && (actualOpenType == typeof(Dictionary<,>) || actualOpenType == typeof(List<>) || actualType == typeof(Texture2D) || actualType == typeof(Map))) { return (IAssetData)this.GetType() - .GetMethod(nameof(this.ApplyEditors), BindingFlags.NonPublic | BindingFlags.Instance) + .GetMethod(nameof(this.ApplyEditors), BindingFlags.NonPublic | BindingFlags.Instance)! .MakeGenericMethod(actualType) - .Invoke(this, new object[] { info, asset }); + .Invoke(this, new object[] { info, asset })!; } } // edit asset - foreach (var entry in this.Editors) + AssetEditOperation[] editors = this.GetEditors<T>(info).OrderBy(p => p.Priority).ToArray(); + foreach (AssetEditOperation editor in editors) { - // check for match - IModMetadata mod = entry.Mod; - IAssetEditor editor = entry.Data; - try - { - if (!editor.CanEdit<T>(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; - } + IModMetadata mod = editor.Mod; // try edit object prevAsset = asset.Data; try { - editor.Edit<T>(asset); - this.Monitor.Log($"{mod.DisplayName} edited {info.AssetName}."); + editor.ApplyEdit(asset); + this.Monitor.Log($"{mod.DisplayName} edited {info.Name}{this.GetOnBehalfOfLabel(editor.OnBehalfOf)}."); } 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); + mod.LogAsMod($"Mod crashed when editing asset '{info.Name}'{this.GetOnBehalfOfLabel(editor.OnBehalfOf)}, which may cause errors in-game. Error details:\n{ex.GetLogSummary()}", LogLevel.Error); } // validate edit + // ReSharper disable once ConditionIsAlwaysTrueOrFalse -- it's only guaranteed non-null after this method if (asset.Data == null) { - mod.LogAsMod($"Mod incorrectly set asset '{info.AssetName}' to a null value; ignoring override.", LogLevel.Warn); + mod.LogAsMod($"Mod incorrectly set asset '{info.Name}'{this.GetOnBehalfOfLabel(editor.OnBehalfOf)} to a null value; ignoring override.", LogLevel.Warn); asset = GetNewData(prevAsset); } - else if (!(asset.Data is T)) + else if (asset.Data is not T) { - mod.LogAsMod($"Mod incorrectly set asset '{asset.AssetName}' to incompatible type '{asset.Data.GetType()}', expected '{typeof(T)}'; ignoring override.", LogLevel.Warn); + mod.LogAsMod($"Mod incorrectly set asset '{asset.Name}'{this.GetOnBehalfOfLabel(editor.OnBehalfOf)} to incompatible type '{asset.Data.GetType()}', expected '{typeof(T)}'; ignoring override.", LogLevel.Warn); asset = GetNewData(prevAsset); } } @@ -382,32 +251,99 @@ namespace StardewModdingAPI.Framework.ContentManagers return asset; } + /// <summary>Get the asset loaders which handle an asset.</summary> + /// <typeparam name="T">The asset type.</typeparam> + /// <param name="info">The basic asset metadata.</param> + private IEnumerable<AssetLoadOperation> GetLoaders<T>(IAssetInfo info) + where T : notnull + { + return this.Coordinator + .GetAssetOperations<T>(info) + .SelectMany(p => p.LoadOperations); + } + + /// <summary>Get the asset editors to apply to an asset.</summary> + /// <typeparam name="T">The asset type.</typeparam> + /// <param name="info">The basic asset metadata.</param> + private IEnumerable<AssetEditOperation> GetEditors<T>(IAssetInfo info) + where T : notnull + { + return this.Coordinator + .GetAssetOperations<T>(info) + .SelectMany(p => p.EditOperations); + } + + /// <summary>Assert that at most one loader will be applied to an asset.</summary> + /// <param name="info">The basic asset metadata.</param> + /// <param name="loaders">The asset loaders to apply.</param> + /// <param name="error">The error message to show to the user, if the method returns false.</param> + /// <returns>Returns true if only one loader will apply, else false.</returns> + private bool AssertMaxOneRequiredLoader(IAssetInfo info, AssetLoadOperation[] loaders, [NotNullWhen(false)] out string? error) + { + AssetLoadOperation[] required = loaders.Where(p => p.Priority == AssetLoadPriority.Exclusive).ToArray(); + if (required.Length <= 1) + { + error = null; + return true; + } + + string[] loaderNames = required + .Select(p => p.Mod.DisplayName + this.GetOnBehalfOfLabel(p.OnBehalfOf)) + .OrderBy(p => p) + .Distinct() + .ToArray(); + string errorPhrase = loaderNames.Length > 1 + ? $"Multiple mods want to provide the '{info.Name}' asset: {string.Join(", ", loaderNames)}" + : $"The '{loaderNames[0]}' mod wants to provide the '{info.Name}' asset multiple times"; + + error = $"{errorPhrase}. An asset can't be loaded multiple times, so 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.)"; + return false; + } + + /// <summary>Get a parenthetical label for log messages for the content pack on whose behalf the action is being performed, if any.</summary> + /// <param name="onBehalfOf">The content pack on whose behalf the action is being performed.</param> + /// <param name="parenthetical">whether to format the label as a parenthetical shown after the mod name like <c> (for the 'X' content pack)</c>, instead of a standalone label like <c>the 'X' content pack</c>.</param> + /// <returns>Returns the on-behalf-of label if applicable, else <c>null</c>.</returns> + [return: NotNullIfNotNull("onBehalfOf")] + private string? GetOnBehalfOfLabel(IModMetadata? onBehalfOf, bool parenthetical = true) + { + if (onBehalfOf == null) + return null; + + return parenthetical + ? $" (for the '{onBehalfOf.Manifest.Name}' content pack)" + : $"the '{onBehalfOf.Manifest.Name}' content pack"; + } + /// <summary>Validate that an asset loaded by a mod is valid and won't cause issues, and fix issues if possible.</summary> /// <typeparam name="T">The asset type.</typeparam> /// <param name="info">The basic asset metadata.</param> /// <param name="data">The loaded asset data.</param> - /// <param name="mod">The mod which loaded the asset.</param> + /// <param name="loader">The loader which loaded the asset.</param> /// <returns>Returns whether the asset passed validation checks (after any fixes were applied).</returns> - private bool TryFixAndValidateLoadedAsset<T>(IAssetInfo info, T data, IModMetadata mod) + private bool TryFixAndValidateLoadedAsset<T>(IAssetInfo info, [NotNullWhen(true)] T? data, AssetLoadOperation loader) + where T : notnull { + IModMetadata mod = loader.Mod; + // can't load a null asset if (data == null) { - mod.LogAsMod($"SMAPI blocked asset replacement for '{info.AssetName}': mod incorrectly set asset to a null value.", LogLevel.Error); + mod.LogAsMod($"SMAPI blocked asset replacement for '{info.Name}': {this.GetOnBehalfOfLabel(loader.OnBehalfOf, parenthetical: false) ?? "mod"} incorrectly set asset to a null value.", LogLevel.Error); return false; } // when replacing a map, the vanilla tilesheets must have the same order and IDs if (data is Map loadedMap) { - TilesheetReference[] vanillaTilesheetRefs = this.Coordinator.GetVanillaTilesheetIds(info.AssetName); + TilesheetReference[] vanillaTilesheetRefs = this.Coordinator.GetVanillaTilesheetIds(info.Name.Name); foreach (TilesheetReference vanillaSheet in vanillaTilesheetRefs) { // add missing tilesheet if (loadedMap.GetTileSheet(vanillaSheet.Id) == null) { - mod.Monitor.LogOnce("SMAPI fixed maps loaded by this mod to prevent errors. See the log file for details.", LogLevel.Warn); - this.Monitor.Log($"Fixed broken map replacement: {mod.DisplayName} loaded '{info.AssetName}' without a required tilesheet (id: {vanillaSheet.Id}, source: {vanillaSheet.ImageSource})."); + mod.Monitor!.LogOnce("SMAPI fixed maps loaded by this mod to prevent errors. See the log file for details.", LogLevel.Warn); + this.Monitor.Log($"Fixed broken map replacement: {mod.DisplayName} loaded '{info.Name}' without a required tilesheet (id: {vanillaSheet.Id}, source: {vanillaSheet.ImageSource})."); loadedMap.AddTileSheet(new TileSheet(vanillaSheet.Id, loadedMap, vanillaSheet.ImageSource, vanillaSheet.SheetSize, vanillaSheet.TileSize)); } @@ -417,17 +353,17 @@ namespace StardewModdingAPI.Framework.ContentManagers { // only show warning if not farm map // This is temporary: mods shouldn't do this for any vanilla map, but these are the ones we know will crash. Showing a warning for others instead gives modders time to update their mods, while still simplifying troubleshooting. - bool isFarmMap = info.AssetNameEquals("Maps/Farm") || info.AssetNameEquals("Maps/Farm_Combat") || info.AssetNameEquals("Maps/Farm_Fishing") || info.AssetNameEquals("Maps/Farm_Foraging") || info.AssetNameEquals("Maps/Farm_FourCorners") || info.AssetNameEquals("Maps/Farm_Island") || info.AssetNameEquals("Maps/Farm_Mining"); + bool isFarmMap = info.Name.IsEquivalentTo("Maps/Farm") || info.Name.IsEquivalentTo("Maps/Farm_Combat") || info.Name.IsEquivalentTo("Maps/Farm_Fishing") || info.Name.IsEquivalentTo("Maps/Farm_Foraging") || info.Name.IsEquivalentTo("Maps/Farm_FourCorners") || info.Name.IsEquivalentTo("Maps/Farm_Island") || info.Name.IsEquivalentTo("Maps/Farm_Mining"); - string reason = $"mod reordered the original tilesheets, which {(isFarmMap ? "would cause a crash" : "often causes crashes")}.\nTechnical details for mod author: Expected order: {string.Join(", ", vanillaTilesheetRefs.Select(p => p.Id))}. See https://stardewvalleywiki.com/Modding:Maps#Tilesheet_order for help."; + string reason = $"{this.GetOnBehalfOfLabel(loader.OnBehalfOf, parenthetical: false) ?? "mod"} reordered the original tilesheets, which {(isFarmMap ? "would cause a crash" : "often causes crashes")}.\nTechnical details for mod author: Expected order: {string.Join(", ", vanillaTilesheetRefs.Select(p => p.Id))}. See https://stardewvalleywiki.com/Modding:Maps#Tilesheet_order for help."; SCore.DeprecationManager.PlaceholderWarn("3.8.2", DeprecationLevel.PendingRemoval); if (isFarmMap) { - mod.LogAsMod($"SMAPI blocked '{info.AssetName}' map load: {reason}", LogLevel.Error); + mod.LogAsMod($"SMAPI blocked a '{info.Name}' map load: {reason}", LogLevel.Error); return false; } - mod.LogAsMod($"SMAPI found an issue with '{info.AssetName}' map load: {reason}", LogLevel.Warn); + mod.LogAsMod($"SMAPI found an issue with a '{info.Name}' map load: {reason}", LogLevel.Warn); } } } diff --git a/src/SMAPI/Framework/ContentManagers/GameContentManagerForAssetPropagation.cs b/src/SMAPI/Framework/ContentManagers/GameContentManagerForAssetPropagation.cs index 61683ce6..1b0e1016 100644 --- a/src/SMAPI/Framework/ContentManagers/GameContentManagerForAssetPropagation.cs +++ b/src/SMAPI/Framework/ContentManagers/GameContentManagerForAssetPropagation.cs @@ -21,13 +21,13 @@ namespace StardewModdingAPI.Framework.ContentManagers ** Public methods *********/ /// <inheritdoc /> - public GameContentManagerForAssetPropagation(string name, IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, ContentCoordinator coordinator, IMonitor monitor, Reflector reflection, Action<BaseContentManager> onDisposing, Action onLoadingFirstAsset, bool aggressiveMemoryOptimizations) - : base(name, serviceProvider, rootDirectory, currentCulture, coordinator, monitor, reflection, onDisposing, onLoadingFirstAsset, aggressiveMemoryOptimizations) { } + public GameContentManagerForAssetPropagation(string name, IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, ContentCoordinator coordinator, IMonitor monitor, Reflector reflection, Action<BaseContentManager> onDisposing, Action onLoadingFirstAsset, Action<BaseContentManager, IAssetName> onAssetLoaded, bool aggressiveMemoryOptimizations) + : base(name, serviceProvider, rootDirectory, currentCulture, coordinator, monitor, reflection, onDisposing, onLoadingFirstAsset, onAssetLoaded, aggressiveMemoryOptimizations) { } /// <inheritdoc /> - public override T Load<T>(string assetName, LanguageCode language, bool useCache) + public override T LoadExact<T>(IAssetName assetName, bool useCache) { - T data = base.Load<T>(assetName, language, useCache); + T data = base.LoadExact<T>(assetName, useCache); if (data is Texture2D texture) texture.Tag = this.Tag; @@ -37,7 +37,7 @@ namespace StardewModdingAPI.Framework.ContentManagers /// <summary>Get whether a texture was loaded by this content manager.</summary> /// <param name="texture">The texture to check.</param> - public bool IsResponsibleFor(Texture2D texture) + public bool IsResponsibleFor(Texture2D? texture) { return texture?.Tag is string tag diff --git a/src/SMAPI/Framework/ContentManagers/IContentManager.cs b/src/SMAPI/Framework/ContentManagers/IContentManager.cs index d7963305..ac67cad5 100644 --- a/src/SMAPI/Framework/ContentManagers/IContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/IContentManager.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics.Contracts; using Microsoft.Xna.Framework.Content; using StardewModdingAPI.Framework.Exceptions; using StardewValley; @@ -29,22 +28,31 @@ namespace StardewModdingAPI.Framework.ContentManagers /********* ** Methods *********/ - /// <summary>Load an asset that has been processed by the content pipeline.</summary> + /// <summary>Get whether an asset exists and can be loaded.</summary> + /// <typeparam name="T">The expected asset type.</typeparam> + /// <param name="assetName">The normalized asset name.</param> + bool DoesAssetExist<T>(IAssetName assetName) + where T: notnull; + + /// <summary>Load an asset through the content pipeline, using a localized variant of the <paramref name="assetName"/> if available.</summary> /// <typeparam name="T">The type of asset to load.</typeparam> - /// <param name="assetName">The asset path relative to the loader root directory, not including the <c>.xnb</c> extension.</param> - /// <param name="language">The language code for which to load content.</param> + /// <param name="assetName">The asset name relative to the loader root directory.</param> + /// <param name="language">The language for which to load the asset.</param> /// <param name="useCache">Whether to read/write the loaded asset to the asset cache.</param> - T Load<T>(string assetName, LocalizedContentManager.LanguageCode language, bool useCache); + T LoadLocalized<T>(IAssetName assetName, LocalizedContentManager.LanguageCode language, bool useCache) + where T : notnull; - /// <summary>Normalize path separators in a file path. For asset keys, see <see cref="AssertAndNormalizeAssetName"/> instead.</summary> - /// <param name="path">The file path to normalize.</param> - [Pure] - string NormalizePathSeparators(string path); + /// <summary>Load an asset through the content pipeline, using the exact asset name without checking for localized variants.</summary> + /// <typeparam name="T">The type of asset to load.</typeparam> + /// <param name="assetName">The asset name relative to the loader root directory.</param> + /// <param name="useCache">Whether to read/write the loaded asset to the asset cache.</param> + T LoadExact<T>(IAssetName assetName, bool useCache) + where T : notnull; /// <summary>Assert that the given key has a valid format and return a normalized form consistent with the underlying cache.</summary> /// <param name="assetName">The asset key to check.</param> /// <exception cref="SContentLoadException">The asset key is empty or contains invalid characters.</exception> - string AssertAndNormalizeAssetName(string assetName); + string AssertAndNormalizeAssetName(string? assetName); /// <summary>Get the current content locale.</summary> string GetLocale(); @@ -55,19 +63,12 @@ namespace StardewModdingAPI.Framework.ContentManagers /// <summary>Get whether the content manager has already loaded and cached the given asset.</summary> /// <param name="assetName">The asset path relative to the loader root directory, not including the <c>.xnb</c> extension.</param> - /// <param name="language">The language.</param> - bool IsLoaded(string assetName, LocalizedContentManager.LanguageCode language); - - /// <summary>Get the cached asset keys.</summary> - IEnumerable<string> GetAssetKeys(); + bool IsLoaded(IAssetName assetName); /// <summary>Purge matched assets from the cache.</summary> /// <param name="predicate">Matches the asset keys to invalidate.</param> /// <param name="dispose">Whether to dispose invalidated assets. This should only be <c>true</c> when they're being invalidated as part of a dispose, to avoid crashing the game.</param> /// <returns>Returns the invalidated asset names and instances.</returns> IDictionary<string, object> InvalidateCache(Func<string, Type, bool> predicate, bool dispose = false); - - /// <summary>Perform any cleanup needed when the locale changes.</summary> - void OnLocaleChanged(); } } diff --git a/src/SMAPI/Framework/ContentManagers/ModContentManager.cs b/src/SMAPI/Framework/ContentManagers/ModContentManager.cs index beb90a5d..8f64c5a8 100644 --- a/src/SMAPI/Framework/ContentManagers/ModContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/ModContentManager.cs @@ -32,8 +32,8 @@ namespace StardewModdingAPI.Framework.ContentManagers /// <summary>The game content manager used for map tilesheets not provided by the mod.</summary> private readonly IContentManager GameContentManager; - /// <summary>The language code for language-agnostic mod assets.</summary> - private readonly LanguageCode DefaultLanguage = Constants.DefaultLanguage; + /// <summary>A case-insensitive lookup of relative paths within the <see cref="ContentManager.RootDirectory"/>.</summary> + private readonly CaseInsensitivePathLookup RelativePathCache; /// <summary>If a map tilesheet's image source has no file extensions, the file extensions to check for in the local mod folder.</summary> private readonly string[] LocalTilesheetExtensions = { ".png", ".xnb" }; @@ -55,33 +55,31 @@ namespace StardewModdingAPI.Framework.ContentManagers /// <param name="jsonHelper">Encapsulates SMAPI's JSON file parsing.</param> /// <param name="onDisposing">A callback to invoke when the content manager is being disposed.</param> /// <param name="aggressiveMemoryOptimizations">Whether to enable more aggressive memory optimizations.</param> - public ModContentManager(string name, IContentManager gameContentManager, IServiceProvider serviceProvider, string modName, string rootDirectory, CultureInfo currentCulture, ContentCoordinator coordinator, IMonitor monitor, Reflector reflection, JsonHelper jsonHelper, Action<BaseContentManager> onDisposing, bool aggressiveMemoryOptimizations) + /// <param name="relativePathCache">A case-insensitive lookup of relative paths within the <paramref name="rootDirectory"/>.</param> + public ModContentManager(string name, IContentManager gameContentManager, IServiceProvider serviceProvider, string modName, string rootDirectory, CultureInfo currentCulture, ContentCoordinator coordinator, IMonitor monitor, Reflector reflection, JsonHelper jsonHelper, Action<BaseContentManager> onDisposing, bool aggressiveMemoryOptimizations, CaseInsensitivePathLookup relativePathCache) : base(name, serviceProvider, rootDirectory, currentCulture, coordinator, monitor, reflection, onDisposing, isNamespaced: true, aggressiveMemoryOptimizations: aggressiveMemoryOptimizations) { this.GameContentManager = gameContentManager; + this.RelativePathCache = relativePathCache; this.JsonHelper = jsonHelper; this.ModName = modName; - } - /// <inheritdoc /> - public override T Load<T>(string assetName) - { - return this.Load<T>(assetName, this.DefaultLanguage, useCache: false); + this.TryLocalizeKeys = false; } /// <inheritdoc /> - public override T Load<T>(string assetName, LanguageCode language) + public override bool DoesAssetExist<T>(IAssetName assetName) { - return this.Load<T>(assetName, language, useCache: false); + if (base.DoesAssetExist<T>(assetName)) + return true; + + FileInfo file = this.GetModFile(assetName.Name); + return file.Exists; } /// <inheritdoc /> - public override T Load<T>(string assetName, LanguageCode language, bool useCache) + public override T LoadExact<T>(IAssetName assetName, bool useCache) { - // normalize key - bool isXnbFile = Path.GetExtension(assetName).ToLower() == ".xnb"; - assetName = this.AssertAndNormalizeAssetName(assetName); - // disable caching // This is necessary to avoid assets being shared between content managers, which can // cause changes to an asset through one content manager affecting the same asset in @@ -90,106 +88,43 @@ namespace StardewModdingAPI.Framework.ContentManagers if (useCache) throw new InvalidOperationException("Mod content managers don't support asset caching."); - // disable language handling - // Mod files don't support automatic translation logic, so this should never happen. - if (language != this.DefaultLanguage) - throw new InvalidOperationException("Localized assets aren't supported by the mod content manager."); - // resolve managed asset key { - if (this.Coordinator.TryParseManagedAssetKey(assetName, out string contentManagerID, out string relativePath)) + if (this.Coordinator.TryParseManagedAssetKey(assetName.Name, out string? contentManagerID, out IAssetName? relativePath)) { if (contentManagerID != this.Name) - throw new SContentLoadException($"Can't load managed asset key '{assetName}' through content manager '{this.Name}' for a different mod."); + throw this.GetLoadError(assetName, "can't load a different mod's managed asset key through this mod content manager."); assetName = relativePath; } } // get local asset - SContentLoadException GetContentError(string reasonPhrase) => new SContentLoadException($"Failed loading asset '{assetName}' from {this.Name}: {reasonPhrase}"); T asset; try { // get file - FileInfo file = this.GetModFile(isXnbFile ? $"{assetName}.xnb" : assetName); // .xnb extension is stripped from asset names passed to the content manager + FileInfo file = this.GetModFile(assetName.Name); if (!file.Exists) - throw GetContentError("the specified path doesn't exist."); + throw this.GetLoadError(assetName, "the specified path doesn't exist."); // load content - switch (file.Extension.ToLower()) + asset = file.Extension.ToLower() switch { - // XNB file - case ".xnb": - { - asset = this.RawLoad<T>(assetName, useCache: false); - if (asset is Map map) - { - map.assetPath = assetName; - this.FixTilesheetPaths(map, relativeMapPath: assetName, fixEagerPathPrefixes: true); - } - } - break; - - // unpacked Bitmap font - case ".fnt": - { - string source = File.ReadAllText(file.FullName); - asset = (T)(object)new XmlSource(source); - } - break; - - // unpacked data - case ".json": - { - if (!this.JsonHelper.ReadJsonFileIfExists(file.FullName, out asset)) - throw GetContentError("the JSON file is invalid."); // should never happen since we check for file existence above - } - break; - - // 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); - asset = (T)(object)texture; - } - break; - - // unpacked map - case ".tbin": - case ".tmx": - { - // validate - if (typeof(T) != typeof(Map)) - throw GetContentError($"can't read file with extension '{file.Extension}' as type '{typeof(T)}'; must be type '{typeof(Map)}'."); - - // fetch & cache - FormatManager formatManager = FormatManager.Instance; - Map map = formatManager.LoadMap(file.FullName); - map.assetPath = assetName; - this.FixTilesheetPaths(map, relativeMapPath: assetName, fixEagerPathPrefixes: false); - asset = (T)(object)map; - } - break; - - default: - throw GetContentError($"unknown file extension '{file.Extension}'; must be one of '.fnt', '.json', '.png', '.tbin', or '.xnb'."); - } + ".fnt" => this.LoadFont<T>(assetName, file), + ".json" => this.LoadDataFile<T>(assetName, file), + ".png" => this.LoadImageFile<T>(assetName, file), + ".tbin" or ".tmx" => this.LoadMapFile<T>(assetName, file), + ".xnb" => this.LoadXnbFile<T>(assetName), + _ => this.HandleUnknownFileType<T>(assetName, file) + }; } - catch (Exception ex) when (!(ex is SContentLoadException)) + catch (Exception ex) when (ex is not SContentLoadException) { - throw new SContentLoadException($"The content manager failed loading content asset '{assetName}' from {this.Name}.", ex); + throw this.GetLoadError(assetName, "an unexpected occurred.", ex); } // track & return asset - this.TrackAsset(assetName, asset, language, useCache); + this.TrackAsset(assetName, asset, useCache: false); return asset; } @@ -202,36 +137,137 @@ namespace StardewModdingAPI.Framework.ContentManagers /// <summary>Get the underlying key in the game's content cache for an asset. This does not validate whether the asset exists.</summary> /// <param name="key">The local path to a content file relative to the mod folder.</param> /// <exception cref="ArgumentException">The <paramref name="key"/> is empty or contains invalid characters.</exception> - public string GetInternalAssetKey(string key) + public IAssetName GetInternalAssetKey(string key) { FileInfo file = this.GetModFile(key); - string relativePath = PathUtilities.GetRelativePath(this.RootDirectory, file.FullName); - return Path.Combine(this.Name, relativePath); + string relativePath = Path.GetRelativePath(this.RootDirectory, file.FullName); + string internalKey = Path.Combine(this.Name, relativePath); + + return this.Coordinator.ParseAssetName(internalKey, allowLocales: false); } /********* ** Private methods *********/ - /// <inheritdoc /> - protected override bool IsNormalizedKeyLoaded(string normalizedAssetName, LanguageCode language) + /// <summary>Load an unpacked font file (<c>.fnt</c>).</summary> + /// <typeparam name="T">The type of asset to load.</typeparam> + /// <param name="assetName">The asset name relative to the loader root directory.</param> + /// <param name="file">The file to load.</param> + private T LoadFont<T>(IAssetName assetName, FileInfo file) { - return this.Cache.ContainsKey(normalizedAssetName); + // validate + if (!typeof(T).IsAssignableFrom(typeof(XmlSource))) + throw this.GetLoadError(assetName, $"can't read file with extension '{file.Extension}' as type '{typeof(T)}'; must be type '{typeof(XmlSource)}'."); + + // load + string source = File.ReadAllText(file.FullName); + return (T)(object)new XmlSource(source); + } + + /// <summary>Load an unpacked data file (<c>.json</c>).</summary> + /// <typeparam name="T">The type of asset to load.</typeparam> + /// <param name="assetName">The asset name relative to the loader root directory.</param> + /// <param name="file">The file to load.</param> + private T LoadDataFile<T>(IAssetName assetName, FileInfo file) + { + if (!this.JsonHelper.ReadJsonFileIfExists(file.FullName, out T? asset)) + throw this.GetLoadError(assetName, "the JSON file is invalid."); // should never happen since we check for file existence before calling this method + + return asset; + } + + /// <summary>Load an unpacked image file (<c>.json</c>).</summary> + /// <typeparam name="T">The type of asset to load.</typeparam> + /// <param name="assetName">The asset name relative to the loader root directory.</param> + /// <param name="file">The file to load.</param> + private T LoadImageFile<T>(IAssetName assetName, FileInfo file) + { + // validate + if (typeof(T) != typeof(Texture2D)) + throw this.GetLoadError(assetName, $"can't read file with extension '{file.Extension}' as type '{typeof(T)}'; must be type '{typeof(Texture2D)}'."); + + // load + using FileStream stream = File.OpenRead(file.FullName); + Texture2D texture = Texture2D.FromStream(Game1.graphics.GraphicsDevice, stream); + texture = this.PremultiplyTransparency(texture); + return (T)(object)texture; + } + + /// <summary>Load an unpacked image file (<c>.tbin</c> or <c>.tmx</c>).</summary> + /// <typeparam name="T">The type of asset to load.</typeparam> + /// <param name="assetName">The asset name relative to the loader root directory.</param> + /// <param name="file">The file to load.</param> + private T LoadMapFile<T>(IAssetName assetName, FileInfo file) + { + // validate + if (typeof(T) != typeof(Map)) + throw this.GetLoadError(assetName, $"can't read file with extension '{file.Extension}' as type '{typeof(T)}'; must be type '{typeof(Map)}'."); + + // load + FormatManager formatManager = FormatManager.Instance; + Map map = formatManager.LoadMap(file.FullName); + map.assetPath = assetName.Name; + this.FixTilesheetPaths(map, relativeMapPath: assetName.Name, fixEagerPathPrefixes: false); + return (T)(object)map; + } + + /// <summary>Load a packed file (<c>.xnb</c>).</summary> + /// <typeparam name="T">The type of asset to load.</typeparam> + /// <param name="assetName">The asset name relative to the loader root directory.</param> + private T LoadXnbFile<T>(IAssetName assetName) + { + // the underlying content manager adds a .xnb extension implicitly, so + // we need to strip it here to avoid trying to load a '.xnb.xnb' file. + IAssetName loadName = assetName.Name.EndsWith(".xnb", StringComparison.OrdinalIgnoreCase) + ? this.Coordinator.ParseAssetName(assetName.Name[..^".xnb".Length], allowLocales: false) + : assetName; + + // load asset + T asset = this.RawLoad<T>(loadName, useCache: false); + if (asset is Map map) + { + map.assetPath = loadName.Name; + this.FixTilesheetPaths(map, relativeMapPath: loadName.Name, fixEagerPathPrefixes: true); + } + + return asset; + } + + /// <summary>Handle a request to load a file type that isn't supported by SMAPI.</summary> + /// <typeparam name="T">The expected file type.</typeparam> + /// <param name="assetName">The asset name relative to the loader root directory.</param> + /// <param name="file">The file to load.</param> + private T HandleUnknownFileType<T>(IAssetName assetName, FileInfo file) + { + throw this.GetLoadError(assetName, $"unknown file extension '{file.Extension}'; must be one of '.fnt', '.json', '.png', '.tbin', '.tmx', or '.xnb'."); + } + + /// <summary>Get an error which indicates that an asset couldn't be loaded.</summary> + /// <param name="assetName">The asset name that failed to load.</param> + /// <param name="reasonPhrase">The reason the file couldn't be loaded.</param> + /// <param name="exception">The underlying exception, if applicable.</param> + private SContentLoadException GetLoadError(IAssetName assetName, string reasonPhrase, Exception? exception = null) + { + return new($"Failed loading asset '{assetName}' from {this.Name}: {reasonPhrase}", exception); } /// <summary>Get a file from the mod folder.</summary> /// <param name="path">The asset path relative to the content folder.</param> private FileInfo GetModFile(string path) { + // map to case-insensitive path if needed + path = this.RelativePathCache.GetFilePath(path); + // try exact match - FileInfo file = new FileInfo(Path.Combine(this.FullRootDirectory, path)); + FileInfo file = new(Path.Combine(this.FullRootDirectory, path)); // try with default extension - if (!file.Exists && file.Extension == string.Empty) + if (!file.Exists) { foreach (string extension in this.LocalTilesheetExtensions) { - FileInfo result = new FileInfo(file.FullName + extension); + FileInfo result = new(file.FullName + extension); if (result.Exists) { file = result; @@ -252,16 +288,20 @@ namespace StardewModdingAPI.Framework.ContentManagers // premultiply pixels Color[] data = new Color[texture.Width * texture.Height]; texture.GetData(data); + bool changed = false; for (int i = 0; i < data.Length; i++) { - var pixel = data[i]; - if (pixel.A == byte.MinValue || pixel.A == byte.MaxValue) + Color pixel = data[i]; + if (pixel.A is (byte.MinValue or byte.MaxValue)) continue; // no need to change fully transparent/opaque pixels data[i] = new Color(pixel.R * pixel.A / byte.MaxValue, pixel.G * pixel.A / byte.MaxValue, pixel.B * pixel.A / byte.MaxValue, pixel.A); // slower version: Color.FromNonPremultiplied(data[i].ToVector4()) + changed = true; } - texture.SetData(data); + if (changed) + texture.SetData(data); + return texture; } @@ -296,15 +336,18 @@ namespace StardewModdingAPI.Framework.ContentManagers // load best match try { - if (!this.TryGetTilesheetAssetName(relativeMapFolder, imageSource, out string assetName, out string error)) + if (!this.TryGetTilesheetAssetName(relativeMapFolder, imageSource, out IAssetName? assetName, out string? error)) throw new SContentLoadException($"{errorPrefix} {error}"); - if (assetName != tilesheet.ImageSource) - this.Monitor.VerboseLog($" Mapped tilesheet '{tilesheet.ImageSource}' to '{assetName}'."); + if (assetName is not null) + { + if (!assetName.IsEquivalentTo(tilesheet.ImageSource)) + this.Monitor.VerboseLog($" Mapped tilesheet '{tilesheet.ImageSource}' to '{assetName}'."); - tilesheet.ImageSource = assetName; + tilesheet.ImageSource = assetName.Name; + } } - catch (Exception ex) when (!(ex is SContentLoadException)) + catch (Exception ex) when (ex is not SContentLoadException) { throw new SContentLoadException($"{errorPrefix} The tilesheet couldn't be loaded.", ex); } @@ -318,7 +361,7 @@ namespace StardewModdingAPI.Framework.ContentManagers /// <param name="error">A message indicating why the file couldn't be loaded.</param> /// <returns>Returns whether the asset name was found.</returns> /// <remarks>See remarks on <see cref="FixTilesheetPaths"/>.</remarks> - private bool TryGetTilesheetAssetName(string modRelativeMapFolder, string relativePath, out string assetName, out string error) + private bool TryGetTilesheetAssetName(string modRelativeMapFolder, string relativePath, out IAssetName? assetName, out string? error) { assetName = null; error = null; @@ -326,7 +369,7 @@ namespace StardewModdingAPI.Framework.ContentManagers // nothing to do if (string.IsNullOrWhiteSpace(relativePath)) { - assetName = relativePath; + assetName = null; return true; } @@ -350,10 +393,10 @@ namespace StardewModdingAPI.Framework.ContentManagers } // get from game assets - string contentKey = this.GetContentKeyForTilesheetImageSource(relativePath); + IAssetName contentKey = this.Coordinator.ParseAssetName(this.GetContentKeyForTilesheetImageSource(relativePath), allowLocales: false); try { - this.GameContentManager.Load<Texture2D>(contentKey, this.Language, useCache: true); // no need to bypass cache here, since we're not storing the asset + this.GameContentManager.LoadLocalized<Texture2D>(contentKey, this.GameContentManager.Language, useCache: true); // no need to bypass cache here, since we're not storing the asset assetName = contentKey; return true; } @@ -366,7 +409,7 @@ namespace StardewModdingAPI.Framework.ContentManagers // if the content file doesn't exist, that doesn't mean the error here is a // content-not-found error. Unfortunately XNA doesn't provide a good way to // detect the error type. - if (this.GetContentFolderFileExists(contentKey)) + if (this.GetContentFolderFileExists(contentKey.Name)) throw; } |