| | | 1 | | //======================================================================= |
| | | 2 | | // FixedBoundSphere.cs |
| | | 3 | | //======================================================================= |
| | | 4 | | // MIT License, Copyright (c) 2024-present David Oravsky (mrdav30) |
| | | 5 | | // See LICENSE file in the project root for full license information. |
| | | 6 | | //======================================================================= |
| | | 7 | | |
| | | 8 | | using System; |
| | | 9 | | using System.Collections.Generic; |
| | | 10 | | using System.Globalization; |
| | | 11 | | using System.Runtime.CompilerServices; |
| | | 12 | | using System.Text.Json.Serialization; |
| | | 13 | | using MemoryPack; |
| | | 14 | | |
| | | 15 | | namespace FixedMathSharp.Geometry; |
| | | 16 | | |
| | | 17 | | /// <summary> |
| | | 18 | | /// Represents a spherical bounding volume with fixed-point precision, optimized for fast, |
| | | 19 | | /// rotationally invariant spatial checks in 3D space. |
| | | 20 | | /// </summary> |
| | | 21 | | /// <remarks> |
| | | 22 | | /// The FixedBoundSphere provides a simple yet effective way to represent the spatial extent of objects, |
| | | 23 | | /// especially when rotational invariance is required. |
| | | 24 | | /// Compared to FixedBoundBox, it offers faster intersection checks but is less precise in |
| | | 25 | | /// tightly fitting non-spherical objects. |
| | | 26 | | /// |
| | | 27 | | /// Use Cases: |
| | | 28 | | /// - Ideal for broad-phase collision detection, proximity checks, and culling in physics engines and rendering pipeline |
| | | 29 | | /// - Useful when fast, rotationally invariant checks are needed, such as detecting overlaps or distances between moving |
| | | 30 | | /// - Suitable for encapsulating objects with roughly spherical shapes or objects that rotate frequently, where the boun |
| | | 31 | | /// </remarks> |
| | | 32 | | [Serializable] |
| | | 33 | | [MemoryPackable] |
| | | 34 | | public partial struct FixedBoundSphere : IEquatable<FixedBoundSphere>, IFormattable |
| | | 35 | | #if NET10_0_OR_GREATER |
| | | 36 | | , ISpanFormattable |
| | | 37 | | #endif |
| | | 38 | | { |
| | | 39 | | |
| | | 40 | | #region Fields |
| | | 41 | | |
| | | 42 | | /// <summary> |
| | | 43 | | /// The radius backing field. |
| | | 44 | | /// </summary> |
| | | 45 | | [JsonIgnore] |
| | | 46 | | [MemoryPackIgnore] |
| | | 47 | | private Fixed64 _radius; |
| | | 48 | | |
| | | 49 | | #endregion |
| | | 50 | | |
| | | 51 | | #region Constructors |
| | | 52 | | |
| | | 53 | | /// <summary> |
| | | 54 | | /// Initializes a new instance of the FixedBoundSphere struct with the specified center and radius. |
| | | 55 | | /// </summary> |
| | | 56 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 57 | | public FixedBoundSphere(Vector3d center, Fixed64 radius) |
| | | 58 | | { |
| | 272 | 59 | | Center = center; |
| | 272 | 60 | | _radius = NormalizeRadius(radius); |
| | 272 | 61 | | } |
| | | 62 | | |
| | | 63 | | /// <summary> |
| | | 64 | | /// Initializes a new instance from serialized or caller-provided state. |
| | | 65 | | /// </summary> |
| | | 66 | | [JsonConstructor] |
| | | 67 | | public FixedBoundSphere(BoundingSphereState state) |
| | | 68 | | { |
| | 3 | 69 | | Center = state.Center; |
| | 3 | 70 | | _radius = state.Radius; |
| | 3 | 71 | | } |
| | | 72 | | |
| | | 73 | | #endregion |
| | | 74 | | |
| | | 75 | | #region Properties |
| | | 76 | | |
| | | 77 | | /// <summary> |
| | | 78 | | /// The center point of the sphere. |
| | | 79 | | /// </summary> |
| | | 80 | | [JsonIgnore] |
| | | 81 | | [MemoryPackIgnore] |
| | | 82 | | public Vector3d Center { get; set; } |
| | | 83 | | |
| | | 84 | | /// <summary> |
| | | 85 | | /// The non-negative radius of the sphere. Assigned values are normalized by absolute value. |
| | | 86 | | /// </summary> |
| | | 87 | | [JsonIgnore] |
| | | 88 | | [MemoryPackIgnore] |
| | | 89 | | public Fixed64 Radius |
| | | 90 | | { |
| | | 91 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 1184 | 92 | | get => _radius; |
| | | 93 | | |
| | | 94 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 1 | 95 | | set => _radius = NormalizeRadius(value); |
| | | 96 | | } |
| | | 97 | | |
| | | 98 | | /// <summary> |
| | | 99 | | /// Gets the coordinates of the minimum corner of the bounding box that contains the sphere. |
| | | 100 | | /// </summary> |
| | | 101 | | /// <remarks> |
| | | 102 | | /// The minimum corner is calculated by subtracting the radius from each component of the sphere's center. |
| | | 103 | | /// This property is useful for spatial queries and bounding box calculations. |
| | | 104 | | /// </remarks> |
| | | 105 | | [JsonIgnore] |
| | | 106 | | [MemoryPackIgnore] |
| | | 107 | | public Vector3d Min |
| | | 108 | | { |
| | | 109 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 3 | 110 | | get => Center - new Vector3d(Radius, Radius, Radius); |
| | | 111 | | } |
| | | 112 | | |
| | | 113 | | /// <summary> |
| | | 114 | | /// Gets the coordinates of the maximum corner of the bounding box that contains the sphere. |
| | | 115 | | /// </summary> |
| | | 116 | | /// <remarks> |
| | | 117 | | /// The maximum corner is calculated as the center of the sphere plus the radius in each dimension. |
| | | 118 | | /// This property is useful for spatial queries and bounding volume calculations. |
| | | 119 | | /// </remarks> |
| | | 120 | | [JsonIgnore] |
| | | 121 | | [MemoryPackIgnore] |
| | | 122 | | public Vector3d Max |
| | | 123 | | { |
| | | 124 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 3 | 125 | | get => Center + new Vector3d(Radius, Radius, Radius); |
| | | 126 | | } |
| | | 127 | | |
| | | 128 | | /// <summary> |
| | | 129 | | /// Gets the current normalized state of the sphere. |
| | | 130 | | /// </summary> |
| | | 131 | | [JsonInclude] |
| | | 132 | | [MemoryPackInclude] |
| | 3 | 133 | | public BoundingSphereState State => new(Center, Radius); |
| | | 134 | | |
| | | 135 | | #endregion |
| | | 136 | | |
| | | 137 | | #region Methods (Static) |
| | | 138 | | |
| | | 139 | | /// <summary> |
| | | 140 | | /// Creates a bounding sphere that contains the specified axis-aligned bounding box. |
| | | 141 | | /// </summary> |
| | | 142 | | /// <exception cref="OverflowException"> |
| | | 143 | | /// Thrown when this construction requires an unrepresentable radius. |
| | | 144 | | /// </exception> |
| | | 145 | | public static FixedBoundSphere CreateFromBoundingBox(FixedBoundBox box) |
| | | 146 | | { |
| | 4 | 147 | | Vector3d center = Vector3d.Midpoint(box.Min, box.Max); |
| | 4 | 148 | | Vector3d farthestCorner = new( |
| | 4 | 149 | | GetFartherEndpoint(box.Min.X, box.Max.X, center.X), |
| | 4 | 150 | | GetFartherEndpoint(box.Min.Y, box.Max.Y, center.Y), |
| | 4 | 151 | | GetFartherEndpoint(box.Min.Z, box.Max.Z, center.Z)); |
| | 4 | 152 | | if (!TryGetRequiredRadius(center, farthestCorner, Fixed64.Zero, out Fixed64 radius)) |
| | 1 | 153 | | throw CreateUnrepresentableRadiusException(); |
| | | 154 | | |
| | 3 | 155 | | return new FixedBoundSphere(center, radius); |
| | | 156 | | } |
| | | 157 | | |
| | | 158 | | /// <summary> |
| | | 159 | | /// Creates a bounding sphere that contains the specified frustum. |
| | | 160 | | /// </summary> |
| | | 161 | | /// <exception cref="OverflowException"> |
| | | 162 | | /// Thrown when this construction requires an unrepresentable radius. |
| | | 163 | | /// </exception> |
| | | 164 | | public static FixedBoundSphere CreateFromFrustum(FixedBoundFrustum frustum) |
| | | 165 | | { |
| | 7 | 166 | | return CreateFromFrustumCorners(frustum); |
| | | 167 | | } |
| | | 168 | | |
| | | 169 | | /// <summary> |
| | | 170 | | /// Creates a bounding sphere that contains the specified points. |
| | | 171 | | /// </summary> |
| | | 172 | | /// <exception cref="OverflowException"> |
| | | 173 | | /// Thrown when this construction requires an unrepresentable radius. |
| | | 174 | | /// </exception> |
| | | 175 | | public static FixedBoundSphere CreateFromPoints(IEnumerable<Vector3d> points) |
| | | 176 | | { |
| | 6 | 177 | | if (points is null) |
| | 1 | 178 | | throw new ArgumentNullException(nameof(points), "Cannot create a bounding sphere from a null collection of p |
| | | 179 | | |
| | 5 | 180 | | if (points is IReadOnlyList<Vector3d> pointList) |
| | 4 | 181 | | return CreateFromPointList(pointList); |
| | | 182 | | |
| | 1 | 183 | | var materialized = new List<Vector3d>(); |
| | 10 | 184 | | foreach (Vector3d point in points) |
| | 4 | 185 | | materialized.Add(point); |
| | | 186 | | |
| | 1 | 187 | | return CreateFromPointList(materialized); |
| | | 188 | | } |
| | | 189 | | |
| | | 190 | | /// <summary> |
| | | 191 | | /// Creates a bounding sphere that contains the specified points. |
| | | 192 | | /// </summary> |
| | | 193 | | /// <exception cref="OverflowException"> |
| | | 194 | | /// Thrown when this construction requires an unrepresentable radius. |
| | | 195 | | /// </exception> |
| | | 196 | | public static FixedBoundSphere CreateFromPoints(Vector3d[] points) |
| | | 197 | | { |
| | 10 | 198 | | if (points is null) |
| | 1 | 199 | | throw new ArgumentNullException(nameof(points), "Cannot create a bounding sphere from a null collection of p |
| | | 200 | | |
| | 9 | 201 | | return CreateFromPoints(points.AsSpan()); |
| | | 202 | | } |
| | | 203 | | |
| | | 204 | | /// <summary> |
| | | 205 | | /// Creates a bounding sphere that contains the specified points. |
| | | 206 | | /// </summary> |
| | | 207 | | /// <exception cref="OverflowException"> |
| | | 208 | | /// Thrown when this construction requires an unrepresentable radius. |
| | | 209 | | /// </exception> |
| | | 210 | | public static FixedBoundSphere CreateFromPoints(ReadOnlySpan<Vector3d> points) |
| | | 211 | | { |
| | 14 | 212 | | return CreateFromPointSpan(points); |
| | | 213 | | } |
| | | 214 | | |
| | | 215 | | /// <summary> |
| | | 216 | | /// Creates a deterministic sphere that contains the two specified spheres. |
| | | 217 | | /// </summary> |
| | | 218 | | /// <exception cref="OverflowException"> |
| | | 219 | | /// Thrown when this construction cannot produce a containing sphere with a |
| | | 220 | | /// representable radius. |
| | | 221 | | /// </exception> |
| | | 222 | | public static FixedBoundSphere CreateMerged(FixedBoundSphere original, FixedBoundSphere additional) |
| | | 223 | | { |
| | 13 | 224 | | if (ContainsSphere(original, additional)) |
| | 2 | 225 | | return original; |
| | | 226 | | |
| | 11 | 227 | | if (ContainsSphere(additional, original)) |
| | 2 | 228 | | return additional; |
| | | 229 | | |
| | 9 | 230 | | return MergeNonContaining(original, additional); |
| | | 231 | | } |
| | | 232 | | |
| | | 233 | | private static FixedBoundSphere MergeNonContaining( |
| | | 234 | | FixedBoundSphere original, |
| | | 235 | | FixedBoundSphere additional) |
| | | 236 | | { |
| | | 237 | | |
| | 36 | 238 | | GetDistanceRoot(original.Center, additional.Center, out Signed192 distanceFloor, out Signed192 distanceRemainder |
| | 36 | 239 | | if (!TryGetMergedRadius( |
| | 36 | 240 | | distanceFloor, |
| | 36 | 241 | | distanceRemainder, |
| | 36 | 242 | | original.Radius, |
| | 36 | 243 | | additional.Radius, |
| | 36 | 244 | | out Fixed64 radius)) |
| | | 245 | | { |
| | 1 | 246 | | throw CreateUnrepresentableRadiusException(); |
| | | 247 | | } |
| | | 248 | | |
| | 35 | 249 | | Signed192 firstGap = Signed192.Signed( |
| | 35 | 250 | | (radius - original.Radius).m_rawValue); |
| | 35 | 251 | | Signed192 secondGap = Signed192.Signed( |
| | 35 | 252 | | (radius - additional.Radius).m_rawValue); |
| | 35 | 253 | | Signed192 gapSum = WideArithmetic.AddSigned192(firstGap, secondGap); |
| | 35 | 254 | | Vector3d center = new( |
| | 35 | 255 | | WideGeometry.InterpolateCoordinate( |
| | 35 | 256 | | original.Center.X, |
| | 35 | 257 | | additional.Center.X, |
| | 35 | 258 | | firstGap, |
| | 35 | 259 | | gapSum), |
| | 35 | 260 | | WideGeometry.InterpolateCoordinate( |
| | 35 | 261 | | original.Center.Y, |
| | 35 | 262 | | additional.Center.Y, |
| | 35 | 263 | | firstGap, |
| | 35 | 264 | | gapSum), |
| | 35 | 265 | | WideGeometry.InterpolateCoordinate( |
| | 35 | 266 | | original.Center.Z, |
| | 35 | 267 | | additional.Center.Z, |
| | 35 | 268 | | firstGap, |
| | 35 | 269 | | gapSum)); |
| | | 270 | | |
| | 35 | 271 | | var merged = new FixedBoundSphere(center, radius); |
| | 35 | 272 | | bool containsOriginal = ContainsSphere(merged, original); |
| | 35 | 273 | | bool containsAdditional = ContainsSphere(merged, additional); |
| | 35 | 274 | | if (containsOriginal & containsAdditional) |
| | 15 | 275 | | return merged; |
| | | 276 | | |
| | 20 | 277 | | bool originalRadiusRepresentable = TryGetRequiredRadius( |
| | 20 | 278 | | center, |
| | 20 | 279 | | original.Center, |
| | 20 | 280 | | original.Radius, |
| | 20 | 281 | | out Fixed64 originalRequired); |
| | 20 | 282 | | bool additionalRadiusRepresentable = TryGetRequiredRadius( |
| | 20 | 283 | | center, |
| | 20 | 284 | | additional.Center, |
| | 20 | 285 | | additional.Radius, |
| | 20 | 286 | | out Fixed64 additionalRequired); |
| | 20 | 287 | | if (!(originalRadiusRepresentable & additionalRadiusRepresentable)) |
| | | 288 | | { |
| | 1 | 289 | | throw CreateUnrepresentableRadiusException(); |
| | | 290 | | } |
| | | 291 | | |
| | 19 | 292 | | return new FixedBoundSphere( |
| | 19 | 293 | | center, |
| | 19 | 294 | | originalRequired >= additionalRequired ? originalRequired : additionalRequired); |
| | | 295 | | } |
| | | 296 | | |
| | | 297 | | private static FixedBoundSphere CreateFromPointList(IReadOnlyList<Vector3d> points) |
| | | 298 | | { |
| | 5 | 299 | | if (points.Count == 0) |
| | 1 | 300 | | throw new ArgumentException("At least one point is required to create a bounding sphere."); |
| | | 301 | | |
| | 4 | 302 | | Vector3d minX = points[0]; |
| | 4 | 303 | | Vector3d maxX = points[0]; |
| | 4 | 304 | | Vector3d minY = points[0]; |
| | 4 | 305 | | Vector3d maxY = points[0]; |
| | 4 | 306 | | Vector3d minZ = points[0]; |
| | 4 | 307 | | Vector3d maxZ = points[0]; |
| | | 308 | | |
| | 24 | 309 | | for (int i = 1; i < points.Count; i++) |
| | | 310 | | { |
| | 8 | 311 | | Vector3d point = points[i]; |
| | | 312 | | |
| | 9 | 313 | | if (point.X < minX.X) minX = point; |
| | 11 | 314 | | if (point.X > maxX.X) maxX = point; |
| | 9 | 315 | | if (point.Y < minY.Y) minY = point; |
| | 10 | 316 | | if (point.Y > maxY.Y) maxY = point; |
| | 9 | 317 | | if (point.Z < minZ.Z) minZ = point; |
| | 11 | 318 | | if (point.Z > maxZ.Z) maxZ = point; |
| | | 319 | | } |
| | | 320 | | |
| | 4 | 321 | | FixedBoundSphere sphere = CreateFromExtremePairs(minX, maxX, minY, maxY, minZ, maxZ); |
| | 32 | 322 | | for (int i = 0; i < points.Count; i++) |
| | 12 | 323 | | ExpandToContain(ref sphere, points[i]); |
| | | 324 | | |
| | 4 | 325 | | return sphere; |
| | | 326 | | } |
| | | 327 | | |
| | | 328 | | private static FixedBoundSphere CreateFromPointSpan(ReadOnlySpan<Vector3d> points) |
| | | 329 | | { |
| | 14 | 330 | | if (points.Length == 0) |
| | 2 | 331 | | throw new ArgumentException("At least one point is required to create a bounding sphere."); |
| | | 332 | | |
| | 12 | 333 | | Vector3d minX = points[0]; |
| | 12 | 334 | | Vector3d maxX = points[0]; |
| | 12 | 335 | | Vector3d minY = points[0]; |
| | 12 | 336 | | Vector3d maxY = points[0]; |
| | 12 | 337 | | Vector3d minZ = points[0]; |
| | 12 | 338 | | Vector3d maxZ = points[0]; |
| | | 339 | | |
| | 80 | 340 | | for (int i = 1; i < points.Length; i++) |
| | | 341 | | { |
| | 28 | 342 | | Vector3d point = points[i]; |
| | | 343 | | |
| | 30 | 344 | | if (point.X < minX.X) minX = point; |
| | 40 | 345 | | if (point.X > maxX.X) maxX = point; |
| | 31 | 346 | | if (point.Y < minY.Y) minY = point; |
| | 37 | 347 | | if (point.Y > maxY.Y) maxY = point; |
| | 31 | 348 | | if (point.Z < minZ.Z) minZ = point; |
| | 30 | 349 | | if (point.Z > maxZ.Z) maxZ = point; |
| | | 350 | | } |
| | | 351 | | |
| | 12 | 352 | | FixedBoundSphere sphere = CreateFromExtremePairs(minX, maxX, minY, maxY, minZ, maxZ); |
| | 98 | 353 | | for (int i = 0; i < points.Length; i++) |
| | 38 | 354 | | ExpandToContain(ref sphere, points[i]); |
| | | 355 | | |
| | 11 | 356 | | return sphere; |
| | | 357 | | } |
| | | 358 | | |
| | | 359 | | private static FixedBoundSphere CreateFromFrustumCorners(FixedBoundFrustum frustum) |
| | | 360 | | { |
| | 7 | 361 | | Vector3d minX = frustum.GetCorner(0); |
| | 7 | 362 | | Vector3d maxX = minX; |
| | 7 | 363 | | Vector3d minY = minX; |
| | 7 | 364 | | Vector3d maxY = minX; |
| | 7 | 365 | | Vector3d minZ = minX; |
| | 7 | 366 | | Vector3d maxZ = minX; |
| | | 367 | | |
| | 112 | 368 | | for (int i = 1; i < FixedBoundFrustum.CornerCount; i++) |
| | | 369 | | { |
| | 49 | 370 | | Vector3d point = frustum.GetCorner(i); |
| | | 371 | | |
| | 51 | 372 | | if (point.X < minX.X) minX = point; |
| | 56 | 373 | | if (point.X > maxX.X) maxX = point; |
| | 56 | 374 | | if (point.Y < minY.Y) minY = point; |
| | 51 | 375 | | if (point.Y > maxY.Y) maxY = point; |
| | 50 | 376 | | if (point.Z < minZ.Z) minZ = point; |
| | 58 | 377 | | if (point.Z > maxZ.Z) maxZ = point; |
| | | 378 | | } |
| | | 379 | | |
| | 7 | 380 | | FixedBoundSphere sphere = CreateFromExtremePairs(minX, maxX, minY, maxY, minZ, maxZ); |
| | 126 | 381 | | for (int i = 0; i < FixedBoundFrustum.CornerCount; i++) |
| | 56 | 382 | | ExpandToContain(ref sphere, frustum.GetCorner(i)); |
| | | 383 | | |
| | 7 | 384 | | return sphere; |
| | | 385 | | } |
| | | 386 | | |
| | | 387 | | private static FixedBoundSphere CreateFromExtremePairs( |
| | | 388 | | Vector3d minX, |
| | | 389 | | Vector3d maxX, |
| | | 390 | | Vector3d minY, |
| | | 391 | | Vector3d maxY, |
| | | 392 | | Vector3d minZ, |
| | | 393 | | Vector3d maxZ) |
| | | 394 | | { |
| | 23 | 395 | | Vector3d min = minX; |
| | 23 | 396 | | Vector3d max = maxX; |
| | 23 | 397 | | if (Vector3d.CompareDistanceSquared(minY, maxY, min, max) > 0) |
| | | 398 | | { |
| | 13 | 399 | | min = minY; |
| | 13 | 400 | | max = maxY; |
| | | 401 | | } |
| | 23 | 402 | | if (Vector3d.CompareDistanceSquared(minZ, maxZ, min, max) > 0) |
| | | 403 | | { |
| | 5 | 404 | | min = minZ; |
| | 5 | 405 | | max = maxZ; |
| | | 406 | | } |
| | | 407 | | |
| | 23 | 408 | | Vector3d center = Vector3d.Midpoint(min, max); |
| | 23 | 409 | | Vector3d farthest = Vector3d.CompareDistanceSquared(center, min, center, max) > 0 |
| | 23 | 410 | | ? min |
| | 23 | 411 | | : max; |
| | 23 | 412 | | if (!TryGetRequiredRadius(center, farthest, Fixed64.Zero, out Fixed64 radius)) |
| | | 413 | | { |
| | 1 | 414 | | throw CreateUnrepresentableRadiusException(); |
| | | 415 | | } |
| | | 416 | | |
| | 22 | 417 | | return new FixedBoundSphere(center, radius); |
| | | 418 | | } |
| | | 419 | | |
| | | 420 | | private static void ExpandToContain(ref FixedBoundSphere sphere, Vector3d point) |
| | | 421 | | { |
| | 106 | 422 | | if (sphere.Contains(point)) |
| | 79 | 423 | | return; |
| | | 424 | | |
| | 27 | 425 | | sphere = MergeNonContaining(sphere, new FixedBoundSphere(point, Fixed64.Zero)); |
| | 27 | 426 | | } |
| | | 427 | | |
| | | 428 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 429 | | private static bool ContainsSphere(FixedBoundSphere outer, FixedBoundSphere inner) |
| | | 430 | | { |
| | 94 | 431 | | if (outer.Radius < inner.Radius) |
| | 5 | 432 | | return false; |
| | | 433 | | |
| | 89 | 434 | | return WideGeometry.CompareDistanceToRadiusSum( |
| | 89 | 435 | | outer.Center, |
| | 89 | 436 | | inner.Center, |
| | 89 | 437 | | outer.Radius - inner.Radius, |
| | 89 | 438 | | Fixed64.Zero) <= 0; |
| | | 439 | | } |
| | | 440 | | |
| | | 441 | | private static bool TryGetMergedRadius( |
| | | 442 | | Signed192 distanceFloor, |
| | | 443 | | Signed192 distanceRemainder, |
| | | 444 | | Fixed64 firstRadius, |
| | | 445 | | Fixed64 secondRadius, |
| | | 446 | | out Fixed64 radius) |
| | | 447 | | { |
| | 36 | 448 | | Signed192 sum = WideArithmetic.AddSigned192( |
| | 36 | 449 | | distanceFloor, |
| | 36 | 450 | | Signed192.Signed(firstRadius.m_rawValue)); |
| | 36 | 451 | | sum = WideArithmetic.AddSigned192( |
| | 36 | 452 | | sum, |
| | 36 | 453 | | Signed192.Signed(secondRadius.m_rawValue)); |
| | 36 | 454 | | bool roundUp = (sum.Low & 1UL) != 0UL || !distanceRemainder.IsZero; |
| | 36 | 455 | | WideArithmetic.GetMagnitude(sum, out ulong high, out ulong middle, out ulong low); |
| | 36 | 456 | | WideArithmetic.ShiftRightOne(ref high, ref middle, ref low); |
| | 36 | 457 | | if (roundUp) |
| | | 458 | | { |
| | 30 | 459 | | Signed192 rounded = WideArithmetic.AddSigned192( |
| | 30 | 460 | | new Signed192(high, middle, low), |
| | 30 | 461 | | Signed192.Signed(1L)); |
| | 30 | 462 | | high = rounded.High; |
| | 30 | 463 | | middle = rounded.Middle; |
| | 30 | 464 | | low = rounded.Low; |
| | | 465 | | } |
| | | 466 | | |
| | 36 | 467 | | return TryCreatePositiveRaw(high, middle, low, out radius); |
| | | 468 | | } |
| | | 469 | | |
| | | 470 | | private static bool TryGetRequiredRadius( |
| | | 471 | | Vector3d center, |
| | | 472 | | Vector3d enclosedCenter, |
| | | 473 | | Fixed64 enclosedRadius, |
| | | 474 | | out Fixed64 radius) |
| | | 475 | | { |
| | 67 | 476 | | GetDistanceRoot(center, enclosedCenter, out Signed192 distanceFloor, out Signed192 distanceRemainder); |
| | 67 | 477 | | if (!distanceRemainder.IsZero) |
| | | 478 | | { |
| | 55 | 479 | | distanceFloor = WideArithmetic.AddSigned192( |
| | 55 | 480 | | distanceFloor, |
| | 55 | 481 | | Signed192.Signed(1L)); |
| | | 482 | | } |
| | | 483 | | |
| | 67 | 484 | | Signed192 required = WideArithmetic.AddSigned192( |
| | 67 | 485 | | distanceFloor, |
| | 67 | 486 | | Signed192.Signed(enclosedRadius.m_rawValue)); |
| | 67 | 487 | | WideArithmetic.GetMagnitude(required, out ulong high, out ulong middle, out ulong low); |
| | 67 | 488 | | return TryCreatePositiveRaw(high, middle, low, out radius); |
| | | 489 | | } |
| | | 490 | | |
| | | 491 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 492 | | private static void GetDistanceRoot( |
| | | 493 | | Vector3d first, |
| | | 494 | | Vector3d second, |
| | | 495 | | out Signed192 floor, |
| | | 496 | | out Signed192 remainder) |
| | | 497 | | { |
| | 103 | 498 | | Signed192 squaredDistance = WideGeometry.GetDifferenceDotProduct3D( |
| | 103 | 499 | | first.X, second.X, first.Y, second.Y, first.Z, second.Z, |
| | 103 | 500 | | first.X, second.X, first.Y, second.Y, first.Z, second.Z); |
| | 103 | 501 | | floor = WideArithmetic.GetFloorSquareRoot( |
| | 103 | 502 | | Signed320.ExtendValue(squaredDistance), |
| | 103 | 503 | | out remainder); |
| | 103 | 504 | | } |
| | | 505 | | |
| | | 506 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 507 | | private static bool TryCreatePositiveRaw( |
| | | 508 | | ulong high, |
| | | 509 | | ulong middle, |
| | | 510 | | ulong low, |
| | | 511 | | out Fixed64 value) |
| | | 512 | | { |
| | 103 | 513 | | if ((high | middle | (low >> 63)) != 0UL) |
| | | 514 | | { |
| | 4 | 515 | | value = default; |
| | 4 | 516 | | return false; |
| | | 517 | | } |
| | | 518 | | |
| | 99 | 519 | | value = Fixed64.FromRaw((long)low); |
| | 99 | 520 | | return true; |
| | | 521 | | } |
| | | 522 | | |
| | | 523 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 524 | | private static Fixed64 GetFartherEndpoint(Fixed64 first, Fixed64 second, Fixed64 center) |
| | | 525 | | { |
| | 12 | 526 | | ulong firstDistance = GetRawDistance(first.m_rawValue, center.m_rawValue); |
| | 12 | 527 | | ulong secondDistance = GetRawDistance(second.m_rawValue, center.m_rawValue); |
| | 12 | 528 | | return firstDistance > secondDistance ? first : second; |
| | | 529 | | } |
| | | 530 | | |
| | | 531 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 532 | | private static ulong GetRawDistance(long first, long second) => |
| | 24 | 533 | | first >= second |
| | 24 | 534 | | ? unchecked((ulong)first - (ulong)second) |
| | 24 | 535 | | : unchecked((ulong)second - (ulong)first); |
| | | 536 | | |
| | | 537 | | private static OverflowException CreateUnrepresentableRadiusException() => |
| | 4 | 538 | | new("A containing sphere produced for the supplied geometry requires an unrepresentable radius."); |
| | | 539 | | |
| | | 540 | | #endregion |
| | | 541 | | |
| | | 542 | | #region Methods (Instance) |
| | | 543 | | |
| | | 544 | | /// <summary> |
| | | 545 | | /// Checks if a point is inside the sphere. |
| | | 546 | | /// </summary> |
| | | 547 | | /// <param name="point">The point to check.</param> |
| | | 548 | | /// <returns>True if the point is inside the sphere, otherwise false.</returns> |
| | | 549 | | public bool Contains(Vector3d point) |
| | | 550 | | { |
| | 227 | 551 | | return WideGeometry.CompareDistanceToRadiusSum(Center, point, Radius, Fixed64.Zero) <= 0; |
| | | 552 | | } |
| | | 553 | | |
| | | 554 | | /// <summary> |
| | | 555 | | /// Returns whether the point lies strictly inside this sphere. |
| | | 556 | | /// </summary> |
| | | 557 | | /// <remarks> |
| | | 558 | | /// Boundary points and every point tested against a zero-radius sphere |
| | | 559 | | /// return <see langword="false"/>. |
| | | 560 | | /// </remarks> |
| | | 561 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 562 | | public bool ContainsStrict(Vector3d point) => |
| | 3 | 563 | | Radius > Fixed64.Zero |
| | 3 | 564 | | && WideGeometry.CompareDistanceToRadiusSum(Center, point, Radius, Fixed64.Zero) < 0; |
| | | 565 | | |
| | | 566 | | /// <summary> |
| | | 567 | | /// Tests a bounding box against this sphere. |
| | | 568 | | /// </summary> |
| | | 569 | | public FixedEnclosureType Contains(FixedBoundBox box) |
| | | 570 | | { |
| | 13 | 571 | | return ContainsBoxLike(box.Min, box.Max); |
| | | 572 | | } |
| | | 573 | | |
| | | 574 | | /// <summary> |
| | | 575 | | /// Tests another sphere against this sphere. |
| | | 576 | | /// </summary> |
| | | 577 | | public FixedEnclosureType Contains(FixedBoundSphere sphere) |
| | | 578 | | { |
| | 19 | 579 | | if (WideGeometry.CompareDistanceToRadiusSum(Center, sphere.Center, Radius, sphere.Radius) > 0) |
| | 5 | 580 | | return FixedEnclosureType.Disjoint; |
| | | 581 | | |
| | 14 | 582 | | Fixed64 radiusDifference = Radius - sphere.Radius; |
| | 14 | 583 | | if (radiusDifference >= Fixed64.Zero |
| | 14 | 584 | | && WideGeometry.CompareDistanceToRadiusSum( |
| | 14 | 585 | | Center, |
| | 14 | 586 | | sphere.Center, |
| | 14 | 587 | | radiusDifference, |
| | 14 | 588 | | Fixed64.Zero) <= 0) |
| | 7 | 589 | | return FixedEnclosureType.Contains; |
| | | 590 | | |
| | 7 | 591 | | return FixedEnclosureType.Intersects; |
| | | 592 | | } |
| | | 593 | | |
| | | 594 | | /// <summary> |
| | | 595 | | /// Tests a frustum against this sphere. |
| | | 596 | | /// </summary> |
| | | 597 | | public FixedEnclosureType Contains(FixedBoundFrustum frustum) |
| | | 598 | | { |
| | 3 | 599 | | bool containsAllCorners = true; |
| | | 600 | | |
| | 22 | 601 | | for (int i = 0; i < FixedBoundFrustum.CornerCount; i++) |
| | | 602 | | { |
| | 10 | 603 | | if (!Contains(frustum.GetCorner(i))) |
| | | 604 | | { |
| | 2 | 605 | | containsAllCorners = false; |
| | 2 | 606 | | break; |
| | | 607 | | } |
| | | 608 | | } |
| | | 609 | | |
| | 3 | 610 | | if (containsAllCorners) |
| | 1 | 611 | | return FixedEnclosureType.Contains; |
| | | 612 | | |
| | 2 | 613 | | return frustum.Intersects(this) |
| | 2 | 614 | | ? FixedEnclosureType.Intersects |
| | 2 | 615 | | : FixedEnclosureType.Disjoint; |
| | | 616 | | } |
| | | 617 | | |
| | | 618 | | /// <summary> |
| | | 619 | | /// Checks whether a bounding box intersects this sphere, including boundary-only contact. |
| | | 620 | | /// </summary> |
| | | 621 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 6 | 622 | | public bool Intersects(FixedBoundBox box) => Contains(box) != FixedEnclosureType.Disjoint; |
| | | 623 | | |
| | | 624 | | /// <summary> |
| | | 625 | | /// Checks whether another sphere intersects this sphere, including boundary-only contact. |
| | | 626 | | /// </summary> |
| | | 627 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 6 | 628 | | public bool Intersects(FixedBoundSphere sphere) => Contains(sphere) != FixedEnclosureType.Disjoint; |
| | | 629 | | |
| | | 630 | | /// <summary> |
| | | 631 | | /// Checks whether a bounding box overlaps this sphere with positive volume. |
| | | 632 | | /// </summary> |
| | | 633 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 3 | 634 | | public bool IntersectsStrict(FixedBoundBox box) => box.IntersectsStrict(this); |
| | | 635 | | |
| | | 636 | | /// <summary> |
| | | 637 | | /// Checks whether another sphere overlaps this sphere with positive volume. |
| | | 638 | | /// </summary> |
| | | 639 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 640 | | public bool IntersectsStrict(FixedBoundSphere sphere) |
| | | 641 | | { |
| | 4 | 642 | | return Radius > Fixed64.Zero |
| | 4 | 643 | | && sphere.Radius > Fixed64.Zero |
| | 4 | 644 | | && WideGeometry.CompareDistanceToRadiusSum(Center, sphere.Center, Radius, sphere.Radius) < 0; |
| | | 645 | | } |
| | | 646 | | |
| | | 647 | | /// <summary> |
| | | 648 | | /// Checks whether a frustum intersects this sphere. |
| | | 649 | | /// </summary> |
| | | 650 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 651 | | public bool Intersects(FixedBoundFrustum frustum) |
| | | 652 | | { |
| | 1 | 653 | | return frustum.Intersects(this); |
| | | 654 | | } |
| | | 655 | | |
| | | 656 | | /// <summary> |
| | | 657 | | /// Classifies this sphere relative to a plane. |
| | | 658 | | /// </summary> |
| | | 659 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 1 | 660 | | public FixedPlaneIntersectionType Intersects(FixedPlane plane) => plane.Intersects(this); |
| | | 661 | | |
| | | 662 | | /// <summary> |
| | | 663 | | /// Finds the first forward ray intersection with this sphere. |
| | | 664 | | /// </summary> |
| | | 665 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 1 | 666 | | public Fixed64? Intersects(FixedRay ray) => ray.Intersects(this); |
| | | 667 | | |
| | | 668 | | /// <summary> |
| | | 669 | | /// Projects a point onto the bounding sphere. If the point is outside the sphere, it returns the closest point on t |
| | | 670 | | /// </summary> |
| | | 671 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 672 | | public Vector3d ProjectPoint(Vector3d point) |
| | | 673 | | { |
| | 3 | 674 | | var direction = point - Center; |
| | 4 | 675 | | if (direction.IsZero) return Center; // If the point is the center, return the center itself |
| | | 676 | | |
| | 2 | 677 | | return Center + direction.NormalizeInPlace() * Radius; |
| | | 678 | | } |
| | | 679 | | |
| | | 680 | | /// <summary> |
| | | 681 | | /// Clamps a point to this sphere, returning the point unchanged when it is already inside the sphere. |
| | | 682 | | /// </summary> |
| | | 683 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 684 | | public Vector3d ClampPoint(Vector3d point) |
| | | 685 | | { |
| | 3 | 686 | | if (Contains(point)) |
| | 2 | 687 | | return point; |
| | | 688 | | |
| | 1 | 689 | | return ProjectPoint(point); |
| | | 690 | | } |
| | | 691 | | |
| | | 692 | | /// <summary> |
| | | 693 | | /// Calculates the distance from a point to the surface of the sphere. |
| | | 694 | | /// </summary> |
| | | 695 | | /// <param name="point">The point to calculate the distance from.</param> |
| | | 696 | | /// <returns>The distance from the point to the surface of the sphere.</returns> |
| | | 697 | | public Fixed64 DistanceToSurface(Vector3d point) |
| | | 698 | | { |
| | 4 | 699 | | return Vector3d.Distance(Center, point) - Radius; |
| | | 700 | | } |
| | | 701 | | |
| | | 702 | | /// <summary> |
| | | 703 | | /// Creates a sphere that contains this sphere transformed by the specified matrix. |
| | | 704 | | /// </summary> |
| | | 705 | | public FixedBoundSphere Transform(Fixed4x4 matrix) |
| | | 706 | | { |
| | 1 | 707 | | Vector3d center = Fixed4x4.TransformPoint(matrix, Center); |
| | 1 | 708 | | Fixed64 scale = GetMaxBasisScale(matrix); |
| | | 709 | | |
| | 1 | 710 | | return new FixedBoundSphere(center, Radius * scale); |
| | | 711 | | } |
| | | 712 | | |
| | | 713 | | /// <summary> |
| | | 714 | | /// Deconstructs this sphere into its center and radius. |
| | | 715 | | /// </summary> |
| | | 716 | | public void Deconstruct(out Vector3d center, out Fixed64 radius) |
| | | 717 | | { |
| | 1 | 718 | | center = Center; |
| | 1 | 719 | | radius = Radius; |
| | 1 | 720 | | } |
| | | 721 | | |
| | | 722 | | private FixedEnclosureType ContainsBoxLike(Vector3d min, Vector3d max) |
| | | 723 | | { |
| | 13 | 724 | | bool containsAllCorners = |
| | 13 | 725 | | Contains(new Vector3d(min.X, min.Y, min.Z)) && |
| | 13 | 726 | | Contains(new Vector3d(max.X, min.Y, min.Z)) && |
| | 13 | 727 | | Contains(new Vector3d(min.X, max.Y, min.Z)) && |
| | 13 | 728 | | Contains(new Vector3d(max.X, max.Y, min.Z)) && |
| | 13 | 729 | | Contains(new Vector3d(min.X, min.Y, max.Z)) && |
| | 13 | 730 | | Contains(new Vector3d(max.X, min.Y, max.Z)) && |
| | 13 | 731 | | Contains(new Vector3d(min.X, max.Y, max.Z)) && |
| | 13 | 732 | | Contains(new Vector3d(max.X, max.Y, max.Z)); |
| | | 733 | | |
| | 13 | 734 | | if (containsAllCorners) |
| | 3 | 735 | | return FixedEnclosureType.Contains; |
| | | 736 | | |
| | 10 | 737 | | Vector3d closest = new( |
| | 10 | 738 | | FixedMath.Clamp(Center.X, min.X, max.X), |
| | 10 | 739 | | FixedMath.Clamp(Center.Y, min.Y, max.Y), |
| | 10 | 740 | | FixedMath.Clamp(Center.Z, min.Z, max.Z)); |
| | | 741 | | |
| | 10 | 742 | | return WideGeometry.CompareDistanceToRadiusSum(Center, closest, Radius, Fixed64.Zero) <= 0 |
| | 10 | 743 | | ? FixedEnclosureType.Intersects |
| | 10 | 744 | | : FixedEnclosureType.Disjoint; |
| | | 745 | | } |
| | | 746 | | |
| | | 747 | | private static Fixed64 GetMaxBasisScale(Fixed4x4 matrix) |
| | | 748 | | { |
| | 1 | 749 | | Fixed64 row0 = matrix.M11 * matrix.M11 + matrix.M12 * matrix.M12 + matrix.M13 * matrix.M13; |
| | 1 | 750 | | Fixed64 row1 = matrix.M21 * matrix.M21 + matrix.M22 * matrix.M22 + matrix.M23 * matrix.M23; |
| | 1 | 751 | | Fixed64 row2 = matrix.M31 * matrix.M31 + matrix.M32 * matrix.M32 + matrix.M33 * matrix.M33; |
| | | 752 | | |
| | 1 | 753 | | return FixedMath.Sqrt(FixedMath.Max(row0, FixedMath.Max(row1, row2))); |
| | | 754 | | } |
| | | 755 | | |
| | | 756 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 280 | 757 | | private static Fixed64 NormalizeRadius(Fixed64 radius) => FixedMath.Abs(radius); |
| | | 758 | | |
| | | 759 | | #endregion |
| | | 760 | | |
| | | 761 | | #region Operators |
| | | 762 | | |
| | | 763 | | /// <summary> |
| | | 764 | | /// Determines whether two FixedBoundSphere instances are equal. |
| | | 765 | | /// </summary> |
| | | 766 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 2 | 767 | | public static bool operator ==(FixedBoundSphere left, FixedBoundSphere right) => left.Equals(right); |
| | | 768 | | |
| | | 769 | | /// <summary> |
| | | 770 | | /// Determines whether two FixedBoundSphere instances are not equal. |
| | | 771 | | /// </summary> |
| | | 772 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 1 | 773 | | public static bool operator !=(FixedBoundSphere left, FixedBoundSphere right) => !left.Equals(right); |
| | | 774 | | |
| | | 775 | | #endregion |
| | | 776 | | |
| | | 777 | | #region Equality and HashCode Overrides |
| | | 778 | | |
| | | 779 | | /// <inheritdoc/> |
| | | 780 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 2 | 781 | | public override bool Equals(object? obj) => obj is FixedBoundSphere other && Equals(other); |
| | | 782 | | |
| | | 783 | | /// <inheritdoc/> |
| | | 784 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 11 | 785 | | public bool Equals(FixedBoundSphere other) => Center.Equals(other.Center) && Radius.Equals(other.Radius); |
| | | 786 | | |
| | | 787 | | /// <inheritdoc/> |
| | | 788 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 789 | | public override int GetHashCode() |
| | | 790 | | { |
| | | 791 | | unchecked |
| | | 792 | | { |
| | 2 | 793 | | int hash = 17; |
| | 2 | 794 | | hash = hash * 23 + Center.GetHashCode(); |
| | 2 | 795 | | hash = hash * 23 + Radius.GetHashCode(); |
| | 2 | 796 | | return hash; |
| | | 797 | | } |
| | | 798 | | } |
| | | 799 | | |
| | | 800 | | /// <summary> |
| | | 801 | | /// Returns a string that represents the current FixedBoundSphere. |
| | | 802 | | /// </summary> |
| | 1 | 803 | | public override string ToString() => ToString(null, CultureInfo.InvariantCulture); |
| | | 804 | | |
| | | 805 | | /// <summary> |
| | | 806 | | /// Returns a string that represents the current FixedBoundSphere. |
| | | 807 | | /// </summary> |
| | | 808 | | public string ToString(string? format, IFormatProvider? formatProvider) |
| | | 809 | | { |
| | 2 | 810 | | FixedBoundSphere value = this; |
| | 2 | 811 | | return FixedDiagnosticsFormatter.ToString((Span<char> destination, out int charsWritten) => |
| | 2 | 812 | | value.TryFormat(destination, out charsWritten, format.AsSpan(), formatProvider)); |
| | | 813 | | } |
| | | 814 | | |
| | | 815 | | /// <summary> |
| | | 816 | | /// Formats this sphere into the provided destination buffer. |
| | | 817 | | /// </summary> |
| | | 818 | | public bool TryFormat( |
| | | 819 | | Span<char> destination, |
| | | 820 | | out int charsWritten, |
| | | 821 | | ReadOnlySpan<char> format, |
| | | 822 | | IFormatProvider? provider) |
| | | 823 | | { |
| | 44 | 824 | | int written = 0; |
| | 44 | 825 | | if (!FixedDiagnosticsFormatter.Append("{Center:", destination, ref written) || |
| | 44 | 826 | | !Center.TryFormat(destination[written..], out int centerChars, format, provider)) |
| | | 827 | | { |
| | 27 | 828 | | charsWritten = 0; |
| | 27 | 829 | | return false; |
| | | 830 | | } |
| | | 831 | | |
| | 17 | 832 | | written += centerChars; |
| | 17 | 833 | | if (!FixedDiagnosticsFormatter.Append(" Radius:", destination, ref written) || |
| | 17 | 834 | | !FixedDiagnosticsFormatter.Append(Radius, destination, ref written, format, provider) || |
| | 17 | 835 | | !FixedDiagnosticsFormatter.Append('}', destination, ref written)) |
| | | 836 | | { |
| | 14 | 837 | | charsWritten = 0; |
| | 14 | 838 | | return false; |
| | | 839 | | } |
| | | 840 | | |
| | 3 | 841 | | charsWritten = written; |
| | 3 | 842 | | return true; |
| | | 843 | | } |
| | | 844 | | |
| | | 845 | | #endregion |
| | | 846 | | } |