| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520 |
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Diagnostics.CodeAnalysis;
- using System.Runtime.Serialization;
- using Microsoft.Xna.Framework;
- namespace MonoGame.Extended;
- /// <summary>
- /// Represents a circular bounding volume in 2D space defined by a center point and radius.
- /// </summary>
- [DataContract]
- [DebuggerDisplay("{DebugDisplayString,nq}")]
- public struct Circle : IEquatable<Circle>
- {
- #region Fields
- private static Circle s_empty = new Circle(Vector2.Zero, 0.0f);
- /// <summary>
- /// The center position of the circular bounding volume.
- /// </summary>
- [DataMember]
- public Vector2 Center;
- /// <summary>
- /// The radius defining the circular boundary, measured as the distance from the center to any point on
- /// the perimeter.
- /// </summary>
- [DataMember]
- public float Radius;
- #endregion
- #region Properties
- /// <summary>
- /// Gets an empty circle representing a degenerate case with zero radius.
- /// </summary>
- public static Circle Empty => s_empty;
- /// <summary>
- /// Gets a value indicating whether this circle represents a degenerate case with no area, having zero
- /// or negative radius.
- /// </summary>
- public readonly bool IsEmpty => Radius <= 0.0f;
- /// <summary>
- /// Gets the diameter of the circle, representing the width across the center.
- /// </summary>
- public readonly float Diameter => Radius * 2.0f;
- /// <summary>
- /// Gets the circumference (perimeter) of the circle, representing the total distance around the circular boundary.
- /// </summary>
- public readonly float Circumference => MathHelper.TwoPi * Radius;
- /// <summary>
- /// Gets the area enclosed by the circular boundary, representing the total space within the circle.
- /// </summary>
- public readonly float Area => MathHelper.Pi * Radius * Radius;
- #endregion
- #region Constructors
- /// <summary>
- /// Initializes a new circle with the specified center and radius.
- /// </summary>
- /// <param name="center">The center position of the circle.</param>
- /// <param name="radius">The radius defining the circular boundary.</param>
- public Circle(Vector2 center, float radius)
- {
- Center = center;
- Radius = radius;
- }
- /// <summary>
- /// Initializes a new circle with the specified center coordinates and radius.
- /// </summary>
- /// <param name="x">The X coordinate of the center position.</param>
- /// <param name="y">The Y coordinate of the center position.</param>
- /// <param name="radius">The radius defining the circular boundary.</param>
- public Circle(float x, float y, float radius)
- {
- Center = new Vector2(x, y);
- Radius = radius;
- }
- #endregion
- #region Create From Methods
- /// <summary>
- /// Creates a circle that circumscribes the rectangular region defined by two corner points.
- /// </summary>
- /// <param name="minimum">The minimum corner coordinates (typically top-left).</param>
- /// <param name="maximum">The maximum corner coordinates (typically bottom-right).</param>
- /// <returns>A circle centered at the midpoint with radius equal to half the larger dimension of the bounding rectangle.</returns>
- /// <remarks>
- /// The circle is guaranteed to contain the entire rectangular region defined by the corner points.
- /// </remarks>
- public static Circle CreateFrom(Vector2 minimum, Vector2 maximum)
- {
- Vector2 center = new Vector2(maximum.X + minimum.X, maximum.Y + minimum.Y) * 0.5f;
- Vector2 distance = maximum - minimum;
- float radius = distance.X > distance.Y
- ? distance.X * 0.5f
- : distance.Y * 0.5f;
- return new Circle(center, radius);
- }
- /// <summary>
- /// Creates the smallest circle that contains all specified points using a centroid-based approximation.
- /// </summary>
- /// <param name="points">The collection of points to enclose.</param>
- /// <returns>A circle centered at the centroid of all points with radius extending to the farthest point, or <see cref="Empty"/> if no points are provided.</returns>
- /// <exception cref="ArgumentNullException">Thrown when <paramref name="points"/> is null.</exception>
- /// <remarks>
- /// This method uses a simple but effective approximation algorithm that computes the centroid (arithmetic mean)
- /// of all points and sets the radius to the distance from the centroid to the farthest point. While this does
- /// not guarantee the mathematically smallest enclosing circle, it provides a good approximation with O(n) time complexity.
- /// </remarks>
- public static Circle CreateFrom(IReadOnlyList<Vector2> points)
- {
- if (points == null || points.Count == 0)
- {
- return Empty;
- }
- RectangleF bounds = RectangleF.CreateFrom(points);
- Vector2 center = bounds.Center;
- float maxDistSquared = 0.0f;
- for (int i = 0; i < points.Count; i++)
- {
- float distSquared = Vector2.DistanceSquared(center, points[i]);
- if (distSquared > maxDistSquared)
- {
- maxDistSquared = distSquared;
- }
- }
- float radius = MathF.Sqrt(maxDistSquared);
- return new Circle(center, radius);
- }
- #endregion
- #region Containment Methods
- /// <summary>
- /// Determines whether the circular boundary contains the specified point.
- /// </summary>
- /// <param name="point">The point to test for containment.</param>
- /// <returns><c>true</c> if the point lies within or on the circular boundary; otherwise, <c>false</c>.</returns>
- /// <remarks>
- /// Points exactly on the boundary are considered contained.
- /// </remarks>
- public readonly bool Contains(Vector2 point)
- {
- float distanceSquared = Vector2.DistanceSquared(Center, point);
- return distanceSquared <= Radius * Radius;
- }
- /// <summary>
- /// Determines whether the circular boundary contains the point at the specified coordinates.
- /// </summary>
- /// <param name="x">The X coordinate of the point to test.</param>
- /// <param name="y">The Y coordinate of the point to test.</param>
- /// <returns><c>true</c> if the point lies within or on the circular boundary; otherwise, <c>false</c>.</returns>
- /// <remarks>
- /// Points exactly on the boundary are considered contained.
- /// </remarks>
- public readonly bool Contains(float x, float y)
- {
- return Contains(new Vector2(x, y));
- }
- #endregion
- #region Intersection Methods
- /// <summary>
- /// Determines whether this circle intersects with another circle.
- /// </summary>
- /// <param name="other">The other circle to test for intersection.</param>
- /// <returns>
- /// <see langword="true"/> if this circle intersects the other; otherwise, <see langword="false"/>.
- /// </returns>
- public readonly bool Intersects(Circle other) => IntersectionTests.CircleCircle(in this, in other);
- /// <summary>
- /// Determines whether this circle intersects with an ellipse
- /// </summary>
- /// <param name="ellipse">The ellipse to test for intersection.</param>
- /// <returns>
- /// <see langword="true"/> if this circle intersects the ellipse; otherwise, <see langword="false"/>.
- /// </returns>
- public readonly bool Intersects(Ellipse ellipse) => IntersectionTests.CircleEllipse(in this, in ellipse);
- /// <summary>
- /// Determines whether this circle intersects with a rectangle
- /// </summary>
- /// <param name="rectangle">The rectangle to test for intersection.</param>
- /// <returns>
- /// <see langword="true"/> if this circle intersects the rectangle; otherwise, <see langword="false"/>.
- /// </returns>
- public readonly bool Intersects(RectangleF rectangle) => IntersectionTests.CircleRectangleF(in this, in rectangle);
- /// <summary>
- /// Determines whether this circle intersects with a ray
- /// </summary>
- /// <param name="ray">The ray to test for intersection.</param>
- /// <returns>
- /// <see langword="true"/> if this circle intersects the ray; otherwise, <see langword="false"/>.
- /// </returns>
- public readonly bool Intersects(Ray ray) => IntersectionTests.CircleRay(in this, in ray);
- /// <summary>
- /// Determines whether this circle intersects with a line segment
- /// </summary>
- /// <param name="lineSegment">The line segment to test for intersection.</param>
- /// <returns>
- /// <see langword="true"/> if this circle intersects the line segment; otherwise, <see langword="false"/>.
- /// </returns>
- public readonly bool Intersects(LineSegment lineSegment) => IntersectionTests.CirceLineSegment(in this, in lineSegment);
- #endregion
- #region Closest Point To Methods
- /// <summary>
- /// Computes the closest point on the circular boundary to the specified point.
- /// </summary>
- /// <param name="point">The query point for closest-point computation.</param>
- /// <returns>The point on the circular perimeter closest to the query point.</returns>
- /// <remarks>
- /// When the query point is at the circle center, returns a point on the positive X-axis.
- /// </remarks>
- public readonly Vector2 ClosestPointTo(Vector2 point)
- {
- Vector2 direction = point - Center;
- float length = direction.Length();
- if (length < 0.001f)
- {
- // Point is at the center, return any point on the circle
- return Center + new Vector2(Radius, 0);
- }
- return Center + direction * (Radius / length);
- }
- #endregion
- #region Distance Methods
- /// <summary>
- /// Computes the squared distance from a point to the circular boundary,
- /// optimized to avoid square root calculation in distance queries.
- /// </summary>
- /// <param name="point">The query point for distance computation.</param>
- /// <returns>The squared distance to the boundary, or zero if the point lies within the circle.</returns>
- public readonly float SquaredDistanceTo(Vector2 point)
- {
- float distanceToCenter = Vector2.Distance(Center, point);
- float distanceToBoundary = distanceToCenter - Radius;
- // If point is inside the circle, distance is 0
- if (distanceToBoundary < 0.0f)
- {
- return 0.0f;
- }
- return distanceToBoundary * distanceToBoundary;
- }
- /// <summary>
- /// Computes the distance from a point to the circular boundary.
- /// </summary>
- /// <param name="point">The query point for distance computation.</param>
- /// <returns>The distance to the boundary, or zero if the point lies within the circle.</returns>
- public readonly float DistanceTo(Vector2 point)
- {
- float distanceToCenter = Vector2.Distance(Center, point);
- float distanceToBoundary = distanceToCenter - Radius;
- // if point is inside the circle, distance is 0
- if (distanceToBoundary < 0.0f)
- {
- return 0.0f;
- }
- return distanceToBoundary;
- }
- #endregion
- #region Offset Methods
- /// <summary>
- /// Translates the circle by moving its center position, preserving the radius.
- /// </summary>
- /// <param name="offset">The translation vector to apply to the center position.</param>
- public void Offset(Vector2 offset)
- {
- Center += offset;
- }
- /// <summary>
- /// Creates a new circle translated by the specified offset vector.
- /// </summary>
- /// <param name="circle">The circle to translate.</param>
- /// <param name="offset">The translation vector to apply.</param>
- /// <returns>A new circle with the translated center position.</returns>
- public static Circle Offset(Circle circle, Vector2 offset)
- {
- return circle with { Center = circle.Center + offset };
- }
- #endregion
- #region Inflate Methods
- /// <summary>
- /// Modifies the radius to expand or contract the circular boundary.
- /// </summary>
- /// <param name="amount">The value to add to the radius. Negative values contract the circle.</param>
- public void Inflate(float amount)
- {
- Radius += amount;
- }
- /// <summary>
- /// Creates a new circle with the radius modified by the specified amount.
- /// </summary>
- /// <param name="circle">The circle to inflate or deflate.</param>
- /// <param name="amount">The value to add to the radius. Negative values contract the circle.</param>
- /// <returns>A new circle with the modified radius.</returns>
- public static Circle Inflate(Circle circle, float amount)
- {
- return circle with { Radius = circle.Radius + amount };
- }
- #endregion
- #region Transform Methods
- /// <summary>
- /// Applies a 2D transformation matrix to the circle, transforming both position and scale.
- /// </summary>
- /// <param name="matrix">The transformation matrix to apply.</param>
- /// <remarks>
- /// The radius is scaled using the maximum scale factor from the matrix to preserve
- /// the circular shape under non-uniform transformations.
- /// </remarks>
- public void Transform(Matrix3x2 matrix)
- {
- Transform(ref matrix);
- }
- /// <summary>
- /// Applies a 2D transformation matrix to the circle using reference parameters.
- /// </summary>
- /// <param name="matrix">The transformation matrix to apply.</param>
- /// <remarks>
- /// The radius is scaled using the maximum scale factor from the matrix to preserve
- /// the circular shape under non-uniform transformations.
- /// </remarks>
- public void Transform(ref Matrix3x2 matrix)
- {
- Center = matrix.Transform(Center);
- // Extract scale from matrix using maximum scale for non-uniform scale
- float scaleX = MathF.Sqrt(matrix.M11 * matrix.M11 + matrix.M12 * matrix.M12);
- float scaleY = MathF.Sqrt(matrix.M21 * matrix.M21 + matrix.M22 * matrix.M22);
- float scale = MathF.Max(scaleX, scaleY);
- Radius *= scale;
- }
- /// <summary>
- /// Creates a new circle by applying a 2D transformation matrix.
- /// </summary>
- /// <param name="circle">The circle to transform.</param>
- /// <param name="matrix">The transformation matrix to apply.</param>
- /// <returns>A new transformed circle.</returns>
- /// <remarks>
- /// The radius is scaled using the maximum scale factor from the matrix to preserve
- /// the circular shape under non-uniform transformations.
- /// </remarks>
- public static Circle Transform(Circle circle, Matrix3x2 matrix)
- {
- Transform(ref circle, ref matrix);
- return circle;
- }
- /// <summary>
- /// Computes a transformed circle using reference parameters for performance.
- /// </summary>
- /// <param name="circle">The circle to transform.</param>
- /// <param name="matrix">The transformation matrix to apply.</param>
- /// <remarks>
- /// The radius is scaled using the maximum scale factor from the matrix to preserve
- /// the circular shape under non-uniform transformations.
- /// </remarks>
- public static void Transform(ref Circle circle, ref Matrix3x2 matrix)
- {
- circle.Center = matrix.Transform(circle.Center);
- // Extract scale from matrix using maximum scale for non-uniform scale
- float scaleX = MathF.Sqrt(matrix.M11 * matrix.M11 + matrix.M12 * matrix.M12);
- float scaleY = MathF.Sqrt(matrix.M21 * matrix.M21 + matrix.M22 * matrix.M22);
- float scale = MathF.Max(scaleX, scaleY);
- circle.Radius *= scale;
- }
- #endregion
- /// <summary>
- /// Fills the provided buffer with points that approximate the circle as a polygon.
- /// </summary>
- /// <param name="buffer">
- /// The buffer to fill with polygon vertices. The number of vertices equals the buffer length.
- /// </param>
- /// <remarks>
- /// Distributes points evenly around the circle perimeter.
- /// </remarks>
- public readonly void ToPolygon(Span<Vector2> buffer)
- {
- int count = buffer.Length;
- float step = MathHelper.TwoPi / count;
- for (int i = 0; i < count; i++)
- {
- float t = step * i;
- buffer[i] = new Vector2(
- Center.X + Radius * MathF.Cos(t),
- Center.Y + Radius * MathF.Sin(t)
- );
- }
- }
- #region Equality Methods
- /// <summary>
- /// Determines whether this circle is equal to the specified object.
- /// </summary>
- /// <param name="obj">The object to compare.</param>
- /// <returns>
- /// <c>true</c> if the object is a <see cref="Circle"/> with the same center and radius; otherwise, <c>false</c>.
- /// </returns>
- public override readonly bool Equals([NotNullWhen(true)] object obj)
- {
- return obj is Circle other && Equals(other);
- }
- /// <summary>
- /// Determines whether this circle is equal to another circle.
- /// </summary>
- /// <param name="other">The circle to compare with this circle.</param>
- /// <returns><c>true</c> if the circles have the same center and radius; otherwise, <c>false</c>.</returns>
- public readonly bool Equals(Circle other)
- {
- return Center.Equals(other.Center) && Radius.Equals(other.Radius);
- }
- #endregion
- /// <summary>
- /// Computes the hash code for this circle.
- /// </summary>
- /// <returns>A hash code derived from the center position and radius.</returns>
- public override readonly int GetHashCode() => HashCode.Combine(Center, Radius);
- /// <summary>
- /// Creates a string representation of this circle.
- /// </summary>
- /// <returns>A formatted string containing the center and radius values.</returns>
- public override readonly string ToString()
- {
- return $"Circle(Center: {Center}, Radius: {Radius})";
- }
- internal readonly string DebugDisplayString => ToString();
- #region Operators
- /// <summary>
- /// Tests whether two circles are equal.
- /// </summary>
- /// <param name="left">The first circle.</param>
- /// <param name="right">The second circle.</param>
- /// <returns><c>true</c> if both circles have the same center and radius; otherwise, <c>false</c>.</returns>
- public static bool operator ==(Circle left, Circle right)
- {
- return left.Equals(right);
- }
- /// <summary>
- /// Tests whether two circles are not equal.
- /// </summary>
- /// <param name="left">The first circle.</param>
- /// <param name="right">The second circle.</param>
- /// <returns><c>true</c> if the circles have different centers or radii; otherwise, <c>false</c>.</returns>
- public static bool operator !=(Circle left, Circle right)
- {
- return !left.Equals(right);
- }
- #endregion
- }
|