ExtendedContentManager.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. // Copyright (c) Craftwork Games. All rights reserved.
  2. // Licensed under the MIT license.
  3. // See LICENSE file in the project root for full license information.
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Reflection;
  9. using Microsoft.Xna.Framework;
  10. using Microsoft.Xna.Framework.Audio;
  11. using Microsoft.Xna.Framework.Content;
  12. using Microsoft.Xna.Framework.Graphics;
  13. using MonoGame.Extended.BitmapFonts;
  14. using MonoGame.Extended.Content.BitmapFonts;
  15. using MonoGame.Extended.Content.TexturePacker;
  16. using MonoGame.Extended.Graphics;
  17. namespace MonoGame.Extended.Content;
  18. /// <summary>
  19. /// Extends the <see cref="ContentManager"/> to provide additional loading functionality and additional asset types
  20. /// </summary>
  21. public class ExtendedContentManager : ContentManager
  22. {
  23. private List<IDisposable> _disposableAssets;
  24. private readonly IGraphicsDeviceService _graphicsDeviceService;
  25. /// <summary>
  26. /// Gets the collection of loaded disposable assets that will be disposed when this content manager is disposed.
  27. /// </summary>
  28. public List<IDisposable> DisposeableAssets
  29. {
  30. get
  31. {
  32. if (_disposableAssets is null)
  33. {
  34. // MonoGame please make this protected so subclass have access plz
  35. FieldInfo field = typeof(ContentManager).GetField(nameof(_disposableAssets), BindingFlags.NonPublic | BindingFlags.Instance);
  36. if (field is null)
  37. {
  38. throw new InvalidOperationException("Unable to get source disposable assets field");
  39. }
  40. _disposableAssets = field.GetValue(this) as List<IDisposable>;
  41. }
  42. return _disposableAssets;
  43. }
  44. }
  45. #if KNI || FNA
  46. private Dictionary<string, object> _loadedAssets;
  47. /// <summary>
  48. /// Gets the dictionary of loaded assets keyed by asset name.
  49. /// </summary>
  50. public Dictionary<string, object> LoadedAssets
  51. {
  52. get
  53. {
  54. if(_loadedAssets is null)
  55. {
  56. // KNI please make this public so I don't have to use reflection
  57. FieldInfo field = typeof(ContentManager).GetField(nameof(_loadedAssets), BindingFlags.NonPublic | BindingFlags.Instance);
  58. if (field is null)
  59. {
  60. throw new InvalidOperationException("Unable to get source loaded assets field");
  61. }
  62. _loadedAssets = field.GetValue(this) as Dictionary<string, object>;
  63. }
  64. return _loadedAssets;
  65. }
  66. }
  67. #endif
  68. /// <summary>
  69. /// Initializes a new instance of the <see cref="ExtendedContentManager"/> class.
  70. /// </summary>
  71. /// <remarks>
  72. /// By default, the content manager searches for content in the directory where the executable is located.
  73. /// </remarks>
  74. /// <param name="serviceProvider">The service provided used for resolving services.</param>
  75. /// <exception cref="ArgumentNullException">
  76. /// Thrown when <paramref name="serviceProvider"/> is <see langword="null"/>.
  77. /// </exception>
  78. public ExtendedContentManager(IServiceProvider serviceProvider) : base(serviceProvider)
  79. {
  80. _graphicsDeviceService = serviceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
  81. }
  82. /// <summary>
  83. /// Initializes a new instance of the <see cref="ExtendedContentManager"/> class with a specified root directory.
  84. /// </summary>
  85. /// <param name="serviceProvider">The service provider to use for resolving services.</param>
  86. /// <param name="rootDirectory">The root directory the content manager will search for content in.</param>
  87. public ExtendedContentManager(IServiceProvider serviceProvider, string rootDirectory) : base(serviceProvider, rootDirectory)
  88. {
  89. _graphicsDeviceService = serviceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
  90. }
  91. #if KNI || FNA
  92. /// <summary>
  93. /// Loads a <see cref="Texture2D"/> asset.
  94. /// </summary>
  95. /// <remarks>
  96. /// If the <paramref name="path"/> parameter is a relative path, it must be relative to the
  97. /// <see cref="ContentManager.RootDirectory"/> path.
  98. /// </remarks>
  99. /// <param name="path">The path to the asset to load</param>
  100. /// <param name="premultiplyAlpha">
  101. /// Specifies whether the color data of the texture should be premultiplied by its alpha value.
  102. /// </param>
  103. /// <returns>The <see cref="Texture2D"/> loaded. </returns>
  104. public Texture2D LoadTexture2D(string path)
  105. {
  106. if (TryGetCachedAsset<Texture2D>(path, out Texture2D texture))
  107. {
  108. return texture;
  109. }
  110. if (NoExtension(path))
  111. {
  112. return Load<Texture2D>(path);
  113. }
  114. using Stream stream = GetStream(path);
  115. texture = Texture2D.FromStream(_graphicsDeviceService.GraphicsDevice, stream);
  116. texture.Name = path;
  117. CacheAsset(path, texture);
  118. return texture;
  119. }
  120. #else
  121. /// <summary>
  122. /// Loads a <see cref="Texture2D"/> asset.
  123. /// </summary>
  124. /// <remarks>
  125. /// If the <paramref name="path"/> parameter is a relative path, it must be relative to the
  126. /// <see cref="ContentManager.RootDirectory"/> path.
  127. /// </remarks>
  128. /// <param name="path">The path to the asset to load</param>
  129. /// <returns>The <see cref="Texture2D"/> loaded.</returns>
  130. public Texture2D LoadTexture2D(string path) => LoadTexture2D(path, true);
  131. /// <summary>
  132. /// Loads a <see cref="Texture2D"/> asset.
  133. /// </summary>
  134. /// <remarks>
  135. /// If the <paramref name="path"/> parameter is a relative path, it must be relative to the
  136. /// <see cref="ContentManager.RootDirectory"/> path.
  137. /// </remarks>
  138. /// <param name="path">The path to the asset to load</param>
  139. /// <param name="premultiplyAlpha">
  140. /// Specifies whether the color data of the texture should be premultiplied by its alpha value.
  141. /// </param>
  142. /// <returns>The <see cref="Texture2D"/> loaded.</returns>
  143. public Texture2D LoadTexture2D(string path, bool premultiplyAlpha)
  144. {
  145. if (TryGetCachedAsset<Texture2D>(path, out Texture2D texture))
  146. {
  147. return texture;
  148. }
  149. if (NoExtension(path))
  150. {
  151. return Load<Texture2D>(path);
  152. }
  153. using Stream stream = GetStream(path);
  154. texture = premultiplyAlpha
  155. ? Texture2D.FromStream(_graphicsDeviceService.GraphicsDevice, stream)
  156. : Texture2D.FromStream(_graphicsDeviceService.GraphicsDevice, stream, DefaultColorProcessors.PremultiplyAlpha);
  157. texture.Name = path;
  158. CacheAsset(path, texture);
  159. return texture;
  160. }
  161. #endif
  162. /// <summary>
  163. /// Loads a <see cref="SoundEffect"/> asset.
  164. /// </summary>
  165. /// <remarks>
  166. /// If the <paramref name="path"/> parameter is a relative path, it must be relative to the
  167. /// <see cref="ContentManager.RootDirectory"/> path.
  168. /// </remarks>
  169. /// <param name="path">The path to the asset to load</param>
  170. /// <returns>The <see cref="SoundEffect"/> loaded.</returns>
  171. public SoundEffect LoadSoundEffect(string path)
  172. {
  173. if (TryGetCachedAsset<SoundEffect>(path, out SoundEffect soundEffect))
  174. {
  175. return soundEffect;
  176. }
  177. if (NoExtension(path))
  178. {
  179. return Load<SoundEffect>(path);
  180. }
  181. using Stream stream = GetStream(path);
  182. soundEffect = SoundEffect.FromStream(stream);
  183. soundEffect.Name = path;
  184. CacheAsset(path, soundEffect);
  185. return soundEffect;
  186. }
  187. /// <summary>
  188. /// Loads a <see cref="BitmapFont"/> asset.
  189. /// </summary>
  190. /// <remarks>
  191. /// If the <paramref name="path"/> parameter is a relative path, it must be relative to the
  192. /// <see cref="ContentManager.RootDirectory"/> path.
  193. /// </remarks>
  194. /// <param name="path">The path to the asset to load.</param>
  195. /// <returns>The <see cref="BitmapFont"/> loaded.</returns>
  196. public BitmapFont LoadBitmapFont(string path)
  197. {
  198. if (TryGetCachedAsset<BitmapFont>(path, out BitmapFont font))
  199. {
  200. return font;
  201. }
  202. if (NoExtension(path))
  203. {
  204. return Load<BitmapFont>(path);
  205. }
  206. using FileStream stream = GetStream(path);
  207. var bmfFile = BitmapFontFileReader.Read(stream);
  208. var textures =
  209. bmfFile.Pages.Select(page => LoadTexture2D(Path.GetRelativePath(path, page)))
  210. .ToArray();
  211. var characters = new Dictionary<int, BitmapFontCharacter>();
  212. foreach (var charBlock in bmfFile.Characters)
  213. {
  214. var texture = textures[charBlock.Page];
  215. var region = new Texture2DRegion(texture, charBlock.X, charBlock.Y, charBlock.Width, charBlock.Height);
  216. var character = new BitmapFontCharacter((int)charBlock.ID, region, charBlock.XOffset, charBlock.YOffset, charBlock.XAdvance);
  217. characters.Add(character.Character, character);
  218. }
  219. foreach (var kerningBlock in bmfFile.Kernings)
  220. {
  221. if (characters.TryGetValue((int)kerningBlock.First, out var character))
  222. {
  223. character.Kernings.Add((int)kerningBlock.Second, kerningBlock.Amount);
  224. }
  225. }
  226. var bmfFont = new BitmapFont(bmfFile.FontName, bmfFile.Info.FontSize, bmfFile.Common.LineHeight, characters.Values);
  227. CacheAsset(path, font);
  228. return font;
  229. }
  230. #if KNI || FNA
  231. /// <summary>
  232. /// Loads a <see cref="Texture2DAtlas"/> from a TexturePacker JSON file.
  233. /// <summary>
  234. /// <param name="path">The path to the TexturePacker JSON file</param>
  235. /// <returns>The <see cref="Texture2DAtlas"/> created from the TexturePacker JSON file content.</returns>
  236. public Texture2DAtlas LoadTexturePacker(string path)
  237. #else
  238. /// <summary>
  239. /// Loads a <see cref="Texture2DAtlas"/> from a TexturePacker JSON file.
  240. /// </summary>
  241. /// <param name="path">The path to the TexturePacker JSON file</param>
  242. /// <param name="premultiplyAlpha">
  243. /// Specifies whether the color data of the texture should be premultiplied by its alpha value.
  244. /// </param>
  245. /// <returns>The <see cref="Texture2DAtlas"/> created from the TexturePacker JSON file content.</returns>
  246. public Texture2DAtlas LoadTexturePacker(string path, bool premultiplyAlpha)
  247. #endif
  248. {
  249. if (TryGetCachedAsset<Texture2DAtlas>(path, out var atlas))
  250. {
  251. return atlas;
  252. }
  253. if (NoExtension(path))
  254. {
  255. return Load<Texture2DAtlas>(path);
  256. }
  257. using var stream = GetStream(path);
  258. var tpFile = TexturePackerFileReader.Read(stream);
  259. var dir = Path.GetDirectoryName(path);
  260. var imageAssetPath = Path.Combine(dir, tpFile.Meta.Image);
  261. #if KNI || FNA
  262. var texture = LoadTexture2D(imageAssetPath);
  263. #else
  264. var texture = LoadTexture2D(imageAssetPath, premultiplyAlpha);
  265. #endif
  266. atlas = new Texture2DAtlas(Path.GetFileNameWithoutExtension(tpFile.Meta.Image), texture);
  267. foreach (var region in tpFile.Regions)
  268. {
  269. var frame = region.Frame;
  270. atlas.CreateRegion(frame.X, frame.Y, frame.Width, frame.Height, Path.GetFileNameWithoutExtension(region.FileName));
  271. }
  272. CacheAsset(path, atlas);
  273. return atlas;
  274. }
  275. /// <summary>
  276. /// Opens a file stream for the specified asset path.
  277. /// </summary>
  278. /// <remarks>
  279. /// The <paramref name="path"/> argument can be either an absolute or relative path. When it is a relative path, it
  280. /// is resolved using <see cref="TitleContainer"/>.
  281. /// </remarks>
  282. /// <param name="path">The path to the asset file.</param>
  283. /// <returns>A <see cref="FileStream"/> for reading the asset file.</returns>
  284. protected FileStream GetStream(string path)
  285. {
  286. if (Path.IsPathRooted(path))
  287. {
  288. return File.OpenRead(path);
  289. }
  290. return (FileStream)TitleContainer.OpenStream(path);
  291. }
  292. /// <summary>
  293. /// Caches a loaded asset in the loaded assets dictionary/
  294. /// </summary>
  295. /// <remarks>
  296. /// Assets that implement <see cref="IDisposable"/> are registered with the <see cref="DisposeableAssets"/>
  297. /// collection for automatic disposal.
  298. /// </remarks>
  299. /// <param name="name">The cache key for the asset, typically the asset path.</param>
  300. /// <param name="obj">The asset instance to cache.</param>
  301. protected void CacheAsset(string name, object obj)
  302. {
  303. LoadedAssets.Add(name, obj);
  304. if (obj is IDisposable disposable)
  305. {
  306. DisposeableAssets.Add(disposable);
  307. }
  308. }
  309. /// <summary>
  310. /// Determines whether the specified asset name has no file extension.
  311. /// </summary>
  312. /// <param name="name">The asset name to check.</param>
  313. /// <returns>
  314. /// <see langword="true"/> if the name has no extension or the extension is empty; otherwise, <see langword="false"/>.
  315. /// </returns>
  316. protected bool NoExtension(string name) => string.IsNullOrEmpty(Path.GetExtension(name));
  317. /// <summary>
  318. /// Attempts to retrieve a previously cached asset of the specified type.
  319. /// </summary>
  320. /// <typeparam name="T">The expected type of the cached asset.</typeparam>
  321. /// <param name="name">The cache key for the asset, typically the asset path.</param>
  322. /// <param name="asset">
  323. /// When this method returns, contains the cached asset if found and of type <typeparamref name="T"/>; otherwise,
  324. /// the default value for <typeparamref name="T"/>.
  325. /// </param>
  326. /// <returns>
  327. /// <see langword="true"/> if a cached asset of type <typeparamref name="T"/> was found; otherwise, <see langword="false"/>.
  328. /// </returns>
  329. protected bool TryGetCachedAsset<T>(string name, out T asset)
  330. {
  331. asset = default;
  332. if (LoadedAssets.TryGetValue(name, out object value))
  333. {
  334. if (value is T)
  335. {
  336. asset = (T)value;
  337. return true;
  338. }
  339. }
  340. return false;
  341. }
  342. }