Syntriax.Engine/Engine.Physics2D/Primitives/Shape.cs

74 lines
2.4 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using Syntriax.Engine.Core;
namespace Syntriax.Engine.Physics2D.Primitives;
public record Shape(IList<Vector2D> Vertices)
{
public Vector2D this[Index index] => Vertices[index];
2024-01-24 12:02:04 +03:00
2024-01-23 19:17:08 +03:00
public static Triangle GetSuperTriangle(Shape shape)
{
2024-01-23 19:17:08 +03:00
float minX = float.MaxValue, minY = float.MaxValue;
float maxX = float.MinValue, maxY = float.MinValue;
2024-01-23 19:17:08 +03:00
foreach (Vector2D point in shape.Vertices)
{
minX = MathF.Min(minX, point.X);
minY = MathF.Min(minY, point.Y);
maxX = MathF.Max(maxX, point.X);
maxY = MathF.Max(maxY, point.Y);
}
2024-01-23 19:17:08 +03:00
float dx = maxX - minX;
float dy = maxY - minY;
float deltaMax = MathF.Max(dx, dy);
float midX = (minX + maxX) / 2;
float midY = (minY + maxY) / 2;
2024-01-23 19:17:08 +03:00
Vector2D p1 = new((float)midX - 20f * (float)deltaMax, (float)midY - (float)deltaMax);
Vector2D p2 = new((float)midX, (float)midY + 20 * (float)deltaMax);
Vector2D p3 = new((float)midX + 20 * (float)deltaMax, (float)midY - (float)deltaMax);
2024-01-23 19:17:08 +03:00
return new Triangle(p1, p2, p3);
}
2024-01-23 19:17:08 +03:00
public static void GetLines(Shape shape, IList<Line> lines)
{
2024-01-23 19:17:08 +03:00
lines.Clear();
for (int i = 0; i < shape.Vertices.Count - 1; i++)
lines.Add(new(shape.Vertices[i], shape.Vertices[i + 1]));
lines.Add(new(shape.Vertices[^1], shape.Vertices[0]));
}
2024-01-23 19:17:08 +03:00
public static List<Line> GetLines(Shape shape)
{
2024-01-23 19:17:08 +03:00
List<Line> lines = new(shape.Vertices.Count - 1);
GetLines(shape, lines);
return lines;
}
2024-01-23 19:17:08 +03:00
public static bool ApproximatelyEquals(Shape left, Shape right)
{
2024-01-23 19:17:08 +03:00
if (left.Vertices.Count != right.Vertices.Count)
return false;
2024-01-23 19:17:08 +03:00
for (int i = 0; i < left.Vertices.Count; i++)
if (!left.Vertices[i].ApproximatelyEquals(right.Vertices[i]))
return false;
return true;
}
}
2024-01-23 19:17:08 +03:00
public static class ShapeExtensions
{
public static Triangle ToSuperTriangle(this Shape shape) => Shape.GetSuperTriangle(shape);
public static void ToLines(this Shape shape, IList<Line> lines) => Shape.GetLines(shape, lines);
public static List<Line> ToLines(this Shape shape) => Shape.GetLines(shape);
public static bool ApproximatelyEquals(this Shape left, Shape right) => Shape.ApproximatelyEquals(left, right);
}