using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
namespace MonoGame.Extended.Tilemaps
{
///
/// Represents a layer containing drawable objects.
///
public class TilemapObjectLayer : TilemapLayer
{
private readonly List _objects = new();
///
/// Gets the collection of objects in this layer.
///
public IReadOnlyList Objects
{
get
{
return _objects;
}
}
///
/// Gets or sets the rendering order for objects in this layer.
///
public TilemapObjectDrawOrder DrawOrder { get; set; }
///
public override Rectangle Bounds
{
get
{
if (_objects.Count == 0)
{
return Rectangle.Empty;
}
// Calculate bounds as the union of all object bounds
RectangleF? unionBounds = null;
foreach (TilemapObject obj in _objects)
{
RectangleF objBounds = obj.Bounds;
if (unionBounds == null)
{
unionBounds = objBounds;
}
else
{
unionBounds = RectangleF.Union(unionBounds.Value, objBounds);
}
}
RectangleF bounds = unionBounds.Value;
return new Rectangle(
(int)bounds.X,
(int)bounds.Y,
(int)Math.Ceiling(bounds.Width),
(int)Math.Ceiling(bounds.Height)
);
}
}
///
/// Initializes a new instance of the class.
///
/// The name of the layer.
public TilemapObjectLayer(string name) : base(name)
{
DrawOrder = TilemapObjectDrawOrder.TopDown;
}
///
/// Adds an object to the layer.
///
/// The object to add.
public void AddObject(TilemapObject obj)
{
_objects.Add(obj);
}
///
/// Removes an object from the layer.
///
/// The object to remove.
/// if the object was removed; otherwise, .
public bool RemoveObject(TilemapObject obj)
{
return _objects.Remove(obj);
}
///
/// Gets the object with the specified ID.
///
/// The object ID.
/// The object with the specified ID, or if not found.
public TilemapObject GetObject(int id)
{
foreach (TilemapObject obj in _objects)
{
if (obj.Id == id)
{
return obj;
}
}
return null;
}
///
/// Gets all objects within the specified rectangular region.
///
/// The region in world coordinates.
/// An enumerable of objects within the region.
public IEnumerable GetObjectsInRegion(RectangleF region)
{
foreach (TilemapObject obj in _objects)
{
if (region.Intersects(obj.Bounds))
{
yield return obj;
}
}
}
///
/// Gets all objects of the specified type.
///
/// The type of objects to retrieve.
/// An enumerable of objects of the specified type.
public IEnumerable GetObjects() where T : TilemapObject
{
foreach (TilemapObject obj in _objects)
{
if (obj is T typedObj)
{
yield return typedObj;
}
}
}
}
}