Skip to content

Commit

Permalink
feat: Add GeometryHelper
Browse files Browse the repository at this point in the history
  • Loading branch information
erictuvesson committed Jun 7, 2021
1 parent 2e05b3d commit 5413a99
Show file tree
Hide file tree
Showing 2 changed files with 112 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/GeometryHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
namespace Nine.Geometry
{
using System.Numerics;

public static class GeometryHelper
{
/// <summary>
/// Returns whether the points are in counter clockwise order.
/// </summary>
/// <param name="points"></param>
/// <returns></returns>
public static bool PointsAreCounterClockwiseOrder(Vector2[] points)
{
float signedArea = 0;
for (int i = 0; i < points.Length; i++)
{
int nextIndex = (i + 1) % points.Length;
signedArea += (points[nextIndex].X - points[i].X)
* (points[nextIndex].Y + points[i].Y);
}

return signedArea < 0;
}

/// <summary>
/// Returns whether the points are in counter clockwise order.
/// </summary>
/// <param name="points"></param>
/// <returns></returns>
public static bool PointsAreCounterClockwiseOrder(Vector3[] points)
{
float signedArea = 0;
for (int i = 0; i < points.Length; i++)
{
int nextIndex = (i + 1) % points.Length;
signedArea += (points[nextIndex].X - points[i].X)
* (points[nextIndex].Y + points[i].Y)
* (points[nextIndex].Z + points[i].Z);
}

return signedArea < 0;
}
}
}
68 changes: 68 additions & 0 deletions test/GeometryHelperTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
namespace Nine.Geometry.Test
{
using System.Numerics;
using Xunit;

public class GeometryHelperTest
{
[Fact]
public void PointsAreCounterClockwiseOrder_Vector2()
{
var points = new Vector2[]
{
new Vector2(0, 0),
new Vector2(1, 0),
new Vector2(1, 1),
};

var counterClockwise = GeometryHelper.PointsAreCounterClockwiseOrder(points);

Assert.True(counterClockwise);
}

[Fact]
public void PointsAreCounterClockwiseOrder_Vector2_Clockwise()
{
var points = new Vector2[]
{
new Vector2(1, 1),
new Vector2(1, 0),
new Vector2(0, 0),
};

var counterClockwise = GeometryHelper.PointsAreCounterClockwiseOrder(points);

Assert.False(counterClockwise);
}

[Fact]
public void PointsAreCounterClockwiseOrder_Vector3()
{
var points = new Vector3[]
{
new Vector3(1, 1, 1),
new Vector3(1, 0, 1),
new Vector3(0, 0, 1),
};

var counterClockwise = GeometryHelper.PointsAreCounterClockwiseOrder(points);

Assert.False(counterClockwise);
}

[Fact]
public void PointsAreCounterClockwiseOrder_Vector3_Clockwise()
{
var points = new Vector3[]
{
new Vector3(1, 1, 1),
new Vector3(1, 0, 1),
new Vector3(0, 0, 1),
};

var counterClockwise = GeometryHelper.PointsAreCounterClockwiseOrder(points);

Assert.False(counterClockwise);
}
}
}

0 comments on commit 5413a99

Please sign in to comment.