Texture2DAtlas.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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;
  6. using System.Collections.Generic;
  7. using Microsoft.Xna.Framework;
  8. using Microsoft.Xna.Framework.Graphics;
  9. using MonoGame.Extended.Animations;
  10. namespace MonoGame.Extended.Graphics;
  11. /// <summary>
  12. /// Represents a 2D texture atlas that contains a collection of texture regions.
  13. /// </summary>
  14. /// <remarks>
  15. /// <para>
  16. /// A texture atlas, also known as a tile map, tile engine, or sprite sheet, is a large image that contains a
  17. /// collection of sub-images, or "textures", each representing a texture map for a specific part of a 2D or 3D model.
  18. /// </para>
  19. /// <para>
  20. /// These sub-textures can be rendered by adjusting the texture coordinates (UV map) to reference the appropriate
  21. /// part of the atlas. This technique allows efficient rendering in applications where many small textures are
  22. /// frequently used.
  23. /// </para>
  24. /// <para>
  25. /// By storing textures in a single atlas, the graphics hardware treats them as a single unit, which can save memory
  26. /// and improve performance by reducing the number of rendering state changes. Binding one large texture once is
  27. /// typically faster than binding multiple smaller textures individually.
  28. /// </para>
  29. /// <para>
  30. /// However, careful alignment is necessary to avoid texture bleeding when using mipmapping, and to prevent artifacts
  31. /// between tiles when using texture compression.
  32. /// </para>
  33. /// </remarks>
  34. public class Texture2DAtlas : IEnumerable<Texture2DRegion>
  35. {
  36. private readonly List<Texture2DRegion> _regionsByIndex = new List<Texture2DRegion>();
  37. private readonly Dictionary<string, Texture2DRegion> _regionsByName = new Dictionary<string, Texture2DRegion>();
  38. /// <summary>
  39. /// Gets the name of the texture atlas.
  40. /// </summary>
  41. public string Name { get; }
  42. /// <summary>
  43. /// Gets the underlying 2D texture.
  44. /// </summary>
  45. public Texture2D Texture { get; }
  46. /// <summary>
  47. /// Gets the number of regions in the atlas.
  48. /// </summary>
  49. public int RegionCount => _regionsByIndex.Count;
  50. /// <summary>
  51. /// Gets the <see cref="Texture2DRegion"/> at the specified index.
  52. /// </summary>
  53. /// <param name="index">The index of the texture region.</param>
  54. /// <returns>The texture region at the specified index.</returns>
  55. /// <exception cref="ArgumentOutOfRangeException">
  56. /// Thrown if the value of the <paramref name="index"/> parameter is less than zero or greater than or equal to
  57. /// the total number of regions in this atlas.
  58. /// </exception>
  59. public Texture2DRegion this[int index] => GetRegion(index);
  60. /// <summary>
  61. /// Gets the <see cref="Texture2DRegion"/> with the specified name.
  62. /// </summary>
  63. /// <param name="name">The name of the texture region.</param>
  64. /// <returns>The texture region with the specified name.</returns>
  65. /// <exception cref="KeyNotFoundException">
  66. /// Thrown if this atlas does not contain a region with a name that matches the <paramref name="name"/> parameter.
  67. /// </exception>
  68. public Texture2DRegion this[string name] => GetRegion(name);
  69. /// <summary>
  70. /// Initializes a new instance of the <see cref="Texture2DAtlas"/> class with the specified texture.
  71. /// </summary>
  72. /// <param name="texture">The texture to create the atlas from.</param>
  73. /// <exception cref="ArgumentNullException">Thrown if <paramref name="texture"/> is null.</exception>
  74. /// <exception cref="ObjectDisposedException">Thrown if <paramref name="texture"/> is disposed.</exception>
  75. public Texture2DAtlas(Texture2D texture) : this(null, texture) { }
  76. /// <summary>
  77. /// Initializes a new instance of the <see cref="Texture2DAtlas"/> class with the specified name and texture.
  78. /// </summary>
  79. /// <param name="name">The name of the texture atlas.</param>
  80. /// <param name="texture">The texture to create the atlas from.</param>
  81. /// <exception cref="ArgumentNullException">Thrown if <paramref name="texture"/> is null.</exception>
  82. /// <exception cref="ObjectDisposedException">Thrown if <paramref name="texture"/> is disposed.</exception>
  83. public Texture2DAtlas(string name, Texture2D texture)
  84. {
  85. ArgumentNullException.ThrowIfNull(texture);
  86. if (texture.IsDisposed)
  87. {
  88. throw new ObjectDisposedException(nameof(texture), $"{nameof(texture)} was disposed prior");
  89. }
  90. if (string.IsNullOrEmpty(name))
  91. {
  92. name = $"{texture.Name}Atlas";
  93. }
  94. Name = name;
  95. Texture = texture;
  96. }
  97. /// <summary>
  98. /// Creates a new texture region and adds it to this atlas.
  99. /// </summary>
  100. /// <param name="x">The x-coordinate of the region.</param>
  101. /// <param name="y">The y-coordinate of the region.</param>
  102. /// <param name="width">The width, in pixels, of the region.</param>
  103. /// <param name="height">The height, in pixels, of the region.</param>
  104. /// <returns>The created texture region.</returns>
  105. public Texture2DRegion CreateRegion(int x, int y, int width, int height) => CreateRegion(new Rectangle(x, y, width, height), null);
  106. /// <summary>
  107. /// Creates a new texture region with the specified name and adds it to this atlas.
  108. /// </summary>
  109. /// <param name="x">The x-coordinate of the region.</param>
  110. /// <param name="y">The y-coordinate of the region.</param>
  111. /// <param name="width">The width, in pixels, of the region.</param>
  112. /// <param name="height">The height, in pixels, of the region.</param>
  113. /// <param name="name">The name of the texture region.</param>
  114. /// <returns>The created texture region.</returns>
  115. /// <exception cref="InvalidOperationException">
  116. /// Thrown if a region with the same name as the <paramref name="name"/> parameter already exists in this atlas.
  117. /// </exception>
  118. public Texture2DRegion CreateRegion(int x, int y, int width, int height, string name) => CreateRegion(new Rectangle(x, y, width, height), name);
  119. /// <summary>
  120. /// Creates a new texture region and adds it to this atlas.
  121. /// </summary>
  122. /// <param name="location">The location of the region.</param>
  123. /// <param name="size">The size, in pixels, of the region.</param>
  124. /// <returns>The created texture region.</returns>
  125. public Texture2DRegion CreateRegion(Point location, Size size) => CreateRegion(new Rectangle(location.X, location.Y, size.Width, size.Height), null);
  126. /// <summary>
  127. /// Creates a new texture region with the specified name and adds it to this atlas.
  128. /// </summary>
  129. /// <param name="location">The location of the region.</param>
  130. /// <param name="size">The size, in pixels, of the region.</param>
  131. /// <param name="name">The name of the texture region.</param>
  132. /// <returns>The created texture region.</returns>
  133. /// <exception cref="InvalidOperationException">
  134. /// Thrown if a region with the same name as the <paramref name="name"/> parameter already exists in this atlas.
  135. /// </exception>
  136. public Texture2DRegion CreateRegion(string name, Point location, Size size) => CreateRegion(new Rectangle(location.X, location.Y, size.Width, size.Height), name);
  137. /// <summary>
  138. /// Creates a new texture region and adds it to this atlas.
  139. /// </summary>
  140. /// <param name="bounds">The bounds of the region.</param>
  141. /// <returns>The created texture region.</returns>
  142. public Texture2DRegion CreateRegion(Rectangle bounds) => CreateRegion(bounds, null);
  143. /// <summary>
  144. /// Creates a new texture region with the specified name and adds it to this atlas.
  145. /// </summary>
  146. /// <param name="bounds">The bounds of the region.</param>
  147. /// <param name="name">The name of the texture region.</param>
  148. /// <returns>The created texture region.</returns>
  149. /// <exception cref="InvalidOperationException">
  150. /// Thrown if a region with the same name as the <paramref name="name"/> parameter already exists in this atlas.
  151. /// </exception>
  152. public Texture2DRegion CreateRegion(Rectangle bounds, string name)
  153. {
  154. Texture2DRegion region = new Texture2DRegion(Texture, bounds, name);
  155. AddRegion(region);
  156. return region;
  157. }
  158. /// <summary>
  159. /// Creates a new texture region with the specified name and adds it to this atlas.
  160. /// </summary>
  161. /// <param name="bounds">The bounds of the region.</param>
  162. /// <param name="name">The name of the texture region.</param>
  163. /// <param name="isRotated">A value indicating whether this texture region is rotated 90 degrees clockwise in the atlas.</param>
  164. /// <returns>The created texture region.</returns>
  165. /// <exception cref="InvalidOperationException">
  166. /// Thrown if a region with the same name as the <paramref name="name"/> parameter already exists in this atlas.
  167. /// </exception>
  168. public Texture2DRegion CreateRegion(Rectangle bounds, bool isRotated, Size originalSize, Vector2 trimOffset, Vector2? originNormalized, string name)
  169. {
  170. Texture2DRegion region = new Texture2DRegion(Texture, bounds.X, bounds.Y, bounds.Width, bounds.Height, isRotated, originalSize, trimOffset, originNormalized, name);
  171. AddRegion(region);
  172. return region;
  173. }
  174. /// <summary>
  175. /// Determines whether the atlas contains a region with the specified name.
  176. /// </summary>
  177. /// <param name="name">The name of the region.</param>
  178. /// <returns>
  179. /// <see langword="true"/> if the atlas contains a region with the specified name; otherwise,
  180. /// <see langword="false"/>.
  181. /// </returns>
  182. public bool ContainsRegion(string name) => _regionsByName.ContainsKey(name);
  183. /// <summary>
  184. /// Gets the index of the region with the specified name.
  185. /// </summary>
  186. /// <param name="name">The name of the region.</param>
  187. /// <returns>The index of the region if found; otherwise, <c>-1</c>.</returns>
  188. public int GetIndexOfRegion(string name)
  189. {
  190. for (int i = 0; i < _regionsByIndex.Count; i++)
  191. {
  192. if (_regionsByIndex[i].Name == name)
  193. {
  194. return i;
  195. }
  196. }
  197. return -1;
  198. }
  199. /// <summary>
  200. /// Gets the region at the specified index.
  201. /// </summary>
  202. /// <param name="index">The index of the region.</param>
  203. /// <returns>The region at the specified index.</returns>
  204. /// <exception cref="ArgumentOutOfRangeException">
  205. /// Throw if the value of the <paramref name="index"/> is less than zero or is greater than or equal to the total
  206. /// number of regions in this atlas.
  207. /// </exception>
  208. public Texture2DRegion GetRegion(int index) => _regionsByIndex[index];
  209. /// <summary>
  210. /// Gets the region with the specified name.
  211. /// </summary>
  212. /// <param name="name">The name of the region.</param>
  213. /// <returns>The region with the specified name.</returns>
  214. /// <exception cref="KeyNotFoundException">
  215. /// Thrown if this atlas does not contain a region with a name that matches the <paramref name="name"/> parameter.
  216. /// </exception>
  217. public Texture2DRegion GetRegion(string name) => _regionsByName[name];
  218. /// <summary>
  219. /// Tries to get the region at the specified index.
  220. /// </summary>
  221. /// <param name="index">The index of the region.</param>
  222. /// <param name="region">
  223. /// When this method returns, contains the region at the specified index, if the index is found; otherwise,
  224. /// <see langword="null"/>.
  225. /// </param>
  226. /// <returns>
  227. /// <see langword="true"/> if the region is found at the specified index; otherwise, <see langword="false"/>.
  228. /// </returns>
  229. public bool TryGetRegion(int index, out Texture2DRegion region)
  230. {
  231. region = default;
  232. if (index < 0 || index >= _regionsByIndex.Count)
  233. {
  234. return false;
  235. }
  236. region = _regionsByIndex[index];
  237. return true;
  238. }
  239. /// <summary>
  240. /// Tries to get the region with the specified name.
  241. /// </summary>
  242. /// <param name="name">The name of the region.</param>
  243. /// <param name="region">
  244. /// When this method returns, contains the region with the specified name, if the name is found; otherwise,
  245. /// <see langword="null"/>.
  246. /// </param>
  247. /// <returns>
  248. /// <see langword="true"/> if the region is found with the specified name; otherwise, <see langword="false"/>.
  249. /// </returns>
  250. public bool TryGetRegion(string name, out Texture2DRegion region) => _regionsByName.TryGetValue(name, out region);
  251. /// <summary>
  252. /// Gets the regions at the specified indexes.
  253. /// </summary>
  254. /// <param name="indexes">The indexes of the regions to get.</param>
  255. /// <returns>An array of the regions at the specified indexes.</returns>
  256. /// <exception cref="ArgumentOutOfRangeException">
  257. /// Thrown if the value of any index in the <paramref name="indexes"/> parameter is less than zero or is greater
  258. /// than or equal to the total number of regions in this atlas.
  259. /// </exception>
  260. public Texture2DRegion[] GetRegions(params int[] indexes)
  261. {
  262. Texture2DRegion[] regions = new Texture2DRegion[indexes.Length];
  263. for (int i = 0; i < indexes.Length; i++)
  264. {
  265. regions[i] = GetRegion(indexes[i]);
  266. }
  267. return regions;
  268. }
  269. internal Texture2DRegion[] GetRegions(ReadOnlySpan<IAnimationFrame> frames)
  270. {
  271. Texture2DRegion[] regions = new Texture2DRegion[frames.Length];
  272. for (int i = 0; i < frames.Length; i++)
  273. {
  274. regions[i] = GetRegion(frames[i].FrameIndex);
  275. }
  276. return regions;
  277. }
  278. /// <summary>
  279. /// Gets the regions with the specified names.
  280. /// </summary>
  281. /// <param name="names">The names of the regions to get.</param>
  282. /// <returns>An array of the regions with the specified names.</returns>
  283. /// <exception cref="KeyNotFoundException">
  284. /// Thrown if a region is not found in this atlas with a name that matches any of the names in the
  285. /// <paramref name="names"/> parameter.
  286. /// </exception>
  287. public Texture2DRegion[] GetRegions(params string[] names)
  288. {
  289. Texture2DRegion[] regions = new Texture2DRegion[names.Length];
  290. for (int i = 0; i < names.Length; i++)
  291. {
  292. regions[i] = GetRegion(names[i]);
  293. }
  294. return regions;
  295. }
  296. /// <summary>
  297. /// Removes the region at the specified index.
  298. /// </summary>
  299. /// <param name="index">The index of the region to remove.</param>
  300. /// <returns>
  301. /// <see langword="true"/> if the region is successfully removed; otherwise, <see langword="false"/>.
  302. /// </returns>
  303. /// <exception cref="ArgumentOutOfRangeException">
  304. /// Throw if the value of the <paramref name="index"/> is less than zero or is greater than or equal to the total
  305. /// number of regions in this atlas.
  306. /// </exception>
  307. public bool RemoveRegion(int index)
  308. {
  309. if (TryGetRegion(index, out Texture2DRegion region))
  310. {
  311. return RemoveRegion(region);
  312. }
  313. return false;
  314. }
  315. /// <summary>
  316. /// Removes the region with the specified name.
  317. /// </summary>
  318. /// <param name="name">The name of the region to remove.</param>
  319. /// <returns>
  320. /// <see langword="true"/> if the region is successfully removed; otherwise, <see langword="false"/>.
  321. /// </returns>
  322. public bool RemoveRegion(string name)
  323. {
  324. if (TryGetRegion(name, out Texture2DRegion region))
  325. {
  326. return RemoveRegion(region);
  327. }
  328. return false;
  329. }
  330. /// <summary>
  331. /// Removes all regions from the atlas.
  332. /// </summary>
  333. public void ClearRegions()
  334. {
  335. _regionsByIndex.Clear();
  336. _regionsByName.Clear();
  337. }
  338. private void AddRegion(Texture2DRegion region)
  339. {
  340. if (_regionsByName.ContainsKey(region.Name))
  341. {
  342. throw new InvalidOperationException($"This {nameof(Texture2DAtlas)} already contains a {nameof(Texture2DRegion)} with the name '{region.Name}'");
  343. }
  344. _regionsByIndex.Add(region);
  345. _regionsByName.Add(region.Name, region);
  346. }
  347. /// <summary>
  348. /// Creates a new <see cref="Sprite"/> using the region from this atlas at the specified index.
  349. /// </summary>
  350. /// <param name="regionIndex">The index of the region to use.</param>
  351. /// <returns>The <see cref="Sprite"/> created using the region at the specified index.</returns>
  352. /// <exception cref="ArgumentOutOfRangeException">
  353. /// Throw if the value of the <paramref name="regionIndex"/> is less than zero or is greater than or equal to the total
  354. /// number of regions in this atlas.
  355. /// </exception>
  356. public Sprite CreateSprite(int regionIndex)
  357. {
  358. Texture2DRegion region = GetRegion(regionIndex);
  359. return new Sprite(region);
  360. }
  361. /// <summary>
  362. /// Creates a new <see cref="Sprite"/> using the region from this atlas with the specified name.
  363. /// </summary>
  364. /// <param name="regionName">The name of the region to use.</param>
  365. /// <returns>The <see cref="Sprite"/> created using the region with the specified name.</returns>
  366. /// <exception cref="KeyNotFoundException">
  367. /// Thrown if this atlas does not contain a region with a name that matches the <paramref name="regionName"/> parameter.
  368. /// </exception>
  369. public Sprite CreateSprite(string regionName)
  370. {
  371. Texture2DRegion region = GetRegion(regionName);
  372. return new Sprite(region);
  373. }
  374. private bool RemoveRegion(Texture2DRegion region) => _regionsByIndex.Remove(region) && _regionsByName.Remove(region.Name);
  375. /// <summary>
  376. /// Returns an enumerator that iterates through the collection of texture regions.
  377. /// </summary>
  378. /// <returns>An enumerator that can be used to iterate through the collection.</returns>
  379. public IEnumerator<Texture2DRegion> GetEnumerator() => _regionsByIndex.GetEnumerator();
  380. /// <summary>
  381. /// Returns an enumerator that iterates through the collection of texture regions.
  382. /// </summary>
  383. /// <returns>An enumerator that can be used to iterate through the collection.</returns>
  384. IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
  385. /// <summary>
  386. /// Creates a new <see cref="Texture2DAtlas"/> from the specified texture by dividing it into regions.
  387. /// </summary>
  388. /// <param name="name">The name of the texture atlas.</param>
  389. /// <param name="texture">The source texture to create the atlas from.</param>
  390. /// <param name="regionWidth">The width, in pixels, of each region.</param>
  391. /// <param name="regionHeight">The height, in pixels, of each region.</param>
  392. /// <param name="maxRegionCount">
  393. /// The maximum number of regions to create. Defaults to <see cref="int.MaxValue"/>.
  394. /// </param>
  395. /// <param name="margin">
  396. /// The margin, in pixels, to leave around the edges of the texture. Defaults to <c>0</c>.
  397. /// </param>
  398. /// <param name="spacing">The spacing, in pixels, between regions. Defaults to <c>0</c>.</param>
  399. /// <returns>A <see cref="Texture2DAtlas"/> containing the created regions.</returns>
  400. /// <exception cref="ArgumentNullException">Thrown if <paramref name="texture"/> is null.</exception>
  401. /// <exception cref="ObjectDisposedException">Thrown if <paramref name="texture"/> is disposed.</exception>
  402. public static Texture2DAtlas Create(string name, Texture2D texture, int regionWidth, int regionHeight,
  403. int maxRegionCount = int.MaxValue, int margin = 0, int spacing = 0)
  404. {
  405. var textureAtlas = new Texture2DAtlas(name, texture);
  406. var count = 0;
  407. var width = texture.Width - margin;
  408. var height = texture.Height - margin;
  409. var xIncrement = regionWidth + spacing;
  410. var yIncrement = regionHeight + spacing;
  411. var columns = (width - margin + spacing) / xIncrement;
  412. var rows = (height - margin + spacing) / yIncrement;
  413. var totalRegions = columns * rows;
  414. for (var i = 0; i < totalRegions; i++)
  415. {
  416. var x = margin + (i % columns) * xIncrement;
  417. var y = margin + (i / columns) * yIncrement;
  418. if (x >= width || y >= height)
  419. break;
  420. textureAtlas.CreateRegion(x, y, regionWidth, regionHeight);
  421. count++;
  422. if (count >= maxRegionCount)
  423. return textureAtlas;
  424. }
  425. return textureAtlas;
  426. }
  427. }