ExtendedContentManager.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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. public class ExtendedContentManager : ContentManager
  19. {
  20. private List<IDisposable> _disposableAssets;
  21. private readonly IGraphicsDeviceService _graphicsDeviceService;
  22. public List<IDisposable> DisposeableAssets
  23. {
  24. get
  25. {
  26. if (_disposableAssets is null)
  27. {
  28. // MonoGame please make this protected so subclass have access plz
  29. FieldInfo field = typeof(ContentManager).GetField(nameof(_disposableAssets), BindingFlags.NonPublic | BindingFlags.Instance);
  30. if (field is null)
  31. {
  32. throw new InvalidOperationException("Unable to get source disposable assets field");
  33. }
  34. _disposableAssets = field.GetValue(this) as List<IDisposable>;
  35. }
  36. return _disposableAssets;
  37. }
  38. }
  39. #if KNI || FNA
  40. private Dictionary<string, object> _loadedAssets;
  41. public Dictionary<string, object> LoadedAssets
  42. {
  43. get
  44. {
  45. if(_loadedAssets is null)
  46. {
  47. // KNI please make this public so I don't have to use reflection
  48. FieldInfo field = typeof(ContentManager).GetField(nameof(_loadedAssets), BindingFlags.NonPublic | BindingFlags.Instance);
  49. if (field is null)
  50. {
  51. throw new InvalidOperationException("Unable to get source loaded assets field");
  52. }
  53. _loadedAssets = field.GetValue(this) as Dictionary<string, object>;
  54. }
  55. return _loadedAssets;
  56. }
  57. }
  58. #endif
  59. public ExtendedContentManager(IServiceProvider serviceProvider) : base(serviceProvider)
  60. {
  61. _graphicsDeviceService = serviceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
  62. }
  63. public ExtendedContentManager(IServiceProvider serviceProvider, string rootDirectory) : base(serviceProvider, rootDirectory)
  64. {
  65. _graphicsDeviceService = serviceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
  66. }
  67. #if KNI || FNA
  68. /// <summary>
  69. /// Loads a <see cref="Texture2D"/> asset.
  70. /// </summary>
  71. /// <remarks>
  72. /// If the <paramref name="path"/> parameter is a relative path, it must be relative to the
  73. /// <see cref="ContentManager.RootDirectory"/> path.
  74. /// </remarks>
  75. /// <param name="path">The path to the asset to load</param>
  76. /// <param name="premultiplyAlpha">
  77. /// Specifies whether the color data of the texture should be premultiplied by its alpha value.
  78. /// </param>
  79. /// <returns></returns>
  80. public Texture2D LoadTexture2D(string path)
  81. {
  82. if (TryGetCachedAsset<Texture2D>(path, out Texture2D texture))
  83. {
  84. return texture;
  85. }
  86. if (NoExtension(path))
  87. {
  88. return Load<Texture2D>(path);
  89. }
  90. using Stream stream = GetStream(path);
  91. texture = Texture2D.FromStream(_graphicsDeviceService.GraphicsDevice, stream);
  92. texture.Name = path;
  93. CacheAsset(path, texture);
  94. return texture;
  95. }
  96. #else
  97. /// <summary>
  98. /// Loads a <see cref="Texture2D"/> asset.
  99. /// </summary>
  100. /// <remarks>
  101. /// If the <paramref name="path"/> parameter is a relative path, it must be relative to the
  102. /// <see cref="ContentManager.RootDirectory"/> path.
  103. /// </remarks>
  104. /// <param name="path">The path to the asset to load</param>
  105. /// <returns>The <see cref="Texture2D"/> loaded.</returns>
  106. public Texture2D LoadTexture2D(string path) => LoadTexture2D(path, true);
  107. /// <summary>
  108. /// Loads a <see cref="Texture2D"/> asset.
  109. /// </summary>
  110. /// <remarks>
  111. /// If the <paramref name="path"/> parameter is a relative path, it must be relative to the
  112. /// <see cref="ContentManager.RootDirectory"/> path.
  113. /// </remarks>
  114. /// <param name="path">The path to the asset to load</param>
  115. /// <param name="premultiplyAlpha">
  116. /// Specifies whether the color data of the texture should be premultiplied by its alpha value.
  117. /// </param>
  118. /// <returns></returns>
  119. public Texture2D LoadTexture2D(string path, bool premultiplyAlpha)
  120. {
  121. if (TryGetCachedAsset<Texture2D>(path, out Texture2D texture))
  122. {
  123. return texture;
  124. }
  125. if (NoExtension(path))
  126. {
  127. return Load<Texture2D>(path);
  128. }
  129. using Stream stream = GetStream(path);
  130. texture = premultiplyAlpha
  131. ? Texture2D.FromStream(_graphicsDeviceService.GraphicsDevice, stream)
  132. : Texture2D.FromStream(_graphicsDeviceService.GraphicsDevice, stream, DefaultColorProcessors.PremultiplyAlpha);
  133. texture.Name = path;
  134. CacheAsset(path, texture);
  135. return texture;
  136. }
  137. #endif
  138. /// <summary>
  139. /// Loads a <see cref="SoundEffect"/> asset.
  140. /// </summary>
  141. /// <remarks>
  142. /// If the <paramref name="path"/> parameter is a relative path, it must be relative to the
  143. /// <see cref="ContentManager.RootDirectory"/> path.
  144. /// </remarks>
  145. /// <param name="path">The path to the asset to load</param>
  146. /// <returns>The <see cref="SoundEffect"/> loaded.</returns>
  147. public SoundEffect LoadSoundEffect(string path)
  148. {
  149. if (TryGetCachedAsset<SoundEffect>(path, out SoundEffect soundEffect))
  150. {
  151. return soundEffect;
  152. }
  153. if (NoExtension(path))
  154. {
  155. return Load<SoundEffect>(path);
  156. }
  157. using Stream stream = GetStream(path);
  158. soundEffect = SoundEffect.FromStream(stream);
  159. soundEffect.Name = path;
  160. CacheAsset(path, soundEffect);
  161. return soundEffect;
  162. }
  163. /// <summary>
  164. /// Loads a <see cref="BitmapFont"/> asset.
  165. /// </summary>
  166. /// <remarks>
  167. /// If the <paramref name="path"/> parameter is a relative path, it must be relative to the
  168. /// <see cref="ContentManager.RootDirectory"/> path.
  169. /// </remarks>
  170. /// <param name="path">The path to the asset to load.</param>
  171. /// <returns>The <see cref="BitmapFont"/> loaded.</returns>
  172. public BitmapFont LoadBitmapFont(string path)
  173. {
  174. if (TryGetCachedAsset<BitmapFont>(path, out BitmapFont font))
  175. {
  176. return font;
  177. }
  178. if (NoExtension(path))
  179. {
  180. return Load<BitmapFont>(path);
  181. }
  182. using FileStream stream = GetStream(path);
  183. var bmfFile = BitmapFontFileReader.Read(stream);
  184. var textures =
  185. bmfFile.Pages.Select(page => LoadTexture2D(Path.GetRelativePath(path, page)))
  186. .ToArray();
  187. var characters = new Dictionary<int, BitmapFontCharacter>();
  188. foreach (var charBlock in bmfFile.Characters)
  189. {
  190. var texture = textures[charBlock.Page];
  191. var region = new Texture2DRegion(texture, charBlock.X, charBlock.Y, charBlock.Width, charBlock.Height);
  192. var character = new BitmapFontCharacter((int)charBlock.ID, region, charBlock.XOffset, charBlock.YOffset, charBlock.XAdvance);
  193. characters.Add(character.Character, character);
  194. }
  195. foreach (var kerningBlock in bmfFile.Kernings)
  196. {
  197. if (characters.TryGetValue((int)kerningBlock.First, out var character))
  198. {
  199. character.Kernings.Add((int)kerningBlock.Second, kerningBlock.Amount);
  200. }
  201. }
  202. var bmfFont = new BitmapFont(bmfFile.FontName, bmfFile.Info.FontSize, bmfFile.Common.LineHeight, characters.Values);
  203. CacheAsset(path, font);
  204. return font;
  205. }
  206. /// <summary>
  207. /// Loads a <see cref="Texture2DAtlas"/> from a TexturePacker JSON file.
  208. /// </summary>
  209. /// <param name="path">The path to the TexturePacker JSON file</param>
  210. #if !KNI && !FNA
  211. /// <param name="premultiplyAlpha">
  212. /// Specifies whether the color data of the texture should be premultiplied by its alpha value.
  213. /// </param>
  214. #endif
  215. /// <returns>The <see cref="Texture2DAtlas"/> created from the TexturePacker JSON file content.</returns>
  216. #if KNI || FNA
  217. public Texture2DAtlas LoadTexturePacker(string path)
  218. #else
  219. public Texture2DAtlas LoadTexturePacker(string path, bool premultiplyAlpha)
  220. #endif
  221. {
  222. if (TryGetCachedAsset<Texture2DAtlas>(path, out var atlas))
  223. {
  224. return atlas;
  225. }
  226. if (NoExtension(path))
  227. {
  228. return Load<Texture2DAtlas>(path);
  229. }
  230. using var stream = GetStream(path);
  231. var tpFile = TexturePackerFileReader.Read(stream);
  232. var dir = Path.GetDirectoryName(path);
  233. var imageAssetPath = Path.Combine(dir, tpFile.Meta.Image);
  234. #if KNI || FNA
  235. var texture = LoadTexture2D(imageAssetPath);
  236. #else
  237. var texture = LoadTexture2D(imageAssetPath, premultiplyAlpha);
  238. #endif
  239. atlas = new Texture2DAtlas(Path.GetFileNameWithoutExtension(tpFile.Meta.Image), texture);
  240. foreach(var region in tpFile.Regions)
  241. {
  242. var frame = region.Frame;
  243. atlas.CreateRegion(frame.X, frame.Y, frame.Width, frame.Height, Path.GetFileNameWithoutExtension(region.FileName));
  244. }
  245. CacheAsset(path, atlas);
  246. return atlas;
  247. }
  248. private FileStream GetStream(string path)
  249. {
  250. if (Path.IsPathRooted(path))
  251. {
  252. return File.OpenRead(path);
  253. }
  254. return (FileStream)TitleContainer.OpenStream(path);
  255. }
  256. private void CacheAsset(string name, object obj)
  257. {
  258. LoadedAssets.Add(name, obj);
  259. if (obj is IDisposable disposable)
  260. {
  261. DisposeableAssets.Add(disposable);
  262. }
  263. }
  264. private bool NoExtension(string name) => string.IsNullOrEmpty(Path.GetExtension(name));
  265. private bool TryGetCachedAsset<T>(string name, out T asset)
  266. {
  267. asset = default;
  268. if (LoadedAssets.TryGetValue(name, out object value))
  269. {
  270. if (value is T)
  271. {
  272. asset = (T)value;
  273. return true;
  274. }
  275. }
  276. return false;
  277. }
  278. }