MoonTools.Bonk/Bonk/Shapes/Line.cs

80 lines
2.1 KiB
C#
Raw Normal View History

2019-09-06 08:11:58 +00:00
using System;
2019-10-25 10:46:47 +00:00
using System.Collections.Generic;
2019-10-31 23:19:30 +00:00
using System.Numerics;
2020-02-21 02:07:59 +00:00
using MoonTools.Structs;
2019-09-06 08:11:58 +00:00
2020-02-21 02:07:59 +00:00
namespace MoonTools.Bonk
2019-09-06 08:11:58 +00:00
{
2019-10-25 21:01:36 +00:00
/// <summary>
/// A line is a shape defined by exactly two points in space.
/// </summary>
public struct Line : IShape2D, IEquatable<Line>
2019-09-06 08:11:58 +00:00
{
2019-12-30 06:19:10 +00:00
private Position2D _v0;
private Position2D _v1;
public AABB AABB { get; }
2019-10-25 10:46:47 +00:00
2019-12-02 06:25:05 +00:00
public IEnumerable<Position2D> Vertices
2019-10-25 10:46:47 +00:00
{
get
{
2019-12-30 06:19:10 +00:00
yield return _v0;
yield return _v1;
2019-10-25 10:46:47 +00:00
}
}
2019-09-06 08:11:58 +00:00
public Line(Position2D start, Position2D end)
{
2019-12-30 06:19:10 +00:00
_v0 = start;
_v1 = end;
AABB = new AABB(Math.Min(_v0.X, _v1.X), Math.Min(_v0.Y, _v1.Y), Math.Max(_v0.X, _v1.X), Math.Max(_v0.Y, _v1.Y));
2019-09-06 08:11:58 +00:00
}
public Vector2 Support(Vector2 direction, Transform2D transform)
{
2019-12-30 06:19:10 +00:00
var transformedStart = Vector2.Transform(_v0, transform.TransformMatrix);
var transformedEnd = Vector2.Transform(_v1, transform.TransformMatrix);
return Vector2.Dot(transformedStart, direction) > Vector2.Dot(transformedEnd, direction) ?
transformedStart :
transformedEnd;
2019-09-06 08:11:58 +00:00
}
2019-12-30 06:19:10 +00:00
public AABB TransformedAABB(Transform2D transform)
2019-09-06 08:11:58 +00:00
{
2019-12-30 06:19:10 +00:00
return AABB.Transformed(AABB, transform);
2019-09-06 08:11:58 +00:00
}
2019-10-25 23:20:43 +00:00
public override bool Equals(object obj)
{
return obj is IShape2D other && Equals(other);
2019-10-25 23:20:43 +00:00
}
2019-09-06 08:11:58 +00:00
public bool Equals(IShape2D other)
{
return other is Line otherLine && Equals(otherLine);
}
2019-09-06 08:11:58 +00:00
public bool Equals(Line other)
{
2019-12-30 06:19:10 +00:00
return (_v0 == other._v0 && _v1 == other._v1) || (_v1 == other._v0 && _v0 == other._v1);
2019-09-06 08:11:58 +00:00
}
2019-10-25 23:20:43 +00:00
public override int GetHashCode()
{
2019-12-30 06:19:10 +00:00
return HashCode.Combine(_v0, _v1);
2019-10-25 23:20:43 +00:00
}
public static bool operator ==(Line a, Line b)
{
return a.Equals(b);
}
public static bool operator !=(Line a, Line b)
{
return !(a == b);
}
2019-09-06 08:11:58 +00:00
}
}