| | | 1 | | //======================================================================= |
| | | 2 | | // SleepIslands.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 System; |
| | | 9 | | |
| | | 10 | | namespace Gravitas; |
| | | 11 | | |
| | | 12 | | /// <summary> |
| | | 13 | | /// Tracks automatic sleep eligibility for connected body slots after response. |
| | | 14 | | /// </summary> |
| | | 15 | | internal sealed class SleepIslands |
| | | 16 | | { |
| | | 17 | | private const int Ready = -1; |
| | | 18 | | private const int Blocked = -2; |
| | 10191 | 19 | | private int[] _parents = Array.Empty<int>(); |
| | | 20 | | |
| | | 21 | | internal void Reserve(int slotCount) |
| | | 22 | | { |
| | 12281 | 23 | | if (slotCount > _parents.Length) |
| | 11422 | 24 | | Array.Resize(ref _parents, Math.Max(slotCount, _parents.Length * 2)); |
| | 12281 | 25 | | } |
| | | 26 | | |
| | 512 | 27 | | internal void Begin(int slotCount) => _parents.AsSpan(0, slotCount).Fill(Ready); |
| | | 28 | | |
| | | 29 | | internal void Join(int first, int second) |
| | | 30 | | { |
| | 536 | 31 | | if (first < 0 || second < 0) |
| | 4 | 32 | | return; |
| | | 33 | | |
| | 532 | 34 | | first = FindRoot(first); |
| | 532 | 35 | | second = FindRoot(second); |
| | 532 | 36 | | if (first != second) |
| | 530 | 37 | | _parents[Math.Max(first, second)] = Math.Min(first, second); |
| | 532 | 38 | | } |
| | | 39 | | |
| | 522 | 40 | | internal void Block(int slot) => _parents[FindRoot(slot)] = Blocked; |
| | | 41 | | |
| | 1036 | 42 | | internal bool CanSleep(int slot) => _parents[FindRoot(slot)] == Ready; |
| | | 43 | | |
| | | 44 | | private int FindRoot(int slot) |
| | | 45 | | { |
| | 3664 | 46 | | while (_parents[slot] >= 0) |
| | | 47 | | { |
| | 1042 | 48 | | int parent = _parents[slot]; |
| | 1042 | 49 | | if (_parents[parent] >= 0) |
| | 11 | 50 | | _parents[slot] = _parents[parent]; |
| | 1042 | 51 | | slot = parent; |
| | | 52 | | } |
| | | 53 | | |
| | 2622 | 54 | | return slot; |
| | | 55 | | } |
| | | 56 | | } |