1
0
Fork 0
mirror of https://github.com/Ellpeck/MLEM.git synced 2024-11-24 21:48:35 +01:00

Compare commits

..

4 commits

Author SHA1 Message Date
Ell
dd295aca1b clarify StaticSpriteBatch depth documentation 2021-11-12 20:31:47 +01:00
Ell
d8517a7492 StaticSpriteBatch refactor that speeds up removal.
Items will now be drawn in an arbitrary order.
2021-11-12 20:21:08 +01:00
Ell
eb323bea01 only allow clearing a static sprite batch when batching 2021-11-12 18:35:10 +01:00
Ell
4a8a55fde3 allow removing items from a static sprite batch 2021-11-12 18:12:57 +01:00

View file

@ -7,8 +7,9 @@ using MLEM.Extensions;
namespace MLEM.Misc { namespace MLEM.Misc {
/// <summary> /// <summary>
/// A static sprite batch is a variation of <see cref="SpriteBatch"/> that keeps all batched items in a <see cref="VertexBuffer"/>, allowing for them to be drawn multiple times. /// A static sprite batch is a variation of <see cref="SpriteBatch"/> that keeps all batched items in a <see cref="VertexBuffer"/>, allowing for them to be drawn multiple times.
/// To add items to a static sprite batch, use <see cref="ClearBatch"/> to clear currently batched items, <see cref="BeginBatch"/> to begin batching, <c>Add</c> and its various overloads to add batch items and <see cref="EndBatch"/> to end batching. /// To add items to a static sprite batch, use <see cref="BeginBatch"/> to begin batching, <see cref="ClearBatch"/> to clear currently batched items, <c>Add</c> and its various overloads to add batch items, <see cref="Remove"/> to remove them again, and <see cref="EndBatch"/> to end batching.
/// To draw the batched items, call <see cref="Draw"/>. /// To draw the batched items, call <see cref="Draw"/>.
/// Unlike a <see cref="SpriteBatch"/>, items added to a static sprite batch will be drawn in an arbitrary order. If depth sorting is desired, the <see cref="GraphicsDeviceManager"/>'s <see cref="GraphicsDeviceManager.PreferredDepthStencilFormat"/> should be modified to include depth, and a <see cref="DepthStencilState"/> that takes depth into account should be passed to <see cref="Draw"/>.
/// </summary> /// </summary>
public class StaticSpriteBatch : IDisposable { public class StaticSpriteBatch : IDisposable {
@ -19,13 +20,13 @@ namespace MLEM.Misc {
/// <summary> /// <summary>
/// The amount of vertices that are currently batched /// The amount of vertices that are currently batched
/// </summary> /// </summary>
public int Vertices => this.vertices.Count; public int Vertices => this.items.Count * 4;
private readonly GraphicsDevice graphicsDevice; private readonly GraphicsDevice graphicsDevice;
private readonly SpriteEffect spriteEffect; private readonly SpriteEffect spriteEffect;
private readonly List<VertexBuffer> vertexBuffers = new List<VertexBuffer>(); private readonly List<VertexBuffer> vertexBuffers = new List<VertexBuffer>();
private readonly List<VertexPositionColorTexture> vertices = new List<VertexPositionColorTexture>(); private readonly ISet<Item> items = new HashSet<Item>();
private IndexBuffer indices; private IndexBuffer indices;
private Texture2D texture; private Texture2D texture;
private bool batching; private bool batching;
@ -43,7 +44,6 @@ namespace MLEM.Misc {
/// <summary> /// <summary>
/// Begins batching. /// Begins batching.
/// Call this method before calling <c>Add</c> or any of its overloads. /// Call this method before calling <c>Add</c> or any of its overloads.
/// Note that, if <see cref="ClearBatch"/> was not called, items that are batched will be appended to the existing batch.
/// </summary> /// </summary>
/// <exception cref="InvalidOperationException">Thrown if this batch is currently batching already</exception> /// <exception cref="InvalidOperationException">Thrown if this batch is currently batching already</exception>
public void BeginBatch() { public void BeginBatch() {
@ -62,28 +62,34 @@ namespace MLEM.Misc {
throw new InvalidOperationException("Not batching"); throw new InvalidOperationException("Not batching");
this.batching = false; this.batching = false;
// if we didn't add any batch items, we don't have to recalculate anything // if we didn't add or remove any batch items, we don't have to recalculate anything
if (!this.batchChanged) if (!this.batchChanged)
return; return;
this.batchChanged = false; this.batchChanged = false;
// ensure we have enough vertex buffers // ensure we have enough vertex buffers
var requiredBuffers = (this.vertices.Count / (MaxBatchItems * 4F)).Ceil(); var requiredBuffers = (this.items.Count / (float) MaxBatchItems).Ceil();
while (this.vertexBuffers.Count < requiredBuffers) while (this.vertexBuffers.Count < requiredBuffers)
this.vertexBuffers.Add(new VertexBuffer(this.graphicsDevice, VertexPositionColorTexture.VertexDeclaration, MaxBatchItems * 4, BufferUsage.WriteOnly)); this.vertexBuffers.Add(new VertexBuffer(this.graphicsDevice, VertexPositionColorTexture.VertexDeclaration, MaxBatchItems * 4, BufferUsage.WriteOnly));
// fill vertex buffers // fill vertex buffers
var dataIndex = 0;
var arrayIndex = 0; var arrayIndex = 0;
var totalIndex = 0; foreach (var item in this.items) {
while (totalIndex < this.vertices.Count) { Data[dataIndex++] = item.TopLeft;
var now = Math.Min(this.vertices.Count - totalIndex, Data.Length); Data[dataIndex++] = item.TopRight;
this.vertices.CopyTo(totalIndex, Data, 0, now); Data[dataIndex++] = item.BottomLeft;
this.vertexBuffers[arrayIndex++].SetData(Data); Data[dataIndex++] = item.BottomRight;
totalIndex += now; if (dataIndex >= Data.Length) {
this.vertexBuffers[arrayIndex++].SetData(Data);
dataIndex = 0;
}
} }
if (dataIndex > 0)
this.vertexBuffers[arrayIndex].SetData(Data);
// ensure we have enough indices // ensure we have enough indices
var maxItems = Math.Min(this.vertices.Count / 4, MaxBatchItems); var maxItems = Math.Min(this.items.Count, MaxBatchItems);
// each item has 2 triangles which each have 3 indices // each item has 2 triangles which each have 3 indices
if (this.indices == null || this.indices.IndexCount < 6 * maxItems) { if (this.indices == null || this.indices.IndexCount < 6 * maxItems) {
var newIndices = new short[6 * maxItems]; var newIndices = new short[6 * maxItems];
@ -109,19 +115,6 @@ namespace MLEM.Misc {
} }
} }
/// <summary>
/// Clears the batch, removing all currently batched vertices.
/// After this operation, <see cref="Vertices"/> will return 0.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if this batch is currently batching</exception>
public void ClearBatch() {
if (this.batching)
throw new InvalidOperationException("Cannot clear while batching");
this.vertices.Clear();
this.texture = null;
this.batchChanged = true;
}
/// <summary> /// <summary>
/// Draws this batch's content onto the <see cref="GraphicsDevice"/>'s current render target (or the back buffer) with the given settings. /// Draws this batch's content onto the <see cref="GraphicsDevice"/>'s current render target (or the back buffer) with the given settings.
/// Note that this method should not be called while a regular <see cref="SpriteBatch"/> is currently active. /// Note that this method should not be called while a regular <see cref="SpriteBatch"/> is currently active.
@ -148,7 +141,7 @@ namespace MLEM.Misc {
var totalIndex = 0; var totalIndex = 0;
foreach (var buffer in this.vertexBuffers) { foreach (var buffer in this.vertexBuffers) {
var tris = Math.Min(this.vertices.Count - totalIndex, buffer.VertexCount) / 4 * 2; var tris = Math.Min(this.items.Count * 4 - totalIndex, buffer.VertexCount) / 4 * 2;
if (tris <= 0) if (tris <= 0)
break; break;
this.graphicsDevice.SetVertexBuffer(buffer); this.graphicsDevice.SetVertexBuffer(buffer);
@ -178,8 +171,9 @@ namespace MLEM.Misc {
/// <param name="origin">Center of the rotation. 0,0 by default.</param> /// <param name="origin">Center of the rotation. 0,0 by default.</param>
/// <param name="scale">A scaling of this sprite.</param> /// <param name="scale">A scaling of this sprite.</param>
/// <param name="effects">Modificators for drawing. Can be combined.</param> /// <param name="effects">Modificators for drawing. Can be combined.</param>
/// <param name="layerDepth">A depth of the layer of this sprite.</param> /// <param name="layerDepth">A depth of the layer of this sprite. See <see cref="StaticSpriteBatch"/> documentation for information on enabling depth support.</param>
public void Add(Texture2D texture, Vector2 position, Rectangle? sourceRectangle, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth) { /// <returns>The <see cref="Item"/> that was created from the added data</returns>
public Item Add(Texture2D texture, Vector2 position, Rectangle? sourceRectangle, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth) {
origin *= scale; origin *= scale;
Vector2 size, texTl, texBr; Vector2 size, texTl, texBr;
@ -204,9 +198,9 @@ namespace MLEM.Misc {
(texBr.X, texTl.X) = (texTl.X, texBr.X); (texBr.X, texTl.X) = (texTl.X, texBr.X);
if (rotation == 0) { if (rotation == 0) {
this.Add(texture, position - origin, size, color, texTl, texBr, layerDepth); return this.Add(texture, position - origin, size, color, texTl, texBr, layerDepth);
} else { } else {
this.Add(texture, position, -origin, size, (float) Math.Sin(rotation), (float) Math.Cos(rotation), color, texTl, texBr, layerDepth); return this.Add(texture, position, -origin, size, (float) Math.Sin(rotation), (float) Math.Cos(rotation), color, texTl, texBr, layerDepth);
} }
} }
@ -222,9 +216,10 @@ namespace MLEM.Misc {
/// <param name="origin">Center of the rotation. 0,0 by default.</param> /// <param name="origin">Center of the rotation. 0,0 by default.</param>
/// <param name="scale">A scaling of this sprite.</param> /// <param name="scale">A scaling of this sprite.</param>
/// <param name="effects">Modificators for drawing. Can be combined.</param> /// <param name="effects">Modificators for drawing. Can be combined.</param>
/// <param name="layerDepth">A depth of the layer of this sprite.</param> /// <param name="layerDepth">A depth of the layer of this sprite. See <see cref="StaticSpriteBatch"/> documentation for information on enabling depth support.</param>
public void Add(Texture2D texture, Vector2 position, Rectangle? sourceRectangle, Color color, float rotation, Vector2 origin, float scale, SpriteEffects effects, float layerDepth) { /// <returns>The <see cref="Item"/> that was created from the added data</returns>
this.Add(texture, position, sourceRectangle, color, rotation, origin, new Vector2(scale), effects, layerDepth); public Item Add(Texture2D texture, Vector2 position, Rectangle? sourceRectangle, Color color, float rotation, Vector2 origin, float scale, SpriteEffects effects, float layerDepth) {
return this.Add(texture, position, sourceRectangle, color, rotation, origin, new Vector2(scale), effects, layerDepth);
} }
/// <summary> /// <summary>
@ -238,8 +233,9 @@ namespace MLEM.Misc {
/// <param name="rotation">A rotation of this sprite.</param> /// <param name="rotation">A rotation of this sprite.</param>
/// <param name="origin">Center of the rotation. 0,0 by default.</param> /// <param name="origin">Center of the rotation. 0,0 by default.</param>
/// <param name="effects">Modificators for drawing. Can be combined.</param> /// <param name="effects">Modificators for drawing. Can be combined.</param>
/// <param name="layerDepth">A depth of the layer of this sprite.</param> /// <param name="layerDepth">A depth of the layer of this sprite. See <see cref="StaticSpriteBatch"/> documentation for information on enabling depth support.</param>
public void Add(Texture2D texture, Rectangle destinationRectangle, Rectangle? sourceRectangle, Color color, float rotation, Vector2 origin, SpriteEffects effects, float layerDepth) { /// <returns>The <see cref="Item"/> that was created from the added data</returns>
public Item Add(Texture2D texture, Rectangle destinationRectangle, Rectangle? sourceRectangle, Color color, float rotation, Vector2 origin, SpriteEffects effects, float layerDepth) {
Vector2 texTl, texBr; Vector2 texTl, texBr;
if (sourceRectangle.HasValue) { if (sourceRectangle.HasValue) {
var src = sourceRectangle.Value; var src = sourceRectangle.Value;
@ -262,9 +258,9 @@ namespace MLEM.Misc {
(texBr.X, texTl.X) = (texTl.X, texBr.X); (texBr.X, texTl.X) = (texTl.X, texBr.X);
if (rotation == 0) { if (rotation == 0) {
this.Add(texture, destinationRectangle.Location.ToVector2() - origin, destinationRectangle.Size.ToVector2(), color, texTl, texBr, layerDepth); return this.Add(texture, destinationRectangle.Location.ToVector2() - origin, destinationRectangle.Size.ToVector2(), color, texTl, texBr, layerDepth);
} else { } else {
this.Add(texture, destinationRectangle.Location.ToVector2(), -origin, destinationRectangle.Size.ToVector2(), (float) Math.Sin(rotation), (float) Math.Cos(rotation), color, texTl, texBr, layerDepth); return this.Add(texture, destinationRectangle.Location.ToVector2(), -origin, destinationRectangle.Size.ToVector2(), (float) Math.Sin(rotation), (float) Math.Cos(rotation), color, texTl, texBr, layerDepth);
} }
} }
@ -276,8 +272,9 @@ namespace MLEM.Misc {
/// <param name="position">The drawing location on screen.</param> /// <param name="position">The drawing location on screen.</param>
/// <param name="sourceRectangle">An optional region on the texture which will be rendered. If null - draws full texture.</param> /// <param name="sourceRectangle">An optional region on the texture which will be rendered. If null - draws full texture.</param>
/// <param name="color">A color mask.</param> /// <param name="color">A color mask.</param>
public void Add(Texture2D texture, Vector2 position, Rectangle? sourceRectangle, Color color) { /// <returns>The <see cref="Item"/> that was created from the added data</returns>
this.Add(texture, position, sourceRectangle, color, 0, Vector2.Zero, 1, SpriteEffects.None, 0); public Item Add(Texture2D texture, Vector2 position, Rectangle? sourceRectangle, Color color) {
return this.Add(texture, position, sourceRectangle, color, 0, Vector2.Zero, 1, SpriteEffects.None, 0);
} }
/// <summary> /// <summary>
@ -288,8 +285,9 @@ namespace MLEM.Misc {
/// <param name="destinationRectangle">The drawing bounds on screen.</param> /// <param name="destinationRectangle">The drawing bounds on screen.</param>
/// <param name="sourceRectangle">An optional region on the texture which will be rendered. If null - draws full texture.</param> /// <param name="sourceRectangle">An optional region on the texture which will be rendered. If null - draws full texture.</param>
/// <param name="color">A color mask.</param> /// <param name="color">A color mask.</param>
public void Add(Texture2D texture, Rectangle destinationRectangle, Rectangle? sourceRectangle, Color color) { /// <returns>The <see cref="Item"/> that was created from the added data</returns>
this.Add(texture, destinationRectangle, sourceRectangle, color, 0, Vector2.Zero, SpriteEffects.None, 0); public Item Add(Texture2D texture, Rectangle destinationRectangle, Rectangle? sourceRectangle, Color color) {
return this.Add(texture, destinationRectangle, sourceRectangle, color, 0, Vector2.Zero, SpriteEffects.None, 0);
} }
/// <summary> /// <summary>
@ -299,8 +297,9 @@ namespace MLEM.Misc {
/// <param name="texture">A texture.</param> /// <param name="texture">A texture.</param>
/// <param name="position">The drawing location on screen.</param> /// <param name="position">The drawing location on screen.</param>
/// <param name="color">A color mask.</param> /// <param name="color">A color mask.</param>
public void Add(Texture2D texture, Vector2 position, Color color) { /// <returns>The <see cref="Item"/> that was created from the added data</returns>
this.Add(texture, position, null, color); public Item Add(Texture2D texture, Vector2 position, Color color) {
return this.Add(texture, position, null, color);
} }
/// <summary> /// <summary>
@ -310,8 +309,39 @@ namespace MLEM.Misc {
/// <param name="texture">A texture.</param> /// <param name="texture">A texture.</param>
/// <param name="destinationRectangle">The drawing bounds on screen.</param> /// <param name="destinationRectangle">The drawing bounds on screen.</param>
/// <param name="color">A color mask.</param> /// <param name="color">A color mask.</param>
public void Add(Texture2D texture, Rectangle destinationRectangle, Color color) { /// <returns>The <see cref="Item"/> that was created from the added data</returns>
this.Add(texture, destinationRectangle, null, color); public Item Add(Texture2D texture, Rectangle destinationRectangle, Color color) {
return this.Add(texture, destinationRectangle, null, color);
}
/// <summary>
/// Removes the given item from this batch.
/// Note that this batch needs to currently be batching, meaning <see cref="BeginBatch"/> has to have been called previously.
/// </summary>
/// <param name="item">The item to remove</param>
/// <returns>Whether the item was successfully removed</returns>
/// <exception cref="InvalidOperationException">Thrown if this method is called before <see cref="BeginBatch"/> was called</exception>
public bool Remove(Item item) {
if (!this.batching)
throw new InvalidOperationException("Not batching");
if (this.items.Remove(item)) {
this.batchChanged = true;
return true;
}
return false;
}
/// <summary>
/// Clears the batch, removing all currently batched vertices.
/// After this operation, <see cref="Vertices"/> will return 0.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if this method is called before <see cref="BeginBatch"/> was called</exception>
public void ClearBatch() {
if (!this.batching)
throw new InvalidOperationException("Not batching");
this.items.Clear();
this.texture = null;
this.batchChanged = true;
} }
/// <inheritdoc /> /// <inheritdoc />
@ -323,33 +353,52 @@ namespace MLEM.Misc {
GC.SuppressFinalize(this); GC.SuppressFinalize(this);
} }
private void Add(Texture2D texture, Vector2 pos, Vector2 offset, Vector2 size, float sin, float cos, Color color, Vector2 texTl, Vector2 texBr, float depth) { private Item Add(Texture2D texture, Vector2 pos, Vector2 offset, Vector2 size, float sin, float cos, Color color, Vector2 texTl, Vector2 texBr, float depth) {
this.Add(texture, return this.Add(texture,
new VertexPositionColorTexture(new Vector3(pos.X + offset.X * cos - offset.Y * sin, pos.Y + offset.X * sin + offset.Y * cos, depth), color, texTl), new VertexPositionColorTexture(new Vector3(pos.X + offset.X * cos - offset.Y * sin, pos.Y + offset.X * sin + offset.Y * cos, depth), color, texTl),
new VertexPositionColorTexture(new Vector3(pos.X + (offset.X + size.X) * cos - offset.Y * sin, pos.Y + (offset.X + size.X) + offset.Y * cos, depth), color, new Vector2(texBr.X, texTl.Y)), new VertexPositionColorTexture(new Vector3(pos.X + (offset.X + size.X) * cos - offset.Y * sin, pos.Y + (offset.X + size.X) + offset.Y * cos, depth), color, new Vector2(texBr.X, texTl.Y)),
new VertexPositionColorTexture(new Vector3(pos.X + offset.X * cos - (offset.Y + size.Y) * sin, pos.Y + offset.X * sin + (offset.Y + size.Y) * cos, depth), color, new Vector2(texTl.X, texBr.Y)), new VertexPositionColorTexture(new Vector3(pos.X + offset.X * cos - (offset.Y + size.Y) * sin, pos.Y + offset.X * sin + (offset.Y + size.Y) * cos, depth), color, new Vector2(texTl.X, texBr.Y)),
new VertexPositionColorTexture(new Vector3(pos.X + (offset.X + size.X) * cos - (offset.Y + size.Y) * sin, pos.Y + (offset.X + size.X) * sin + (offset.Y + size.Y) * cos, depth), color, texBr)); new VertexPositionColorTexture(new Vector3(pos.X + (offset.X + size.X) * cos - (offset.Y + size.Y) * sin, pos.Y + (offset.X + size.X) * sin + (offset.Y + size.Y) * cos, depth), color, texBr));
} }
private void Add(Texture2D texture, Vector2 pos, Vector2 size, Color color, Vector2 texTl, Vector2 texBr, float depth) { private Item Add(Texture2D texture, Vector2 pos, Vector2 size, Color color, Vector2 texTl, Vector2 texBr, float depth) {
this.Add(texture, return this.Add(texture,
new VertexPositionColorTexture(new Vector3(pos, depth), color, texTl), new VertexPositionColorTexture(new Vector3(pos, depth), color, texTl),
new VertexPositionColorTexture(new Vector3(pos.X + size.X, pos.Y, depth), color, new Vector2(texBr.X, texTl.Y)), new VertexPositionColorTexture(new Vector3(pos.X + size.X, pos.Y, depth), color, new Vector2(texBr.X, texTl.Y)),
new VertexPositionColorTexture(new Vector3(pos.X, pos.Y + size.Y, depth), color, new Vector2(texTl.X, texBr.Y)), new VertexPositionColorTexture(new Vector3(pos.X, pos.Y + size.Y, depth), color, new Vector2(texTl.X, texBr.Y)),
new VertexPositionColorTexture(new Vector3(pos.X + size.X, pos.Y + size.Y, depth), color, texBr)); new VertexPositionColorTexture(new Vector3(pos.X + size.X, pos.Y + size.Y, depth), color, texBr));
} }
private void Add(Texture2D texture, VertexPositionColorTexture tl, VertexPositionColorTexture tr, VertexPositionColorTexture bl, VertexPositionColorTexture br) { private Item Add(Texture2D texture, VertexPositionColorTexture tl, VertexPositionColorTexture tr, VertexPositionColorTexture bl, VertexPositionColorTexture br) {
if (!this.batching) if (!this.batching)
throw new InvalidOperationException("Not batching"); throw new InvalidOperationException("Not batching");
if (this.texture != null && this.texture != texture) if (this.texture != null && this.texture != texture)
throw new ArgumentException("Cannot use multiple textures in one batch"); throw new ArgumentException("Cannot use multiple textures in one batch");
var item = new Item(tl, tr, bl, br);
this.items.Add(item);
this.texture = texture; this.texture = texture;
this.vertices.Add(tl);
this.vertices.Add(tr);
this.vertices.Add(bl);
this.vertices.Add(br);
this.batchChanged = true; this.batchChanged = true;
return item;
}
/// <summary>
/// A struct that represents an item added to a <see cref="StaticSpriteBatch"/> using <c>Add</c> or any of its overloads.
/// An item returned after adding can be removed using <see cref="Remove"/>.
/// </summary>
public class Item {
internal readonly VertexPositionColorTexture TopLeft;
internal readonly VertexPositionColorTexture TopRight;
internal readonly VertexPositionColorTexture BottomLeft;
internal readonly VertexPositionColorTexture BottomRight;
internal Item(VertexPositionColorTexture topLeft, VertexPositionColorTexture topRight, VertexPositionColorTexture bottomLeft, VertexPositionColorTexture bottomRight) {
this.TopLeft = topLeft;
this.TopRight = topRight;
this.BottomLeft = bottomLeft;
this.BottomRight = bottomRight;
}
} }
} }