using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Newtonsoft.Json; using RecrownedAthenaeum.DataTypes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace RecrownedAthenaeum.DataTypes { public class TextureAtlas { [JsonIgnore] private Texture2D texture; private Dictionary dictionaryOfRegions = new Dictionary(); public TextureAtlas(Texture2D texture, TextureAtlasRegion[] regions) { this.texture = texture; foreach (TextureAtlasRegion region in regions) { dictionaryOfRegions.Add(region.name, region); } } public TextureAtlas(Texture2D texture, Dictionary dictionaryOfRegions) { this.texture = texture; this.dictionaryOfRegions = dictionaryOfRegions; } public void Draw(string name, SpriteBatch batch, Rectangle destination, Color color, float rotation = 0, Vector2 origin = new Vector2()) { dictionaryOfRegions[name].Draw(batch, destination, color, rotation, origin); } public Texture2D TextureOfRegion(string name, GraphicsDevice graphicsDevice) { return dictionaryOfRegions[name].AsTexture2D(graphicsDevice, texture); } public class TextureAtlasRegion : IComparable, IDisposable { public readonly string name; public readonly Rectangle sourceRectangle; readonly NinePatch ninepatch; Texture2D atlasTexture; Texture2D regionTexture; public TextureAtlasRegion(string name, Rectangle source, NinePatch ninePatch, Texture2D atlasTexture) { this.atlasTexture = atlasTexture; this.name = name; this.sourceRectangle = source; this.ninepatch = ninePatch; } public void Draw(SpriteBatch batch, Rectangle destination, Color color, float rotation, Vector2 origin) { batch.Draw(atlasTexture, destination, sourceRectangle, color, rotation, origin, SpriteEffects.None, 0f); } public Texture2D AsTexture2D(GraphicsDevice graphicsDevice, Texture2D textureAtlas) { if (regionTexture == null) { Color[] data = new Color[sourceRectangle.Width * sourceRectangle.Height]; regionTexture = new Texture2D(graphicsDevice, sourceRectangle.Width, sourceRectangle.Height); textureAtlas.GetData(0, sourceRectangle, data, 0, sourceRectangle.Width * sourceRectangle.Height); regionTexture.SetData(data); } return regionTexture; } public int CompareTo(TextureAtlasRegion other) { return name.CompareTo(other); } public void Dispose() { regionTexture?.Dispose(); } } } }