using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using RecrownedAthenaeum.Camera;
using System;
namespace RecrownedAthenaeum.Render
{
///
/// Renders rectangles using the .
///
public class RectangleRenderer : IDisposable
{
private bool filled;
private bool disposed;
///
/// The used. Needs to be disposed.
///
private readonly PrimitiveBatch primitiveBatch;
///
/// Creates a rectangle renderer with the given .
///
/// Camera to use for . Default will use .
/// Graphics device to use. Default will use .
public RectangleRenderer(Camera2D camera = null, GraphicsDevice graphicsDevice = null)
{
primitiveBatch = new PrimitiveBatch(camera, graphicsDevice);
}
///
/// Disposes the rectangle renderer.
///
public void Dispose()
{
Dispose(true);
}
///
/// Overridable for dispose.
///
/// True when its a player calling the dispose.
public virtual void Dispose(bool disposing)
{
if (disposed) throw new ObjectDisposedException(GetType().Name);
if (disposing)
{
primitiveBatch.Dispose();
}
disposed = true;
}
///
/// Begins a batch for rectangles.
///
/// Whether or not this batch should be filled rectangles.
public void Begin(bool filled = false)
{
this.filled = filled;
primitiveBatch.Begin(filled ? PrimitiveType.TriangleStrip : PrimitiveType.LineStrip);
}
///
/// Ends the batch.
///
public void End()
{
primitiveBatch.End();
}
///
/// Draws a basic rectangle given bottom left and top right.
///
/// X coordinate of bottom left.
/// Y coordinate of bottom left.
/// Width of rectangle.
/// Height of rectangle.
/// Color of all vertices of this rectangle.
/// Rotation of rectangle. Default is 0 radians.
public void Draw(int x, int y, int width, int height, Color color, float rotation = 0)
{
primitiveBatch.primitiveCount = filled ? 3 : 4;
Vector2[] corners = new Vector2[4];
corners[1] = new Vector2(width, 0);
corners[2] = new Vector2(width, height);
corners[3] = new Vector2(0, height);
if (rotation != 0)
{
Matrix rotMat = Matrix.CreateRotationZ(rotation);
for (int i = 0; i < corners.Length; i++)
{
corners[i] = Vector2.Transform(corners[i], rotMat);
}
}
for (int i = 0; i < corners.Length; i++)
{
corners[i].X += x;
corners[i].Y += y;
}
primitiveBatch.AddVertex(corners[0], color);
primitiveBatch.AddVertex(corners[1], color);
primitiveBatch.AddVertex(corners[2], color);
primitiveBatch.AddVertex(corners[3], color);
primitiveBatch.AddVertex(corners[0], color);
primitiveBatch.Flush();
}
///
/// Draws the given rectangle.
///
/// Uses the x, y and dimensions to draw a rectangle.
/// The color of the rectangle.
public void Draw(Rectangle rectangle, Color color)
{
Draw(rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height, color);
}
}
}