Syntriax.Engine/Engine.Physics2D/Primitives/Triangle.cs

45 lines
1.6 KiB
C#

using System;
using Syntriax.Engine.Core;
namespace Syntriax.Engine.Physics2D.Primitives;
public record Triangle(Vector2D A, Vector2D B, Vector2D C)
{
public float Area
=> .5f * MathF.Abs(
A.X * (B.Y - C.Y) +
B.X * (C.Y - A.Y) +
C.X * (A.Y - B.Y)
);
public static Circle GetCircumCircle(Triangle triangle)
{
Vector2D midAB = (triangle.A + triangle.B) / 2f;
Vector2D midBC = (triangle.B + triangle.C) / 2f;
float slopeAB = (triangle.B.Y - triangle.A.Y) / (triangle.B.X - triangle.A.X);
float slopeBC = (triangle.C.Y - triangle.B.Y) / (triangle.C.X - triangle.B.X);
Vector2D center;
if (MathF.Abs(slopeAB - slopeBC) > float.Epsilon)
{
float x = (slopeAB * slopeBC * (triangle.A.Y - triangle.C.Y) + slopeBC * (triangle.A.X + triangle.B.X) - slopeAB * (triangle.B.X + triangle.C.X)) / (2f * (slopeBC - slopeAB));
float y = -(x - (triangle.A.X + triangle.B.X) / 2f) / slopeAB + (triangle.A.Y + triangle.B.Y) / 2f;
center = new Vector2D(x, y);
}
else
center = (midAB + midBC) * .5f;
return new(center, Vector2D.Distance(center, triangle.A));
}
public static bool ApproximatelyEquals(Triangle left, Triangle right)
=> left.A.ApproximatelyEquals(right.A) && left.B.ApproximatelyEquals(right.B) && left.C.ApproximatelyEquals(right.C);
}
public static class TriangleExtensions
{
public static bool ApproximatelyEquals(this Triangle left, Triangle right) => Triangle.ApproximatelyEquals(left, right);
}