| | | 1 | | //======================================================================= |
| | | 2 | | // GravitasPhysicsService.cs |
| | | 3 | | //======================================================================= |
| | | 4 | | // MIT License, Copyright (c) 2026–present David Oravsky (mrdav30) |
| | | 5 | | // See LICENSE file in the project root for full license information. |
| | | 6 | | //======================================================================= |
| | | 7 | | |
| | | 8 | | using Gravitas.Colliders; |
| | | 9 | | using Gravitas.CollisionHandling; |
| | | 10 | | using SwiftCollections; |
| | | 11 | | using System.Runtime.CompilerServices; |
| | | 12 | | |
| | | 13 | | namespace Gravitas; |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// Owns physics registration and collision-pair state for one <see cref="GravitasWorldContext"/>. |
| | | 17 | | /// </summary> |
| | | 18 | | public sealed partial class GravitasPhysicsService |
| | | 19 | | { |
| | | 20 | | private const int DefaultColliderSize = 2048; |
| | | 21 | | private const int DefaultBodySize = DefaultColliderSize / 4; |
| | | 22 | | private const int DefaultColliderIdSize = DefaultColliderSize / 8; |
| | 1 | 23 | | private static readonly CollisionPairStableKeyComparer ResponsePairComparer = new(); |
| | 1 | 24 | | private static readonly IslandNodeKeyComparer<DiscreteIslandNode> IslandNodeComparer = new(); |
| | 1 | 25 | | private static readonly DiscreteIslandConstraintComparer IslandConstraintComparer = new(); |
| | | 26 | | |
| | | 27 | | private readonly GravitasWorldContext _context; |
| | | 28 | | |
| | 5083 | 29 | | private SwiftBucket<SolidBody> _dynamicBodies = new(DefaultBodySize); |
| | 5083 | 30 | | private readonly ColliderRegistry<LSCollider> _colliders = new(DefaultColliderSize); |
| | 5083 | 31 | | private SwiftList<LSCollider> _serviceRefreshColliders = new(DefaultColliderIdSize); |
| | 5083 | 32 | | private SwiftStack<CollisionPair> _cachedCollisionPairs = new(); |
| | 5083 | 33 | | private SwiftQueue<CollisionPairLifetimeToken> _activeCollisionPairs = new(); |
| | 5083 | 34 | | private readonly SwiftList<CollisionPairLifetimeToken> _activeCollisionPairSnapshot = new(); |
| | 5083 | 35 | | private readonly SwiftList<CollisionPairLifetimeToken> _pairsPendingDeactivation = new(); |
| | 5083 | 36 | | private readonly SwiftList<CollisionPair> _discreteResponsePairs = new(); |
| | 5083 | 37 | | private readonly SwiftList<DiscreteIslandNode> _discreteIslandNodes = new(); |
| | 5083 | 38 | | private readonly SwiftList<DiscreteIslandConstraint> _discreteIslandConstraints = new(); |
| | 5083 | 39 | | private readonly DynamicCcdCandidateIndex _continuousCollisionCandidates = new(DefaultBodySize); |
| | 5083 | 40 | | private readonly DynamicCcdCandidateIndex _dirtyContinuousCollisionCandidates = |
| | 5083 | 41 | | new(DefaultBodySize, supportsUpdates: true); |
| | 5083 | 42 | | private readonly SwiftList<ColliderLifetimeToken> _continuousCollisionCandidateLifetimes = |
| | 5083 | 43 | | new(DefaultBodySize); |
| | 5083 | 44 | | private readonly SwiftList<int> _continuousCollisionCandidateIds = new(DefaultBodySize); |
| | 5083 | 45 | | private readonly SwiftList<int> _dirtyContinuousCollisionCandidateIds = new(DefaultBodySize); |
| | 5083 | 46 | | private readonly SwiftHashSet<int> _dirtyContinuousCollisionBodyIds = new(DefaultBodySize); |
| | 5083 | 47 | | private readonly SwiftList<SolidBody> _dirtyContinuousCollisionBodies = new(DefaultBodySize); |
| | 5083 | 48 | | private readonly SwiftHashSet<SolidBody> _processedContinuousCollisionBodies = new(DefaultBodySize); |
| | 5083 | 49 | | private readonly SwiftHashSet<SolidBody> _queuedContinuousCollisionHandoffBodies = new(DefaultBodySize); |
| | 5083 | 50 | | private readonly SwiftList<SolidBody> _continuousCollisionHandoffQueue = new(DefaultBodySize); |
| | 5083 | 51 | | private int _continuousCollisionPreparedToken = int.MinValue; |
| | | 52 | | |
| | | 53 | | /// <summary> |
| | | 54 | | /// Initializes a new physics service for the supplied context. |
| | | 55 | | /// </summary> |
| | | 56 | | /// <param name="context">The owning world context.</param> |
| | 5083 | 57 | | public GravitasPhysicsService(GravitasWorldContext context) |
| | | 58 | | { |
| | 5083 | 59 | | SwiftThrowHelper.ThrowIfNull(context, nameof(context)); |
| | 5083 | 60 | | _context = context; |
| | 5083 | 61 | | } |
| | | 62 | | |
| | | 63 | | /// <summary> |
| | | 64 | | /// Gets or sets whether this context should simulate physics. |
| | | 65 | | /// </summary> |
| | | 66 | | public bool SimulatePhysics { get; set; } = true; |
| | | 67 | | |
| | | 68 | | /// <summary> |
| | | 69 | | /// Gets the highest collider ID allocated in this context. |
| | | 70 | | /// </summary> |
| | 310 | 71 | | public int PeakColliderCount => _colliders.PeakCount; |
| | | 72 | | |
| | | 73 | | /// <summary> |
| | | 74 | | /// Gets the number of dynamic bodies currently registered in this context. |
| | | 75 | | /// </summary> |
| | | 76 | | public int BodyCount { get; private set; } |
| | | 77 | | |
| | | 78 | | /// <summary> |
| | | 79 | | /// Gets the number of colliders currently registered in this context. |
| | | 80 | | /// </summary> |
| | 1936 | 81 | | public int ColliderCount => _colliders.Count; |
| | | 82 | | |
| | | 83 | | /// <summary> |
| | | 84 | | /// Gets how many service-owned continuous-collision handoff batches were consumed during the last late step. |
| | | 85 | | /// </summary> |
| | | 86 | | public int LastContinuousCollisionIslandCount { get; private set; } |
| | | 87 | | |
| | | 88 | | /// <summary> |
| | | 89 | | /// Gets how many service-owned continuous-collision handoff iterations were consumed during the last late step. |
| | | 90 | | /// </summary> |
| | | 91 | | public int LastContinuousCollisionIslandIterationCount { get; private set; } |
| | | 92 | | |
| | | 93 | | /// <summary> |
| | | 94 | | /// Gets whether the service-owned continuous-collision handoff queue hit its deterministic iteration cap. |
| | | 95 | | /// </summary> |
| | | 96 | | public bool LastContinuousCollisionIslandLimitReached { get; private set; } |
| | | 97 | | |
| | | 98 | | /// <summary> |
| | | 99 | | /// Runs this context's physics simulation step. |
| | | 100 | | /// </summary> |
| | | 101 | | public void Simulate() |
| | | 102 | | { |
| | 2001 | 103 | | _context.EnterSimulationPhase(); |
| | | 104 | | try |
| | | 105 | | { |
| | 2001 | 106 | | if (!SimulatePhysics) |
| | | 107 | | return; |
| | 2001 | 108 | | } |
| | | 109 | | finally |
| | | 110 | | { |
| | 2001 | 111 | | _context.ExitSimulationPhase(); |
| | 2001 | 112 | | } |
| | 2001 | 113 | | } |
| | | 114 | | |
| | | 115 | | private void PrepareCollisionPartitions() |
| | | 116 | | { |
| | 31366 | 117 | | foreach (SolidBody body in _dynamicBodies) |
| | 13502 | 118 | | body.Collider.Simulate(); |
| | | 119 | | |
| | 18918 | 120 | | for (int i = 0; i < _serviceRefreshColliders.Count; i++) |
| | 7278 | 121 | | _serviceRefreshColliders[i].Simulate(); |
| | 2181 | 122 | | } |
| | | 123 | | |
| | | 124 | | /// <summary> |
| | | 125 | | /// Runs this context's late physics step. |
| | | 126 | | /// </summary> |
| | | 127 | | public void LateSimulate() |
| | | 128 | | { |
| | 3 | 129 | | _context.EnterSimulationPhase(); |
| | | 130 | | try |
| | | 131 | | { |
| | 3 | 132 | | if (!BeginLateSimulateBodies(continuousCollisionFramePrepared: false)) |
| | 1 | 133 | | return; |
| | | 134 | | |
| | 2 | 135 | | ProcessQueuedContinuousCollisionHandoffs(); |
| | 2 | 136 | | CompleteLateSimulatePhysicsStep(); |
| | 2 | 137 | | } |
| | | 138 | | finally |
| | | 139 | | { |
| | 3 | 140 | | _context.ExitSimulationPhase(); |
| | 3 | 141 | | } |
| | 3 | 142 | | } |
| | | 143 | | |
| | | 144 | | internal bool BeginLateSimulateBodies(bool continuousCollisionFramePrepared) |
| | | 145 | | { |
| | 2198 | 146 | | if (!SimulatePhysics) |
| | 1 | 147 | | return false; |
| | | 148 | | |
| | 2197 | 149 | | if (!continuousCollisionFramePrepared) |
| | 17 | 150 | | _context.AdvanceLateSimulateToken(); |
| | | 151 | | |
| | 2197 | 152 | | PrepareContinuousCollisionFrame(); |
| | 2197 | 153 | | BeginContinuousCollisionHandoffFrame(); |
| | | 154 | | |
| | 2197 | 155 | | int peak = _dynamicBodies.PeakCount; |
| | 31480 | 156 | | for (int i = 0; i < peak; i++) |
| | | 157 | | { |
| | 13544 | 158 | | if (_dynamicBodies.TryGetValue(i, out SolidBody body)) |
| | | 159 | | { |
| | 13530 | 160 | | body.LateSimulate(updateSleepState: false, updateColliderState: false); |
| | 13529 | 161 | | _processedContinuousCollisionBodies.Add(body); |
| | | 162 | | } |
| | | 163 | | } |
| | | 164 | | |
| | 2196 | 165 | | return true; |
| | | 166 | | } |
| | | 167 | | |
| | | 168 | | internal void CompleteLateSimulatePhysicsStep() |
| | | 169 | | { |
| | 2181 | 170 | | PrepareCollisionPartitions(); |
| | 2181 | 171 | | RunDiscreteCollisionStep(); |
| | 2181 | 172 | | ProcessActiveCollisionPairs(); |
| | 2179 | 173 | | UpdateSleepStatesAfterPhysicsStep(); |
| | 2179 | 174 | | } |
| | | 175 | | |
| | | 176 | | private void RunDiscreteCollisionStep() |
| | | 177 | | { |
| | 2181 | 178 | | _discreteResponsePairs.FastClear(); |
| | 2181 | 179 | | _context.Collisions.CheckAndDistributeCollisions(); |
| | 2181 | 180 | | SolveDiscreteResponsePairs(); |
| | 2181 | 181 | | _context.Collisions.RetireExpiredRetainedPartitions(); |
| | 2181 | 182 | | } |
| | | 183 | | |
| | | 184 | | private void UpdateSleepStatesAfterPhysicsStep() |
| | | 185 | | { |
| | 2179 | 186 | | int peak = _dynamicBodies.PeakCount; |
| | 31394 | 187 | | for (int i = 0; i < peak; i++) |
| | | 188 | | { |
| | 13518 | 189 | | if (_dynamicBodies.TryGetValue(i, out SolidBody body)) |
| | 13501 | 190 | | body.UpdateSleepStateAfterPhysicsStep(); |
| | | 191 | | } |
| | 2179 | 192 | | } |
| | | 193 | | |
| | | 194 | | /// <summary>Publishes interpolated presentation state for registered 3D bodies.</summary> |
| | | 195 | | public void Visualize() |
| | | 196 | | { |
| | 23 | 197 | | int peak = _dynamicBodies.PeakCount; |
| | 110 | 198 | | for (int i = 0; i < peak; i++) |
| | | 199 | | { |
| | 32 | 200 | | if (_dynamicBodies.TryGetValue(i, out SolidBody body)) |
| | 31 | 201 | | body.OnVisualize(); |
| | | 202 | | } |
| | 23 | 203 | | } |
| | | 204 | | |
| | | 205 | | /// <summary> |
| | | 206 | | /// Clears all context-local physics registration state. |
| | | 207 | | /// </summary> |
| | | 208 | | public void Reset() |
| | | 209 | | { |
| | 34 | 210 | | DiscardContinuousCollisionHandoffQueue(); |
| | 34 | 211 | | _dynamicBodies.Clear(); |
| | 34 | 212 | | _colliders.Clear(); |
| | 34 | 213 | | _serviceRefreshColliders.FastClear(); |
| | 34 | 214 | | _cachedCollisionPairs.FastClear(); |
| | 34 | 215 | | _activeCollisionPairs.FastClear(); |
| | 34 | 216 | | _activeCollisionPairSnapshot.FastClear(); |
| | 34 | 217 | | _pairsPendingDeactivation.FastClear(); |
| | 34 | 218 | | _discreteResponsePairs.FastClear(); |
| | 34 | 219 | | _discreteIslandNodes.FastClear(); |
| | 34 | 220 | | _discreteIslandConstraints.FastClear(); |
| | 34 | 221 | | _continuousCollisionCandidates.Clear(); |
| | 34 | 222 | | _dirtyContinuousCollisionCandidates.Clear(); |
| | 34 | 223 | | _continuousCollisionCandidateLifetimes.Clear(); |
| | 34 | 224 | | _continuousCollisionCandidateIds.FastClear(); |
| | 34 | 225 | | _dirtyContinuousCollisionCandidateIds.FastClear(); |
| | 34 | 226 | | _dirtyContinuousCollisionBodyIds.Clear(); |
| | 34 | 227 | | _dirtyContinuousCollisionBodies.FastClear(); |
| | 34 | 228 | | _processedContinuousCollisionBodies.Clear(); |
| | 34 | 229 | | _continuousCollisionPreparedToken = int.MinValue; |
| | 34 | 230 | | LastContinuousCollisionIslandCount = 0; |
| | 34 | 231 | | LastContinuousCollisionIslandIterationCount = 0; |
| | 34 | 232 | | LastContinuousCollisionIslandLimitReached = false; |
| | | 233 | | |
| | 34 | 234 | | BodyCount = 0; |
| | 34 | 235 | | } |
| | | 236 | | |
| | | 237 | | internal int AssimilateBody(SolidBody body, BodyMotionType motionType) |
| | | 238 | | { |
| | 5082 | 239 | | SwiftThrowHelper.ThrowIfNull(body, nameof(body)); |
| | 5082 | 240 | | SwiftThrowHelper.ThrowIfArgument( |
| | 5082 | 241 | | !ReferenceEquals(body.Context, _context), |
| | 5082 | 242 | | nameof(body), |
| | 5082 | 243 | | "Body must belong to this physics service context."); |
| | | 244 | | |
| | 5082 | 245 | | int dynamicId = -1; |
| | 5082 | 246 | | if (motionType != BodyMotionType.Static) |
| | | 247 | | { |
| | 4523 | 248 | | dynamicId = _dynamicBodies.Add(body); |
| | 9024 | 249 | | while (_continuousCollisionCandidateLifetimes.Count <= dynamicId) |
| | 4501 | 250 | | _continuousCollisionCandidateLifetimes.Add(default); |
| | 4523 | 251 | | BodyCount++; |
| | | 252 | | } |
| | | 253 | | |
| | 5082 | 254 | | return dynamicId; |
| | | 255 | | } |
| | | 256 | | |
| | | 257 | | internal void RefreshBodyMotionTypeRegistration( |
| | | 258 | | SolidBody body, |
| | | 259 | | BodyMotionType previousMotionType) |
| | | 260 | | { |
| | 64 | 261 | | if (previousMotionType == BodyMotionType.Static) |
| | | 262 | | { |
| | 15 | 263 | | int dynamicId = _dynamicBodies.Add(body); |
| | 24 | 264 | | while (_continuousCollisionCandidateLifetimes.Count <= dynamicId) |
| | 9 | 265 | | _continuousCollisionCandidateLifetimes.Add(default); |
| | 15 | 266 | | body.SetDynamicId(dynamicId); |
| | 15 | 267 | | BodyCount++; |
| | 15 | 268 | | return; |
| | | 269 | | } |
| | | 270 | | |
| | 49 | 271 | | if (body.MotionType == BodyMotionType.Static) |
| | | 272 | | { |
| | 14 | 273 | | int previousDynamicId = body.DynamicId; |
| | 14 | 274 | | _dynamicBodies.RemoveAt(previousDynamicId); |
| | 14 | 275 | | _continuousCollisionCandidateLifetimes[previousDynamicId] = default; |
| | 14 | 276 | | ReleaseContinuousCollisionCandidateRefresh(body); |
| | 14 | 277 | | body.SetDynamicId(-1); |
| | 14 | 278 | | BodyCount--; |
| | | 279 | | } |
| | 49 | 280 | | } |
| | | 281 | | |
| | | 282 | | internal int AssimilateCollider(LSCollider collider) |
| | | 283 | | { |
| | 5685 | 284 | | SwiftThrowHelper.ThrowIfNull(collider, nameof(collider)); |
| | 5685 | 285 | | collider.BindContext(_context); |
| | | 286 | | |
| | 5685 | 287 | | int id = _colliders.Register(collider); |
| | 5685 | 288 | | RefreshColliderServiceRefreshRegistration(collider); |
| | 5685 | 289 | | return id; |
| | | 290 | | } |
| | | 291 | | |
| | | 292 | | internal void DessimilateBody(SolidBody body) |
| | | 293 | | { |
| | 91 | 294 | | SwiftThrowHelper.ThrowIfNull(body, nameof(body)); |
| | 91 | 295 | | int dynamicId = body.DynamicId; |
| | 91 | 296 | | if (!_dynamicBodies.TryRemoveAt(dynamicId)) |
| | 18 | 297 | | return; |
| | | 298 | | |
| | 73 | 299 | | _continuousCollisionCandidateLifetimes[dynamicId] = default; |
| | 73 | 300 | | ReleaseContinuousCollisionCandidateRefresh(body); |
| | 73 | 301 | | BodyCount--; |
| | 73 | 302 | | } |
| | | 303 | | |
| | | 304 | | internal void DessimilateCollider(LSCollider collider) |
| | | 305 | | { |
| | 224 | 306 | | SwiftThrowHelper.ThrowIfNull(collider, nameof(collider)); |
| | 224 | 307 | | int id = collider.Id; |
| | | 308 | | |
| | 224 | 309 | | if (!_colliders.TryGetById(id, out LSCollider? registered) || !ReferenceEquals(registered, collider)) |
| | | 310 | | { |
| | 4 | 311 | | GravitasLogger.Channel.Warn($"Object with ID {collider.Id} cannot be dessimilated because it is not assimila |
| | 4 | 312 | | return; |
| | | 313 | | } |
| | | 314 | | |
| | 220 | 315 | | if (collider.Body != null) |
| | 92 | 316 | | _context.Constraints3D.RemoveJointsForBody(collider.Body); |
| | 220 | 317 | | RemovePairsForCollider(collider); |
| | 219 | 318 | | if (collider.IsPartitioned) |
| | 215 | 319 | | _context.Collisions.ClearPartitionedObject(collider, true); |
| | | 320 | | |
| | 219 | 321 | | _context.MixedCollisions.RemovePairsFor3DCollider(collider); |
| | 219 | 322 | | if (collider.IsMixedPartitioned) |
| | 18 | 323 | | _context.MixedCollisions.ClearPartitioned3DCollider(collider, force: true); |
| | | 324 | | |
| | 219 | 325 | | RemoveServiceRefreshCollider(collider); |
| | 219 | 326 | | _colliders.Remove(collider); |
| | 219 | 327 | | } |
| | | 328 | | |
| | | 329 | | internal void RefreshColliderServiceRefreshRegistration(LSCollider collider) |
| | | 330 | | { |
| | 5749 | 331 | | SwiftThrowHelper.ThrowIfNull(collider, nameof(collider)); |
| | | 332 | | |
| | 5749 | 333 | | if (collider.RequiresServiceSideRefresh) |
| | 1175 | 334 | | AddServiceRefreshCollider(collider); |
| | | 335 | | else |
| | 4574 | 336 | | RemoveServiceRefreshCollider(collider); |
| | 4574 | 337 | | } |
| | | 338 | | |
| | | 339 | | /// <summary> |
| | | 340 | | /// Resolves a context-local collider ID. |
| | | 341 | | /// </summary> |
| | | 342 | | /// <param name="id">The context-local collider ID.</param> |
| | | 343 | | /// <param name="collider">The resolved collider, if present.</param> |
| | | 344 | | /// <returns>True when the ID resolves in this context.</returns> |
| | | 345 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 346 | | public bool TryGetColliderById(int id, out LSCollider? collider) |
| | | 347 | | { |
| | 1241703 | 348 | | if (id < 0) |
| | | 349 | | { |
| | 14 | 350 | | collider = null; |
| | 14 | 351 | | return false; |
| | | 352 | | } |
| | | 353 | | |
| | 1241689 | 354 | | return _colliders.TryGetById(id, out collider); |
| | | 355 | | } |
| | | 356 | | |
| | | 357 | | internal bool TryGetColliderByServiceIndex(int serviceIndex, out LSCollider? collider) => |
| | 8 | 358 | | _colliders.TryGetByServiceIndex(serviceIndex, out collider); |
| | | 359 | | |
| | 1401 | 360 | | internal LSCollider GetColliderByServiceIndex(int serviceIndex) => _colliders[serviceIndex]; |
| | | 361 | | |
| | 1629 | 362 | | internal SwiftList<LSCollider> PrepareReplayColliders() => _colliders.PrepareReplayColliders(); |
| | | 363 | | |
| | | 364 | | private void AddServiceRefreshCollider(LSCollider collider) |
| | | 365 | | { |
| | 1175 | 366 | | collider.SetServiceRefreshIndex(_serviceRefreshColliders.Count); |
| | 1175 | 367 | | _serviceRefreshColliders.Add(collider); |
| | 1175 | 368 | | } |
| | | 369 | | |
| | | 370 | | private void RemoveServiceRefreshCollider(LSCollider collider) |
| | | 371 | | { |
| | 4793 | 372 | | int index = collider.ServiceRefreshIndex; |
| | 4793 | 373 | | if (index < 0 || !ReferenceEquals(_serviceRefreshColliders[index], collider)) |
| | | 374 | | { |
| | 4633 | 375 | | collider.ClearServiceRefreshIndex(); |
| | 4633 | 376 | | return; |
| | | 377 | | } |
| | | 378 | | |
| | 160 | 379 | | int lastIndex = _serviceRefreshColliders.Count - 1; |
| | 160 | 380 | | if (index != lastIndex) |
| | | 381 | | { |
| | 6 | 382 | | LSCollider moved = _serviceRefreshColliders[lastIndex]; |
| | 6 | 383 | | _serviceRefreshColliders[index] = moved; |
| | 6 | 384 | | moved.SetServiceRefreshIndex(index); |
| | | 385 | | } |
| | | 386 | | |
| | 160 | 387 | | _serviceRefreshColliders.RemoveAt(lastIndex); |
| | 160 | 388 | | collider.ClearServiceRefreshIndex(); |
| | 160 | 389 | | } |
| | | 390 | | |
| | | 391 | | } |