From 2054ae3a359cf6d2a8cbbfa30e48b3bdf6d4825b Mon Sep 17 00:00:00 2001 From: Syntriax Date: Mon, 9 Jun 2025 16:45:12 +0300 Subject: [PATCH] feat: added Ray2D primitive --- Engine.Core/Primitives/Ray2D.cs | 66 +++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Engine.Core/Primitives/Ray2D.cs diff --git a/Engine.Core/Primitives/Ray2D.cs b/Engine.Core/Primitives/Ray2D.cs new file mode 100644 index 0000000..a369d39 --- /dev/null +++ b/Engine.Core/Primitives/Ray2D.cs @@ -0,0 +1,66 @@ +namespace Syntriax.Engine.Core; + +public readonly struct Ray2D(Vector2D Origin, Vector2D Direction) +{ + /// + /// The starting point of the . + /// + public readonly Vector2D Origin = Origin; + + /// + /// The direction in which the points. Should be a normalized vector. + /// + public readonly Vector2D Direction = Direction; + + /// + /// Gets a with the same origin but with the direction reversed. + /// + public readonly Ray2D Reversed => new(Origin, -Direction); + + public static implicit operator Ray2D(Line2D line) => new(line.From, line.From.FromTo(line.To).Normalized); + + /// + /// Constructs a from a , extending from its origin in the 's direction for a given distance. + /// + /// The source . + /// The length of the line segment to create from the . + /// A representing the segment of the . + public static Line2D GetLine(Ray2D ray, float distance) + => new(ray.Origin, ray.Origin + ray.Direction * distance); + + /// + /// Evaluates the point on the at a specified distance from its origin. + /// + /// The to evaluate. + /// The distance from the origin along the 's direction. + /// A representing the point at the given distance on the . + public static Vector2D Evaluate(Ray2D ray, float distanceFromOrigin) + => ray.Origin + ray.Direction * distanceFromOrigin; + + /// + /// Calculates the closest point on the to the specified point. + /// + public static Vector2D ClosestPointTo(Ray2D ray, Vector2D point) + { + Vector2D originToPoint = ray.Origin.FromTo(point); + + float dot = ray.Direction.Dot(originToPoint); + + return ray.Origin + ray.Direction * dot; + } +} + +/// +/// Provides extension methods for the struct. +/// +public static class Ray2DExtensions +{ + /// + public static Vector2D Evaluate(this Ray2D ray, float distanceFromOrigin) => Ray2D.Evaluate(ray, distanceFromOrigin); + + ///