MoonTools.Bonk/Bonk/AABB.cs

96 lines
2.6 KiB
C#
Raw Normal View History

using System;
2019-09-06 08:11:58 +00:00
using System.Collections.Generic;
2019-10-31 23:19:30 +00:00
using System.Numerics;
2019-09-06 08:11:58 +00:00
using MoonTools.Core.Structs;
namespace MoonTools.Core.Bonk
{
2019-10-25 21:01:36 +00:00
/// <summary>
/// Axis-aligned bounding box.
/// </summary>
public struct AABB : IEquatable<AABB>
2019-09-06 08:11:58 +00:00
{
public float MinX { get; private set; }
public float MinY { get; private set; }
public float MaxX { get; private set; }
public float MaxY { get; private set; }
2019-09-06 08:11:58 +00:00
public float Width { get { return MaxX - MinX; } }
public float Height { get { return MaxY - MinY; } }
2019-09-06 08:11:58 +00:00
2019-09-06 20:00:35 +00:00
public static AABB FromTransformedVertices(IEnumerable<Position2D> vertices, Transform2D transform)
2019-09-06 08:11:58 +00:00
{
float minX = float.MaxValue;
float minY = float.MaxValue;
float maxX = float.MinValue;
float maxY = float.MinValue;
foreach (var vertex in vertices)
{
var transformedVertex = Vector2.Transform(vertex, transform.TransformMatrix);
if (transformedVertex.X < minX)
{
minX = transformedVertex.X;
}
if (transformedVertex.Y < minY)
{
minY = transformedVertex.Y;
}
if (transformedVertex.X > maxX)
{
maxX = transformedVertex.X;
}
if (transformedVertex.Y > maxY)
{
maxY = transformedVertex.Y;
}
}
2019-09-06 08:11:58 +00:00
return new AABB
{
MinX = minX,
MinY = minY,
MaxX = maxX,
MaxY = maxY
2019-09-06 08:11:58 +00:00
};
}
public override bool Equals(object obj)
{
return obj is AABB aabb && Equals(aabb);
}
public bool Equals(AABB other)
{
return MinX == other.MinX &&
MinY == other.MinY &&
MaxX == other.MaxX &&
MaxY == other.MaxY;
}
public override int GetHashCode()
{
return HashCode.Combine(MinX, MinY, MaxX, MaxY);
}
public AABB(float minX, float minY, float maxX, float maxY)
2019-09-06 08:11:58 +00:00
{
MinX = minX;
MinY = minY;
MaxX = maxX;
MaxY = maxY;
}
public static bool operator ==(AABB left, AABB right)
{
return left.Equals(right);
}
public static bool operator !=(AABB left, AABB right)
{
return !(left == right);
}
2019-09-06 08:11:58 +00:00
}
2019-12-16 18:51:27 +00:00
}