< Summary

Information
Class: Lattice.ECS.Core.Frame
Assembly: Lattice
File(s): /home/runner/work/Sideline/Sideline/godot/scripts/lattice/ECS/Core/Frame.cs
Line coverage
82%
Covered lines: 677
Uncovered lines: 147
Coverable lines: 824
Total lines: 2035
Line coverage: 82.1%
Branch coverage
69%
Covered branches: 305
Total branches: 436
Branch coverage: 69.9%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
get_Tick()100%11100%
get_DeltaTime()100%11100%
set_DeltaTime(...)100%11100%
get_EntityCount()100%11100%
get_EntityCapacity()100%11100%
get_PendingDeferredRemovalCount()100%11100%
get_HasPendingStructuralChanges()50%22100%
.ctor(...)100%11100%
CreateSnapshot(...)91.66%121293.93%
CapturePackedSnapshot(...)100%11100%
RestoreFromSnapshot(...)72.72%232288.23%
RestoreFromPackedSnapshot(...)73.68%443884.05%
Clone(...)100%11100%
CloneState()100%11100%
CopyFrom(...)100%210%
CopyStateFrom(...)68.75%171682.35%
CalculateChecksum(...)100%11100%
CreateEntity()83.33%6693.75%
DestroyEntity(...)87.5%88100%
IsValid(...)50%22100%
Add(...)40%171058.33%
Set(...)66.66%151273.91%
Remove(...)75%1616100%
Get(...)66.66%6677.77%
GetPointer(...)66.66%6685.71%
TryGet(...)16.66%21625%
Has(...)100%66100%
HasGlobal()50%22100%
GetGlobal()50%4485.71%
TryGetGlobal(...)100%44100%
GetGlobalEntity()50%4485.71%
TryGetGlobalEntity(...)100%44100%
SetGlobal(...)100%44100%
RemoveGlobal()66.66%6691.66%
GetStorage(...)100%22100%
GetOrCreateStorageForSnapshotRestore(...)100%11100%
GetComponentMaskPointer(...)100%11100%
HasComponentBit(...)100%11100%
MatchesFilter(...)0%210140%
CommitDeferredRemovals()100%1010100%
BeginDeferredStructuralChanges()50%2285.71%
CommitStructuralChanges()75%8884.61%
AbortStructuralChanges()0%620%
BeginSystemAuthoringScope(...)50%2285.71%
EndSystemAuthoringScope()100%11100%
GetComponentBlockIterator()50%2280%
GetComponentBlockIterator(...)0%620%
Query()100%11100%
Query()100%11100%
Query()100%11100%
Query()100%11100%
RegisterOwningGroup()62.5%8891.66%
RegisterOwningGroup()62.5%8892.3%
GetOwningGroup()50%3250%
GetOwningGroup()0%620%
TryGetOwningGroup(...)50%4475%
TryGetOwningGroup(...)50%4477.77%
GetStoragePointer()100%11100%
GetAllocatorPointer()100%11100%
Dispose()100%11100%
GetOrCreateStorage(...)100%22100%
RemoveComponentInternal(...)50%5460%
EnqueuePendingRemoval(...)100%11100%
RemovePendingRemovalAt(...)50%21841.17%
EnsurePendingRemovalCapacity(...)25%14415.38%
SetComponentMask(...)100%11100%
ClearComponentMaskBit(...)100%11100%
ClearComponentMask(...)100%22100%
HasComponentMask(...)100%11100%
InvokeOnAdded(...)100%44100%
NotifyOwningGroups(...)100%88100%
EnsureSingletonComponentType(...)100%22100%
EntityHasOnlyComponent(...)80%101084.61%
RebuildOwningGroups()100%66100%
WritePackedState(...)90.9%222294.28%
ComposeOwningGroupKey(...)100%11100%
InitializeState(...)100%1010100%
PrepareForSnapshotRestore(...)83.33%66100%
ResetInitializedStorages()100%66100%
FinalizeSnapshotRestore()16.66%9657.14%
EnsureCompatibleStateForCopy(...)33.33%19628.57%
ReleaseState(...)85.71%1414100%
ShouldDeferStructuralChanges()100%22100%
ShouldDeferSet(...)16.66%19628.57%
QueueCreateEntity()100%11100%
QueueDestroyEntity(...)75%4480%
QueueAddComponent(...)75%4480%
QueueSetComponent(...)0%2040%
QueueRemoveComponent(...)75%4480%
EnsureStructuralCommandBuffer()100%22100%
ResetStructuralChangeTracking()100%22100%
ReleaseStructuralCommandBuffer()100%22100%
EnsureGlobalReadAllowed(...)100%44100%
EnsureGlobalWriteAllowed(...)100%44100%
EnsureStructuralChangesAllowed(...)100%44100%
ResetSystemAuthoringGuard()100%11100%
ReinitializeOwningGroups()66.66%6680%

File(s)

/home/runner/work/Sideline/Sideline/godot/scripts/lattice/ECS/Core/Frame.cs

#LineLine coverage
 1// Copyright (c) 2026 Sideline Authors. All rights reserved.
 2// Licensed under GPL-3.0.
 3
 4using System;
 5using System.Collections.Generic;
 6using System.ComponentModel;
 7using System.Runtime.CompilerServices;
 8using Lattice.Core;
 9using Lattice.ECS.Framework;
 10using Lattice.Math;
 11
 12namespace Lattice.ECS.Core
 13{
 14    /// <summary>
 15    /// ECS 帧 - 高性能非托管实现(FrameSync 风格)
 16    ///
 17    /// 设计原则:
 18    /// 1. 零 GC 压力 - 所有数据使用非托管内存
 19    /// 2. O(1) 组件访问 - 稀疏集实现
 20    /// 3. 缓存友好 - 密集数组存储
 21    /// 4. 确定性 - 完全可预测的行为
 22    /// </summary>
 23    public unsafe class Frame : IDisposable
 24    {
 25        #region 常量
 26
 27        /// <summary>最大组件类型数</summary>
 28        public const int MaxComponentTypes = 512;
 29
 30        /// <summary>组件位图块数(512位 = 8个ulong)</summary>
 31        private const int ComponentMaskBlockCount = 8;
 32
 33        #endregion
 34
 35        #region 实体管理
 36
 37        /// <summary>实体数组(密集存储)</summary>
 38        private EntityRef* _entities;
 39
 40        /// <summary>实体版本数组</summary>
 41        private ushort* _entityVersions;
 42
 43        /// <summary>实体下一个空闲索引</summary>
 44        private int* _entityNextFree;
 45
 46        /// <summary>实体组件位图(每个实体8个ulong)</summary>
 47        private ulong* _entityComponentMasks;
 48
 49        /// <summary>实体数组容量</summary>
 50        private int _entityCapacity;
 51
 52        /// <summary>实体数量</summary>
 53        private int _entityCount;
 54
 55        /// <summary>空闲实体链表头</summary>
 56        private int _freeListHead;
 57
 58        #endregion
 59
 60        #region 组件存储
 61
 62        /// <summary>组件存储数组(类型ID -> 存储指针)</summary>
 63        private void** _componentStorages;
 64
 65        /// <summary>组件存储是否已初始化</summary>
 66        private bool* _storageInitialized;
 67
 68        /// <summary>延迟删除队列中的实体。</summary>
 69        private EntityRef* _pendingRemovalEntities;
 70
 71        /// <summary>延迟删除队列中的组件类型 ID。</summary>
 72        private ushort* _pendingRemovalTypeIds;
 73
 74        /// <summary>延迟删除队列数量。</summary>
 75        private int _pendingRemovalCount;
 76
 77        /// <summary>延迟删除队列容量。</summary>
 78        private int _pendingRemovalCapacity;
 79
 80        /// <summary>内存分配器</summary>
 81        private Allocator* _allocator;
 82
 83        /// <summary>显式注册的 Owning Group 索引。</summary>
 84        private Dictionary<ulong, object>? _owningGroups;
 85
 86        /// <summary>Owning Group 生命周期维护列表。</summary>
 87        private List<IFrameOwningGroup>? _owningGroupBindings;
 88
 89        /// <summary>结构性修改命令缓冲。</summary>
 90        private CommandBuffer _structuralCommandBuffer;
 91
 92        /// <summary>结构性修改命令缓冲是否已初始化。</summary>
 93        private bool _structuralCommandBufferInitialized;
 94
 95        /// <summary>当前是否正在延迟结构性修改。</summary>
 96        private bool _deferStructuralChanges;
 97
 98        /// <summary>当前是否正在回放结构性修改。</summary>
 99        private bool _isReplayingStructuralChanges;
 100
 101        /// <summary>当前是否处于系统作者契约守卫作用域。</summary>
 102        private bool _hasActiveSystemAuthoringContract;
 103
 104        /// <summary>当前执行系统的作者契约。</summary>
 105        private SystemAuthoringContract _activeSystemAuthoringContract;
 106
 107        /// <summary>当前执行系统名称,仅用于守卫报错。</summary>
 108        private string? _activeSystemName;
 109
 110        #endregion
 111
 112        #region 属性
 113
 114        /// <summary>当前帧号</summary>
 10941115        public int Tick { get; set; }
 116
 117        /// <summary>固定时间步长</summary>
 118        public FP DeltaTime
 119        {
 942120            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 942121            get;
 2429122            set;
 123        }
 124
 125        /// <summary>实体数量</summary>
 5126        public int EntityCount => _entityCount;
 127
 128        /// <summary>实体容量。</summary>
 1006129        internal int EntityCapacity => _entityCapacity;
 130
 131        /// <summary>待提交的延迟删除数量。</summary>
 3132        public int PendingDeferredRemovalCount => _pendingRemovalCount;
 133
 134        /// <summary>
 135        /// 当前是否存在尚未提交的结构性修改。
 136        /// 主要用于运行时 Tick 管线与测试验证,不属于快照状态的一部分。
 137        /// </summary>
 2138        public bool HasPendingStructuralChanges => _structuralCommandBufferInitialized && !_structuralCommandBuffer.IsEm
 139
 140        #endregion
 141
 142        #region 构造函数
 143
 469144        public Frame(int maxEntities = 65536)
 145        {
 469146            InitializeState(maxEntities);
 469147        }
 148
 149        #endregion
 150
 151        #region 快照与复制
 152
 153        /// <summary>
 154        /// 创建帧状态对象图快照。
 155        /// 该接口主要保留给兼容、调试和显式恢复测试,不用于 Session 热路径。
 156        /// </summary>
 157        [Obsolete("请优先改用 CapturePackedSnapshot()。CreateSnapshot() 仅保留给兼容、调试和显式恢复测试。", false)]
 158        [EditorBrowsable(EditorBrowsableState.Never)]
 159        public FrameSnapshot CreateSnapshot(ComponentSerializationMode mode = ComponentSerializationMode.Default)
 160        {
 4161            int metadataCount = _entityCount;
 4162            var entityVersions = new ushort[metadataCount];
 4163            var entityNextFree = new int[metadataCount];
 4164            var entityComponentMasks = new ulong[metadataCount * ComponentMaskBlockCount];
 165
 4166            if (metadataCount > 0)
 167            {
 4168                new ReadOnlySpan<ushort>(_entityVersions, metadataCount).CopyTo(entityVersions);
 4169                new ReadOnlySpan<int>(_entityNextFree, metadataCount).CopyTo(entityNextFree);
 4170                new ReadOnlySpan<ulong>(_entityComponentMasks, entityComponentMasks.Length).CopyTo(entityComponentMasks)
 171            }
 172
 4173            var pendingEntities = new EntityRef[_pendingRemovalCount];
 4174            var pendingTypeIds = new ushort[_pendingRemovalCount];
 8175            for (int i = 0; i < _pendingRemovalCount; i++)
 176            {
 0177                pendingEntities[i] = _pendingRemovalEntities[i];
 0178                pendingTypeIds[i] = _pendingRemovalTypeIds[i];
 179            }
 180
 4181            var snapshots = new ComponentStorageSnapshot[ComponentRegistry.Count];
 4182            int snapshotCount = 0;
 342183            for (int typeId = 1; typeId <= ComponentRegistry.Count; typeId++)
 184            {
 167185                if (!_storageInitialized[typeId] || _componentStorages[typeId] == null)
 186                {
 187                    continue;
 188                }
 189
 7190                ComponentStorageSnapshot? storageSnapshot = ComponentRegistry.GetSnapshotCapturer(typeId)(_componentStor
 7191                if (storageSnapshot == null)
 192                {
 193                    continue;
 194                }
 195
 6196                snapshots[snapshotCount++] = storageSnapshot;
 197            }
 198
 4199            Array.Resize(ref snapshots, snapshotCount);
 200
 4201            return new FrameSnapshot(
 4202                Tick,
 4203                DeltaTime,
 4204                _entityCapacity,
 4205                _entityCount,
 4206                _freeListHead,
 4207                entityVersions,
 4208                entityNextFree,
 4209                entityComponentMasks,
 4210                pendingEntities,
 4211                pendingTypeIds,
 4212                snapshots);
 213        }
 214
 215        /// <summary>
 216        /// 创建紧凑字节帧快照。
 217        /// 主要用于 Session 的 checkpoint 与采样历史。
 218        /// 当前会同时记录 packed snapshot 格式版本和本次实际写出的组件 schema 摘要。
 219        /// </summary>
 220        public PackedFrameSnapshot CapturePackedSnapshot(ComponentSerializationMode mode = ComponentSerializationMode.De
 221        {
 163222            var writer = new FrameStateBufferWriter();
 163223            ComponentSchemaManifest schemaManifest = WritePackedState(writer, mode);
 163224            return writer.ToSnapshot(Tick, _entityCapacity, schemaManifest);
 225        }
 226
 227        #endregion
 228
 229        /// <summary>
 230        /// 从对象图快照恢复帧状态。
 231        /// 该接口主要保留给兼容 API 与测试使用。
 232        /// </summary>
 233        [Obsolete("请优先改用 RestoreFromPackedSnapshot()。RestoreFromSnapshot() 仅保留给兼容 API 与测试使用。", false)]
 234        [EditorBrowsable(EditorBrowsableState.Never)]
 235        public void RestoreFromSnapshot(FrameSnapshot snapshot, ComponentSerializationMode mode = ComponentSerialization
 236        {
 3237            if (snapshot == null)
 238            {
 0239                throw new ArgumentNullException(nameof(snapshot));
 240            }
 241
 3242            PrepareForSnapshotRestore(snapshot.EntityCapacity, reuseExistingState: false);
 243
 3244            Tick = snapshot.Tick;
 3245            DeltaTime = snapshot.DeltaTime;
 3246            _entityCount = snapshot.EntityCount;
 3247            _freeListHead = snapshot.FreeListHead;
 3248            int metadataCount = snapshot.EntityVersions.Length;
 249
 3250            if (metadataCount < snapshot.EntityCount ||
 3251                snapshot.EntityNextFree.Length != metadataCount ||
 3252                snapshot.EntityComponentMasks.Length != metadataCount * ComponentMaskBlockCount)
 253            {
 0254                throw new InvalidOperationException("Snapshot entity metadata size does not match frame capacity.");
 255            }
 256
 14257            for (int i = 0; i < metadataCount; i++)
 258            {
 4259                _entityVersions[i] = snapshot.EntityVersions[i];
 4260                _entityNextFree[i] = snapshot.EntityNextFree[i];
 4261                _entities[i] = i < _entityCount ? new EntityRef(i, _entityVersions[i]) : EntityRef.None;
 262            }
 263
 46264            for (int i = metadataCount; i < _entityCapacity; i++)
 265            {
 20266                _entityVersions[i] = 1;
 20267                _entityNextFree[i] = -1;
 20268                _entities[i] = EntityRef.None;
 269            }
 270
 70271            for (int i = 0; i < snapshot.EntityComponentMasks.Length; i++)
 272            {
 32273                _entityComponentMasks[i] = snapshot.EntityComponentMasks[i];
 274            }
 275
 326276            for (int i = snapshot.EntityComponentMasks.Length; i < _entityCapacity * ComponentMaskBlockCount; i++)
 277            {
 160278                _entityComponentMasks[i] = 0;
 279            }
 280
 14281            for (int i = 0; i < snapshot.ComponentStorages.Length; i++)
 282            {
 4283                ComponentStorageSnapshot storageSnapshot = snapshot.ComponentStorages[i];
 4284                ComponentRegistry.GetSnapshotRestorer(storageSnapshot.TypeId)(this, storageSnapshot, mode);
 285            }
 286
 3287            EnsurePendingRemovalCapacity(snapshot.PendingRemovalEntities.Length);
 3288            _pendingRemovalCount = snapshot.PendingRemovalEntities.Length;
 6289            for (int i = 0; i < _pendingRemovalCount; i++)
 290            {
 0291                _pendingRemovalEntities[i] = snapshot.PendingRemovalEntities[i];
 0292                _pendingRemovalTypeIds[i] = snapshot.PendingRemovalTypeIds[i];
 293            }
 294
 3295            FinalizeSnapshotRestore();
 3296        }
 297
 298        /// <summary>
 299        /// 从紧凑字节帧快照恢复状态。
 300        /// </summary>
 301        public void RestoreFromPackedSnapshot(PackedFrameSnapshot snapshot, ComponentSerializationMode mode = ComponentS
 302        {
 76303            if (snapshot == null)
 304            {
 0305                throw new ArgumentNullException(nameof(snapshot));
 306            }
 307
 76308            if (snapshot.FormatVersion != PackedFrameSnapshot.CurrentFormatVersion)
 309            {
 0310                throw new InvalidOperationException(
 0311                    $"Packed snapshot format version {snapshot.FormatVersion} is not compatible with current runtime for
 312            }
 313
 76314            if (snapshot.SchemaManifest.IsSpecified && snapshot.SchemaManifest.SerializationMode != mode)
 315            {
 0316                throw new InvalidOperationException(
 0317                    $"Packed snapshot was captured with serialization mode {snapshot.SchemaManifest.SerializationMode}, 
 318            }
 319
 76320            var reader = new FrameStateReader(snapshot.Data, snapshot.Length);
 321
 76322            int tick = reader.ReadInt32();
 76323            long deltaTimeRaw = reader.ReadInt64();
 76324            int entityCapacity = reader.ReadInt32();
 76325            int entityCount = reader.ReadInt32();
 76326            int freeListHead = reader.ReadInt32();
 327
 76328            PrepareForSnapshotRestore(entityCapacity, reuseExistingState: true);
 329
 76330            Tick = tick;
 76331            DeltaTime = FP.FromRaw(deltaTimeRaw);
 76332            _entityCount = entityCount;
 76333            _freeListHead = freeListHead;
 334
 76335            int metadataCount = reader.ReadInt32();
 76336            if (metadataCount < entityCount)
 337            {
 0338                throw new InvalidOperationException("Packed snapshot entity metadata size does not match frame capacity.
 339            }
 340
 596341            for (int i = 0; i < metadataCount; i++)
 342            {
 222343                _entityVersions[i] = reader.ReadUInt16();
 344            }
 345
 5767876346            for (int i = metadataCount; i < _entityCapacity; i++)
 347            {
 2883862348                _entityVersions[i] = 1;
 349            }
 350
 76351            int nextFreeCount = reader.ReadInt32();
 76352            if (nextFreeCount != metadataCount)
 353            {
 0354                throw new InvalidOperationException("Packed snapshot next-free metadata size does not match entity metad
 355            }
 356
 596357            for (int i = 0; i < metadataCount; i++)
 358            {
 222359                _entityNextFree[i] = reader.ReadInt32();
 222360                _entities[i] = i < _entityCount ? new EntityRef(i, _entityVersions[i]) : EntityRef.None;
 361            }
 362
 5767876363            for (int i = metadataCount; i < _entityCapacity; i++)
 364            {
 2883862365                _entityNextFree[i] = -1;
 2883862366                _entities[i] = EntityRef.None;
 367            }
 368
 76369            int maskCount = reader.ReadInt32();
 76370            if (maskCount != metadataCount * ComponentMaskBlockCount)
 371            {
 0372                throw new InvalidOperationException("Packed snapshot component mask size does not match entity metadata.
 373            }
 374
 76375            ReadOnlySpan<byte> maskBytes = reader.ReadBytes(maskCount * sizeof(ulong));
 76376            fixed (byte* maskPtr = maskBytes)
 377            {
 76378                Buffer.MemoryCopy(maskPtr, _entityComponentMasks, sizeof(ulong) * _entityCapacity * ComponentMaskBlockCo
 379            }
 380
 46141944381            for (int i = maskCount; i < _entityCapacity * ComponentMaskBlockCount; i++)
 382            {
 23070896383                _entityComponentMasks[i] = 0;
 384            }
 385
 76386            int pendingEntityCount = reader.ReadInt32();
 76387            EnsurePendingRemovalCapacity(pendingEntityCount);
 76388            _pendingRemovalCount = pendingEntityCount;
 152389            for (int i = 0; i < pendingEntityCount; i++)
 390            {
 0391                _pendingRemovalEntities[i] = EntityRef.FromRaw(reader.ReadUInt64());
 392            }
 393
 76394            int pendingTypeCount = reader.ReadInt32();
 76395            if (pendingTypeCount != pendingEntityCount)
 396            {
 0397                throw new InvalidOperationException("Packed snapshot pending removal metadata size does not match.");
 398            }
 399
 152400            for (int i = 0; i < pendingTypeCount; i++)
 401            {
 0402                _pendingRemovalTypeIds[i] = reader.ReadUInt16();
 403            }
 404
 76405            int storageCount = reader.ReadInt32();
 76406            ResetInitializedStorages();
 76407            Span<int> serializedTypeIds = stackalloc int[MaxComponentTypes];
 408
 630409            for (int i = 0; i < storageCount; i++)
 410            {
 239411                int typeId = reader.ReadInt32();
 239412                serializedTypeIds[i] = typeId;
 239413                ComponentRegistry.GetPackedStateRestorer(typeId)(this, reader, mode);
 239414                _storageInitialized[typeId] = true;
 415            }
 416
 76417            if (snapshot.SchemaManifest.IsSpecified)
 418            {
 76419                ComponentSchemaManifest currentSchema = ComponentRegistry.CreateSchemaManifest(serializedTypeIds[..stora
 76420                if (!currentSchema.Equals(snapshot.SchemaManifest))
 421                {
 1422                    throw new InvalidOperationException(
 1423                        $"Packed snapshot component schema fingerprint does not match the current registry for mode {mod
 1424                        $"Snapshot={snapshot.SchemaManifest.Fingerprint}, Current={currentSchema.Fingerprint}.");
 425                }
 426            }
 427
 75428            FinalizeSnapshotRestore();
 75429        }
 430
 431        /// <summary>
 432        /// 克隆当前帧。
 433        /// </summary>
 434        public Frame Clone(ComponentSerializationMode mode = ComponentSerializationMode.Default)
 435        {
 30436            var clone = new Frame(_entityCapacity);
 30437            clone.RestoreFromPackedSnapshot(CapturePackedSnapshot(mode), mode);
 30438            return clone;
 439        }
 440
 441        /// <summary>
 442        /// 克隆当前帧的完整运行时状态。
 443        /// 该路径保留所有组件状态,供预测推进、回滚和历史补帧复用。
 444        /// </summary>
 445        public Frame CloneState()
 446        {
 97447            var clone = new Frame(_entityCapacity);
 97448            clone.CopyStateFrom(this);
 97449            return clone;
 450        }
 451
 452        /// <summary>
 453        /// 从另一个帧复制状态到当前帧。
 454        /// </summary>
 455        public void CopyFrom(Frame source, ComponentSerializationMode mode = ComponentSerializationMode.Default)
 456        {
 0457            ArgumentNullException.ThrowIfNull(source);
 0458            RestoreFromPackedSnapshot(source.CapturePackedSnapshot(mode), mode);
 0459        }
 460
 461        /// <summary>
 462        /// 从另一个帧直接复制完整运行时状态,避免热路径走托管快照分配。
 463        /// </summary>
 464        public void CopyStateFrom(Frame source)
 465        {
 691466            ArgumentNullException.ThrowIfNull(source);
 467
 691468            if (ReferenceEquals(this, source))
 469            {
 0470                return;
 471            }
 472
 691473            bool preserveOwningGroups = _owningGroupBindings != null && _owningGroupBindings.Count > 0;
 691474            EnsureCompatibleStateForCopy(source._entityCapacity, preserveOwningGroups);
 691475            ResetStructuralChangeTracking();
 476
 691477            Tick = source.Tick;
 691478            DeltaTime = source.DeltaTime;
 691479            _entityCount = source._entityCount;
 691480            _freeListHead = source._freeListHead;
 481
 691482            int entityBytes = sizeof(EntityRef) * source._entityCapacity;
 691483            int versionBytes = sizeof(ushort) * source._entityCapacity;
 691484            int nextFreeBytes = sizeof(int) * source._entityCapacity;
 691485            int maskBytes = sizeof(ulong) * source._entityCapacity * ComponentMaskBlockCount;
 486
 691487            Buffer.MemoryCopy(source._entities, _entities, entityBytes, entityBytes);
 691488            Buffer.MemoryCopy(source._entityVersions, _entityVersions, versionBytes, versionBytes);
 691489            Buffer.MemoryCopy(source._entityNextFree, _entityNextFree, nextFreeBytes, nextFreeBytes);
 691490            Buffer.MemoryCopy(source._entityComponentMasks, _entityComponentMasks, maskBytes, maskBytes);
 491
 691492            EnsurePendingRemovalCapacity(source._pendingRemovalCount);
 691493            _pendingRemovalCount = source._pendingRemovalCount;
 691494            if (_pendingRemovalCount > 0)
 495            {
 0496                int pendingEntityBytes = sizeof(EntityRef) * _pendingRemovalCount;
 0497                int pendingTypeBytes = sizeof(ushort) * _pendingRemovalCount;
 0498                Buffer.MemoryCopy(source._pendingRemovalEntities, _pendingRemovalEntities, pendingEntityBytes, pendingEn
 0499                Buffer.MemoryCopy(source._pendingRemovalTypeIds, _pendingRemovalTypeIds, pendingTypeBytes, pendingTypeBy
 500            }
 501
 67368502            for (int typeId = 1; typeId <= ComponentRegistry.Count; typeId++)
 503            {
 32993504                if (source._storageInitialized[typeId] && source._componentStorages[typeId] != null)
 505                {
 2113506                    ComponentRegistry.GetStorageCopier(typeId)(this, source._componentStorages[typeId]);
 2113507                    _storageInitialized[typeId] = true;
 2113508                    continue;
 509                }
 510
 30880511                if (_storageInitialized[typeId] && _componentStorages[typeId] != null)
 512                {
 0513                    ComponentRegistry.GetStorageResetter(typeId)(_componentStorages[typeId]);
 514                }
 515            }
 516
 691517            RebuildOwningGroups();
 691518        }
 519
 520        /// <summary>
 521        /// 计算帧校验和。
 522        /// </summary>
 523        public ulong CalculateChecksum(ComponentSerializationMode mode = ComponentSerializationMode.Checkpoint)
 524        {
 82525            var writer = new FrameStateChecksumWriter();
 82526            WritePackedState(writer, mode);
 82527            return writer.Checksum;
 528        }
 529
 530        #region 实体操作
 531
 532        /// <summary>
 533        /// 创建实体 - O(1)。
 534        /// 若当前帧正处于运行时的结构性修改延迟阶段,则返回临时实体引用,并在后续提交阶段真正物化。
 535        /// </summary>
 536        public EntityRef CreateEntity()
 537        {
 590538            EnsureStructuralChangesAllowed(nameof(CreateEntity));
 539
 589540            if (ShouldDeferStructuralChanges())
 541            {
 202542                return QueueCreateEntity();
 543            }
 544
 545            int index;
 546            ushort version;
 547
 387548            if (_freeListHead >= 0)
 549            {
 550                // 复用空闲槽位
 150551                index = _freeListHead;
 150552                _freeListHead = _entityNextFree[index];
 150553                version = _entityVersions[index];
 554            }
 555            else
 556            {
 557                // 分配新槽位
 237558                if (_entityCount >= _entityCapacity)
 0559                    throw new InvalidOperationException("Entity limit reached");
 560
 237561                index = _entityCount++;
 237562                version = 1;
 237563                _entityVersions[index] = version;
 564            }
 565
 566            // 清空组件位图
 387567            ClearComponentMask(index);
 568
 387569            var entity = new EntityRef(index, version);
 387570            _entities[index] = entity;
 387571            return entity;
 572        }
 573
 574        /// <summary>
 575        /// 销毁实体 - O(C),C为组件数
 576        /// </summary>
 577        public void DestroyEntity(EntityRef entity)
 578        {
 339579            EnsureStructuralChangesAllowed(nameof(DestroyEntity));
 580
 339581            if (ShouldDeferStructuralChanges())
 582            {
 166583                QueueDestroyEntity(entity);
 166584                return;
 585            }
 586
 173587            if (!IsValid(entity)) return;
 588
 589            // 删除所有组件
 173590            ulong* mask = GetComponentMaskPointer(entity.Index);
 177498591            for (int typeId = 0; typeId < MaxComponentTypes; typeId++)
 592            {
 88576593                int block = typeId >> 6;
 88576594                int bit = typeId & 0x3F;
 88576595                if ((mask[block] & (1UL << bit)) != 0)
 596                {
 797597                    RemoveComponentInternal(entity, typeId);
 598                }
 599            }
 600
 601            // 版本递增(使旧引用失效)
 173602            _entityVersions[entity.Index]++;
 603
 604            // 加入空闲链表
 173605            _entityNextFree[entity.Index] = _freeListHead;
 173606            _freeListHead = entity.Index;
 173607        }
 608
 609        /// <summary>
 610        /// 检查实体是否有效 - O(1)
 611        /// </summary>
 612        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 613        public bool IsValid(EntityRef entity)
 614        {
 2840615            uint index = (uint)entity.Index;
 2840616            return index < (uint)_entityCount &&
 2840617                   _entityVersions[index] == entity.Version;
 618        }
 619
 620        #endregion
 621
 622        #region 组件操作
 623
 624        /// <summary>
 625        /// 添加组件 - O(1) 均摊。
 626        /// 若当前帧正处于运行时的结构性修改延迟阶段,则该操作会先排入结构提交缓冲,而不是立即影响查询拓扑。
 627        /// </summary>
 628        public void Add<T>(EntityRef entity, in T component) where T : unmanaged, IComponent
 629        {
 2234630            EnsureStructuralChangesAllowed(nameof(Add));
 631
 2234632            if (ShouldDeferStructuralChanges())
 633            {
 950634                QueueAddComponent(entity, component);
 950635                return;
 636            }
 637
 1284638            if (!IsValid(entity))
 0639                throw new ArgumentException($"Invalid entity: {entity}");
 640
 1284641            int typeId = ComponentTypeId<T>.Id;
 1284642            var storage = GetOrCreateStorage<T>(typeId);
 1284643            bool hasComponentMask = HasComponentMask(entity.Index, typeId);
 644
 1284645            if (storage->Has(entity))
 646            {
 0647                if (storage->IsDeferredRemoval && !hasComponentMask)
 648                {
 0649                    int pendingQueueIndex = storage->GetPendingQueueIndex(entity);
 0650                    storage->CancelPendingRemoval(entity);
 0651                    RemovePendingRemovalAt(pendingQueueIndex);
 0652                    storage->Get(entity) = component;
 0653                    SetComponentMask(entity.Index, typeId);
 0654                    InvokeOnAdded(entity, storage);
 0655                    return;
 656                }
 657
 0658                throw new InvalidOperationException($"Component {typeof(T).Name} already exists on entity {entity}");
 659            }
 660
 1284661            storage->Add(entity, component);
 1284662            SetComponentMask(entity.Index, typeId);
 1284663            InvokeOnAdded(entity, storage);
 1284664            NotifyOwningGroups(entity, typeId);
 1284665        }
 666
 667        /// <summary>
 668        /// 设置组件值;若组件不存在则添加。
 669        /// 当运行时开启结构性修改延迟时,对已存在组件的字段写入仍会立即生效;
 670        /// 但对缺失组件或临时实体的写入会延迟到结构提交阶段统一生效。
 671        /// </summary>
 672        public void Set<T>(EntityRef entity, in T component) where T : unmanaged, IComponent
 673        {
 105674            if (ShouldDeferSet<T>(entity))
 675            {
 0676                EnsureStructuralChangesAllowed(nameof(Set));
 0677                QueueSetComponent(entity, component);
 0678                return;
 679            }
 680
 105681            if (!IsValid(entity))
 0682                throw new ArgumentException($"Invalid entity: {entity}");
 683
 105684            int typeId = ComponentTypeId<T>.Id;
 105685            var storage = GetOrCreateStorage<T>(typeId);
 686
 105687            if (HasComponentMask(entity.Index, typeId) && storage->Has(entity))
 688            {
 104689                storage->Get(entity) = component;
 104690                NotifyOwningGroups(entity, typeId);
 104691                return;
 692            }
 693
 1694            if (storage->IsDeferredRemoval && storage->Has(entity))
 695            {
 1696                int pendingQueueIndex = storage->GetPendingQueueIndex(entity);
 1697                storage->CancelPendingRemoval(entity);
 1698                RemovePendingRemovalAt(pendingQueueIndex);
 1699                storage->Get(entity) = component;
 1700                SetComponentMask(entity.Index, typeId);
 1701                InvokeOnAdded(entity, storage);
 1702                NotifyOwningGroups(entity, typeId);
 1703                return;
 704            }
 705
 0706            Add(entity, component);
 0707        }
 708
 709        /// <summary>
 710        /// 移除组件 - O(1)。
 711        /// 若当前帧正处于运行时的结构性修改延迟阶段,则移除会延迟到结构提交阶段统一生效。
 712        /// </summary>
 713        public void Remove<T>(EntityRef entity) where T : unmanaged, IComponent
 714        {
 809715            EnsureStructuralChangesAllowed(nameof(Remove));
 716
 809717            if (ShouldDeferStructuralChanges())
 718            {
 1719                QueueRemoveComponent<T>(entity);
 1720                return;
 721            }
 722
 808723            if (!IsValid(entity)) return;
 724
 808725            int typeId = ComponentTypeId<T>.Id;
 808726            if (!HasComponentMask(entity.Index, typeId)) return;
 727
 808728            var storage = GetStorage<T>(typeId);
 808729            if (storage == null || !storage->Has(entity)) return;
 730
 808731            ComponentChangedDelegate? onRemoved = ComponentTypeId<T>.Callbacks.OnRemoved;
 808732            if (onRemoved != null)
 733            {
 1734                T* removedComponent = storage->GetPointer(entity);
 1735                if (removedComponent != null)
 736                {
 1737                    onRemoved(entity, removedComponent, this);
 738                }
 739            }
 740
 808741            if (storage->IsDeferredRemoval)
 742            {
 8743                storage->MarkForRemoval(entity);
 8744                ClearComponentMaskBit(entity.Index, typeId);
 8745                int pendingQueueIndex = EnqueuePendingRemoval(entity, typeId);
 8746                storage->SetPendingQueueIndex(entity, pendingQueueIndex);
 8747                NotifyOwningGroups(entity, typeId);
 8748                return;
 749            }
 750
 800751            storage->Remove(entity);
 800752            ClearComponentMaskBit(entity.Index, typeId);
 800753            NotifyOwningGroups(entity, typeId);
 800754        }
 755
 756        /// <summary>
 757        /// 获取组件引用 - O(1),2次内存访问
 758        /// </summary>
 759        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 760        public ref T Get<T>(EntityRef entity) where T : unmanaged, IComponent
 761        {
 139762            if (!IsValid(entity))
 1763                throw new ArgumentException($"Invalid entity: {entity}");
 764
 138765            int typeId = ComponentTypeId<T>.Id;
 138766            if (!HasComponentMask(entity.Index, typeId))
 0767                throw new InvalidOperationException($"Component {typeof(T).Name} not found");
 768
 138769            var storage = GetStorage<T>(typeId);
 138770            if (storage == null)
 0771                throw new InvalidOperationException($"Component {typeof(T).Name} not found");
 138772            return ref storage->Get(entity);
 773        }
 774
 775        /// <summary>
 776        /// 获取组件指针 - O(1),2次内存访问
 777        /// </summary>
 778        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 779        public T* GetPointer<T>(EntityRef entity) where T : unmanaged, IComponent
 780        {
 15781            if (!IsValid(entity))
 1782                return null;
 783
 14784            int typeId = ComponentTypeId<T>.Id;
 14785            if (!HasComponentMask(entity.Index, typeId))
 0786                return null;
 787
 14788            var storage = GetStorage<T>(typeId);
 14789            return storage != null ? storage->GetPointer(entity) : null;
 790        }
 791
 792        /// <summary>
 793        /// 尝试获取组件 - O(1)
 794        /// </summary>
 795        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 796        public bool TryGet<T>(EntityRef entity, out T component) where T : unmanaged, IComponent
 797        {
 1798            if (!IsValid(entity))
 799            {
 1800                component = default;
 1801                return false;
 802            }
 803
 0804            int typeId = ComponentTypeId<T>.Id;
 0805            if (!HasComponentMask(entity.Index, typeId))
 806            {
 0807                component = default;
 0808                return false;
 809            }
 810
 0811            var storage = GetStorage<T>(typeId);
 0812            if (storage != null)
 0813                return storage->TryGet(entity, out component);
 0814            component = default;
 0815            return false;
 816        }
 817
 818        /// <summary>
 819        /// 检查是否有组件 - O(1)
 820        /// </summary>
 821        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 822        public bool Has<T>(EntityRef entity) where T : unmanaged, IComponent
 823        {
 27824            if (!IsValid(entity)) return false;
 25825            int typeId = ComponentTypeId<T>.Id;
 25826            if (!HasComponentMask(entity.Index, typeId))
 827            {
 4828                return false;
 829            }
 830
 21831            var storage = GetStorage<T>(typeId);
 21832            return storage != null && storage->Has(entity);
 833        }
 834
 835        /// <summary>
 836        /// 检查当前帧是否存在指定的全局 singleton 组件。
 837        /// 该 API 是玩法层正式推荐的全局状态入口,不再要求外部自己约定“特殊实体”。
 838        /// </summary>
 839        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 840        public bool HasGlobal<T>() where T : unmanaged, IComponent
 841        {
 5842            EnsureGlobalReadAllowed(nameof(HasGlobal));
 843
 5844            int typeId = ComponentTypeId<T>.Id;
 5845            EnsureSingletonComponentType<T>(typeId);
 4846            var storage = GetStorage<T>(typeId);
 4847            return storage != null && storage->SingletonEntity != EntityRef.None;
 848        }
 849
 850        /// <summary>
 851        /// 获取全局 singleton 组件引用。
 852        /// </summary>
 853        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 854        public ref T GetGlobal<T>() where T : unmanaged, IComponent
 855        {
 123856            EnsureGlobalWriteAllowed(nameof(GetGlobal));
 857
 123858            int typeId = ComponentTypeId<T>.Id;
 123859            EnsureSingletonComponentType<T>(typeId);
 860
 123861            var storage = GetStorage<T>(typeId);
 123862            if (storage == null || storage->SingletonEntity == EntityRef.None)
 863            {
 0864                throw new InvalidOperationException($"Global component {typeof(T).Name} not found.");
 865            }
 866
 123867            return ref storage->GetSingleton();
 868        }
 869
 870        /// <summary>
 871        /// 尝试获取全局 singleton 组件值。
 872        /// </summary>
 873        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 874        public bool TryGetGlobal<T>(out T component) where T : unmanaged, IComponent
 875        {
 107876            EnsureGlobalReadAllowed(nameof(TryGetGlobal));
 877
 106878            int typeId = ComponentTypeId<T>.Id;
 106879            EnsureSingletonComponentType<T>(typeId);
 880
 105881            var storage = GetStorage<T>(typeId);
 105882            if (storage != null && storage->SingletonEntity != EntityRef.None)
 883            {
 104884                component = storage->GetSingleton();
 104885                return true;
 886            }
 887
 1888            component = default;
 1889            return false;
 890        }
 891
 892        /// <summary>
 893        /// 获取全局 singleton 组件所在实体。
 894        /// </summary>
 895        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 896        public EntityRef GetGlobalEntity<T>() where T : unmanaged, IComponent
 897        {
 2898            EnsureGlobalWriteAllowed(nameof(GetGlobalEntity));
 899
 2900            int typeId = ComponentTypeId<T>.Id;
 2901            EnsureSingletonComponentType<T>(typeId);
 902
 2903            var storage = GetStorage<T>(typeId);
 2904            if (storage == null || storage->SingletonEntity == EntityRef.None)
 905            {
 0906                throw new InvalidOperationException($"Global component {typeof(T).Name} not found.");
 907            }
 908
 2909            return storage->SingletonEntity;
 910        }
 911
 912        /// <summary>
 913        /// 尝试获取全局 singleton 组件所在实体。
 914        /// </summary>
 915        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 916        public bool TryGetGlobalEntity<T>(out EntityRef entity) where T : unmanaged, IComponent
 917        {
 3918            EnsureGlobalWriteAllowed(nameof(TryGetGlobalEntity));
 919
 3920            int typeId = ComponentTypeId<T>.Id;
 3921            EnsureSingletonComponentType<T>(typeId);
 922
 3923            var storage = GetStorage<T>(typeId);
 3924            if (storage != null && storage->SingletonEntity != EntityRef.None)
 925            {
 2926                entity = storage->SingletonEntity;
 2927                return true;
 928            }
 929
 1930            entity = EntityRef.None;
 1931            return false;
 932        }
 933
 934        /// <summary>
 935        /// 设置全局 singleton 组件。
 936        /// 若当前尚未存在对应全局状态,则会自动创建承载它的实体。
 937        /// </summary>
 938        public EntityRef SetGlobal<T>(in T component) where T : unmanaged, IComponent
 939        {
 130940            EnsureGlobalWriteAllowed(nameof(SetGlobal));
 941
 129942            int typeId = ComponentTypeId<T>.Id;
 129943            EnsureSingletonComponentType<T>(typeId);
 944
 128945            var storage = GetStorage<T>(typeId);
 128946            if (storage != null && storage->SingletonEntity != EntityRef.None)
 947            {
 102948                EntityRef entity = storage->SingletonEntity;
 102949                Set(entity, component);
 102950                return entity;
 951            }
 952
 26953            EntityRef created = CreateEntity();
 26954            Add(created, component);
 26955            return created;
 956        }
 957
 958        /// <summary>
 959        /// 移除全局 singleton 组件。
 960        /// 若该组件是实体上唯一的组件,则会一并销毁其承载实体,避免留下空壳全局实体。
 961        /// </summary>
 962        public bool RemoveGlobal<T>() where T : unmanaged, IComponent
 963        {
 3964            EnsureGlobalWriteAllowed(nameof(RemoveGlobal));
 965
 3966            int typeId = ComponentTypeId<T>.Id;
 3967            EnsureSingletonComponentType<T>(typeId);
 968
 2969            var storage = GetStorage<T>(typeId);
 2970            if (storage == null || storage->SingletonEntity == EntityRef.None)
 971            {
 0972                return false;
 973            }
 974
 2975            EntityRef entity = storage->SingletonEntity;
 2976            if (EntityHasOnlyComponent(entity, typeId))
 977            {
 1978                DestroyEntity(entity);
 1979                return true;
 980            }
 981
 1982            Remove<T>(entity);
 1983            return true;
 984        }
 985
 986        #endregion
 987
 988        #region 查询支持
 989
 990        /// <summary>
 991        /// 获取组件存储。
 992        /// 供 Query、兼容层 Filter 以及底层高性能遍历入口使用。
 993        /// </summary>
 994        internal Storage<T>* GetStorage<T>(int typeId) where T : unmanaged, IComponent
 995        {
 4388996            if (!_storageInitialized[typeId]) return null;
 4252997            return (Storage<T>*)_componentStorages[typeId];
 998        }
 999
 1000        internal Storage<T>* GetOrCreateStorageForSnapshotRestore<T>(int typeId) where T : unmanaged, IComponent
 1001        {
 23561002            return GetOrCreateStorage<T>(typeId);
 1003        }
 1004
 1005        /// <summary>
 1006        /// 获取实体组件位图指针
 1007        /// </summary>
 1008        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1009        internal ulong* GetComponentMaskPointer(int entityIndex)
 1010        {
 5621011            return _entityComponentMasks + (entityIndex * ComponentMaskBlockCount);
 1012        }
 1013
 1014        /// <summary>
 1015        /// 检查实体位图上是否仍然持有指定组件。
 1016        /// </summary>
 1017        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1018        internal bool HasComponentBit(int entityIndex, int typeId)
 1019        {
 24541020            int block = typeId >> 6;
 24541021            int bit = typeId & 0x3F;
 24541022            return (_entityComponentMasks[entityIndex * ComponentMaskBlockCount + block] & (1UL << bit)) != 0;
 1023        }
 1024
 1025        /// <summary>
 1026        /// 检查实体是否匹配位图组件过滤器。
 1027        /// 该 API 主要用于动态条件匹配,不替代强类型 Query。
 1028        /// </summary>
 1029        public bool MatchesFilter(EntityRef entity, in ComponentFilter filter)
 1030        {
 01031            if (!IsValid(entity)) return false;
 1032
 01033            ulong* mask = GetComponentMaskPointer(entity.Index);
 1034
 1035            // 检查必须包含的组件
 01036            if (!filter.Required.IsEmpty)
 1037            {
 01038                for (int i = 0; i < ComponentMaskBlockCount; i++)
 1039                {
 01040                    ulong required = filter.Required.GetBlock(i);
 01041                    if ((mask[i] & required) != required)
 01042                        return false;
 1043                }
 1044            }
 1045
 1046            // 检查必须排除的组件
 01047            if (!filter.Excluded.IsEmpty)
 1048            {
 01049                for (int i = 0; i < ComponentMaskBlockCount; i++)
 1050                {
 01051                    ulong excluded = filter.Excluded.GetBlock(i);
 01052                    if ((mask[i] & excluded) != 0)
 01053                        return false;
 1054                }
 1055            }
 1056
 01057            return true;
 1058        }
 1059
 1060        /// <summary>
 1061        /// 提交所有延迟删除。
 1062        /// </summary>
 1063        public void CommitDeferredRemovals()
 1064        {
 6331065            if (ShouldDeferStructuralChanges())
 1066            {
 11067                throw new InvalidOperationException(
 11068                    "Cannot commit deferred removals while structural changes are being deferred. " +
 11069                    "Wait for the runtime structural commit stage to complete.");
 1070            }
 1071
 6321072            if (_pendingRemovalCount == 0)
 1073            {
 6311074                return;
 1075            }
 1076
 41077            for (int i = 0; i < _pendingRemovalCount; i++)
 1078            {
 11079                int typeId = _pendingRemovalTypeIds[i];
 11080                if (!_storageInitialized[typeId] || _componentStorages[typeId] == null)
 1081                {
 1082                    continue;
 1083                }
 1084
 11085                ComponentRegistry.GetDeferredCommitter(typeId)(_componentStorages[typeId], _pendingRemovalEntities[i]);
 1086            }
 1087
 11088            _pendingRemovalCount = 0;
 11089        }
 1090
 1091        /// <summary>
 1092        /// 进入“结构性修改延迟提交”模式。
 1093        /// 在该模式下,实体创建/销毁与组件增删会先进入命令缓冲,直到显式提交时才生效。
 1094        /// </summary>
 1095        internal void BeginDeferredStructuralChanges()
 1096        {
 6261097            if (_deferStructuralChanges)
 1098            {
 01099                throw new InvalidOperationException("Deferred structural changes have already been started for this fram
 1100            }
 1101
 6261102            EnsureStructuralCommandBuffer();
 6261103            _structuralCommandBuffer.Clear();
 6261104            _deferStructuralChanges = true;
 6261105            _isReplayingStructuralChanges = false;
 6261106        }
 1107
 1108        /// <summary>
 1109        /// 提交当前 Tick 累积的结构性修改。
 1110        /// </summary>
 1111        internal void CommitStructuralChanges()
 1112        {
 6261113            if (!_deferStructuralChanges && !_isReplayingStructuralChanges)
 1114            {
 01115                CommitDeferredRemovals();
 01116                return;
 1117            }
 1118
 6261119            _deferStructuralChanges = false;
 1120
 6261121            if (!_structuralCommandBufferInitialized || _structuralCommandBuffer.IsEmpty)
 1122            {
 5101123                CommitDeferredRemovals();
 5101124                return;
 1125            }
 1126
 1161127            _isReplayingStructuralChanges = true;
 1128            try
 1129            {
 1161130                _structuralCommandBuffer.Playback(this);
 1161131            }
 1132            finally
 1133            {
 1161134                _isReplayingStructuralChanges = false;
 1161135            }
 1161136        }
 1137
 1138        /// <summary>
 1139        /// 中止当前 Tick 尚未提交的结构性修改。
 1140        /// 仅供运行时在 Tick 失败或异常路径下回收临时状态。
 1141        /// </summary>
 1142        internal void AbortStructuralChanges()
 1143        {
 01144            if (_structuralCommandBufferInitialized)
 1145            {
 01146                _structuralCommandBuffer.Clear();
 1147            }
 1148
 01149            _deferStructuralChanges = false;
 01150            _isReplayingStructuralChanges = false;
 01151        }
 1152
 1153        /// <summary>
 1154        /// 进入系统作者契约守卫作用域。
 1155        /// 仅供 `SystemScheduler` 在系统 `OnUpdate(...)` 执行前后使用。
 1156        /// </summary>
 1157        internal void BeginSystemAuthoringScope(ISystem system)
 1158        {
 10041159            ArgumentNullException.ThrowIfNull(system);
 1160
 10041161            if (_hasActiveSystemAuthoringContract)
 1162            {
 01163                throw new InvalidOperationException("A system authoring scope is already active for this frame.");
 1164            }
 1165
 10041166            _activeSystemAuthoringContract = system.Contract;
 10041167            _activeSystemName = system.GetType().Name;
 10041168            _hasActiveSystemAuthoringContract = true;
 10041169        }
 1170
 1171        /// <summary>
 1172        /// 退出系统作者契约守卫作用域。
 1173        /// </summary>
 1174        internal void EndSystemAuthoringScope()
 1175        {
 10041176            ResetSystemAuthoringGuard();
 10041177        }
 1178
 1179        #endregion
 1180
 1181        #region Unsafe API (高性能直接访问)
 1182
 1183        /// <summary>
 1184        /// 获取组件块迭代器 - 批量遍历,最大化缓存命中率
 1185        /// </summary>
 1186        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1187        public ComponentBlockIterator<T> GetComponentBlockIterator<T>() where T : unmanaged, IComponent
 1188        {
 21189            int typeId = ComponentTypeId<T>.Id;
 21190            var storage = GetStorage<T>(typeId);
 21191            if (storage == null)
 01192                return default;
 21193            return new ComponentBlockIterator<T>(storage);
 1194        }
 1195
 1196        /// <summary>
 1197        /// 获取组件块迭代器(范围版)
 1198        /// </summary>
 1199        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1200        public ComponentBlockIterator<T> GetComponentBlockIterator<T>(int offset, int count) where T : unmanaged, ICompo
 1201        {
 01202            int typeId = ComponentTypeId<T>.Id;
 01203            var storage = GetStorage<T>(typeId);
 01204            if (storage == null)
 01205                return default;
 01206            return new ComponentBlockIterator<T>(storage, offset, count);
 1207        }
 1208
 1209        /// <summary>
 1210        /// 获取单组件查询。
 1211        /// </summary>
 1212        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1213        public Query<T> Query<T>() where T : unmanaged, IComponent
 1214        {
 11481215            return new Query<T>(this);
 1216        }
 1217
 1218        /// <summary>
 1219        /// 获取双组件查询。
 1220        /// </summary>
 1221        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1222        public Query<T1, T2> Query<T1, T2>()
 1223            where T1 : unmanaged, IComponent
 1224            where T2 : unmanaged, IComponent
 1225        {
 9021226            return new Query<T1, T2>(this);
 1227        }
 1228
 1229        /// <summary>
 1230        /// 获取三组件查询。
 1231        /// </summary>
 1232        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1233        public Query<T1, T2, T3> Query<T1, T2, T3>()
 1234            where T1 : unmanaged, IComponent
 1235            where T2 : unmanaged, IComponent
 1236            where T3 : unmanaged, IComponent
 1237        {
 21238            return new Query<T1, T2, T3>(this);
 1239        }
 1240
 1241        /// <summary>
 1242        /// 获取四组件查询。
 1243        /// 这是当前正式公开的强类型 Query 上限;
 1244        /// 更高维组合应优先考虑拆分系统职责,或结合 `MatchesFilter(...)` 做显式条件匹配。
 1245        /// </summary>
 1246        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1247        public Query<T1, T2, T3, T4> Query<T1, T2, T3, T4>()
 1248            where T1 : unmanaged, IComponent
 1249            where T2 : unmanaged, IComponent
 1250            where T3 : unmanaged, IComponent
 1251            where T4 : unmanaged, IComponent
 1252        {
 31253            return new Query<T1, T2, T3, T4>(this);
 1254        }
 1255
 1256        /// <summary>
 1257        /// 注册并维护双组件 Owning Group。
 1258        /// 仅建议用于极少数稳定热点系统。
 1259        /// </summary>
 1260        public OwningGroup<T1, T2> RegisterOwningGroup<T1, T2>()
 1261            where T1 : unmanaged, IComponent
 1262            where T2 : unmanaged, IComponent
 1263        {
 31264            int typeId1 = ComponentTypeId<T1>.Id;
 31265            int typeId2 = ComponentTypeId<T2>.Id;
 31266            ulong key = ComposeOwningGroupKey(2, typeId1, typeId2, 0);
 1267
 31268            if (_owningGroups != null && _owningGroups.TryGetValue(key, out object? existing))
 1269            {
 01270                return (OwningGroup<T1, T2>)existing;
 1271            }
 1272
 31273            var group = new OwningGroup<T1, T2>(_allocator, _entityCapacity, typeId1, typeId2);
 31274            group.Rebuild(this);
 31275            _owningGroups ??= new Dictionary<ulong, object>();
 31276            _owningGroupBindings ??= new List<IFrameOwningGroup>();
 31277            _owningGroups[key] = group;
 31278            _owningGroupBindings.Add(group);
 31279            return group;
 1280        }
 1281
 1282        /// <summary>
 1283        /// 注册并维护三组件 Owning Group。
 1284        /// </summary>
 1285        public OwningGroup<T1, T2, T3> RegisterOwningGroup<T1, T2, T3>()
 1286            where T1 : unmanaged, IComponent
 1287            where T2 : unmanaged, IComponent
 1288            where T3 : unmanaged, IComponent
 1289        {
 11290            int typeId1 = ComponentTypeId<T1>.Id;
 11291            int typeId2 = ComponentTypeId<T2>.Id;
 11292            int typeId3 = ComponentTypeId<T3>.Id;
 11293            ulong key = ComposeOwningGroupKey(3, typeId1, typeId2, typeId3);
 1294
 11295            if (_owningGroups != null && _owningGroups.TryGetValue(key, out object? existing))
 1296            {
 01297                return (OwningGroup<T1, T2, T3>)existing;
 1298            }
 1299
 11300            var group = new OwningGroup<T1, T2, T3>(_allocator, _entityCapacity, typeId1, typeId2, typeId3);
 11301            group.Rebuild(this);
 11302            _owningGroups ??= new Dictionary<ulong, object>();
 11303            _owningGroupBindings ??= new List<IFrameOwningGroup>();
 11304            _owningGroups[key] = group;
 11305            _owningGroupBindings.Add(group);
 11306            return group;
 1307        }
 1308
 1309        /// <summary>
 1310        /// 获取已注册的双组件 Owning Group。
 1311        /// </summary>
 1312        public OwningGroup<T1, T2> GetOwningGroup<T1, T2>()
 1313            where T1 : unmanaged, IComponent
 1314            where T2 : unmanaged, IComponent
 1315        {
 21316            if (TryGetOwningGroup<T1, T2>(out OwningGroup<T1, T2> group))
 1317            {
 21318                return group;
 1319            }
 1320
 01321            throw new InvalidOperationException(
 01322                $"OwningGroup<{typeof(T1).Name}, {typeof(T2).Name}> 尚未注册,请先调用 RegisterOwningGroup。");
 1323        }
 1324
 1325        /// <summary>
 1326        /// 获取已注册的三组件 Owning Group。
 1327        /// </summary>
 1328        public OwningGroup<T1, T2, T3> GetOwningGroup<T1, T2, T3>()
 1329            where T1 : unmanaged, IComponent
 1330            where T2 : unmanaged, IComponent
 1331            where T3 : unmanaged, IComponent
 1332        {
 01333            if (TryGetOwningGroup<T1, T2, T3>(out OwningGroup<T1, T2, T3> group))
 1334            {
 01335                return group;
 1336            }
 1337
 01338            throw new InvalidOperationException(
 01339                $"OwningGroup<{typeof(T1).Name}, {typeof(T2).Name}, {typeof(T3).Name}> 尚未注册,请先调用 RegisterOwningGroup。");
 1340        }
 1341
 1342        /// <summary>
 1343        /// 尝试获取已注册的双组件 Owning Group。
 1344        /// </summary>
 1345        public bool TryGetOwningGroup<T1, T2>(out OwningGroup<T1, T2> group)
 1346            where T1 : unmanaged, IComponent
 1347            where T2 : unmanaged, IComponent
 1348        {
 21349            int typeId1 = ComponentTypeId<T1>.Id;
 21350            int typeId2 = ComponentTypeId<T2>.Id;
 21351            ulong key = ComposeOwningGroupKey(2, typeId1, typeId2, 0);
 1352
 21353            if (_owningGroups != null && _owningGroups.TryGetValue(key, out object? existing))
 1354            {
 21355                group = (OwningGroup<T1, T2>)existing;
 21356                return true;
 1357            }
 1358
 01359            group = null!;
 01360            return false;
 1361        }
 1362
 1363        /// <summary>
 1364        /// 尝试获取已注册的三组件 Owning Group。
 1365        /// </summary>
 1366        public bool TryGetOwningGroup<T1, T2, T3>(out OwningGroup<T1, T2, T3> group)
 1367            where T1 : unmanaged, IComponent
 1368            where T2 : unmanaged, IComponent
 1369            where T3 : unmanaged, IComponent
 1370        {
 11371            int typeId1 = ComponentTypeId<T1>.Id;
 11372            int typeId2 = ComponentTypeId<T2>.Id;
 11373            int typeId3 = ComponentTypeId<T3>.Id;
 11374            ulong key = ComposeOwningGroupKey(3, typeId1, typeId2, typeId3);
 1375
 11376            if (_owningGroups != null && _owningGroups.TryGetValue(key, out object? existing))
 1377            {
 11378                group = (OwningGroup<T1, T2, T3>)existing;
 11379                return true;
 1380            }
 1381
 01382            group = null!;
 01383            return false;
 1384        }
 1385
 1386        /// <summary>
 1387        /// 获取组件存储的原始指针(高级用法)
 1388        /// </summary>
 1389        internal Storage<T>* GetStoragePointer<T>() where T : unmanaged, IComponent
 1390        {
 29701391            int typeId = ComponentTypeId<T>.Id;
 29701392            return GetStorage<T>(typeId);
 1393        }
 1394
 1395        /// <summary>
 1396        /// 获取帧内部使用的分配器。
 1397        /// </summary>
 1398        internal Allocator* GetAllocatorPointer()
 1399        {
 231400            return _allocator;
 1401        }
 1402
 1403        #endregion
 1404
 1405        #region IDisposable
 1406
 1407        public void Dispose()
 1408        {
 4681409            ReleaseState();
 4681410        }
 1411
 1412        #endregion
 1413
 1414        #region 私有辅助
 1415
 1416        private Storage<T>* GetOrCreateStorage<T>(int typeId) where T : unmanaged, IComponent
 1417        {
 37451418            if (!_storageInitialized[typeId])
 1419            {
 13601420                var storage = (Storage<T>*)_allocator->Alloc(sizeof(Storage<T>));
 13601421                storage->Initialize(_entityCapacity, _allocator, ComponentRegistry.GetStorageFlags(typeId), componentTyp
 13601422                _componentStorages[typeId] = storage;
 13601423                _storageInitialized[typeId] = true;
 13601424                return storage;
 1425            }
 23851426            return (Storage<T>*)_componentStorages[typeId];
 1427        }
 1428
 1429        private void RemoveComponentInternal(EntityRef entity, int typeId)
 1430        {
 7971431            if (!_storageInitialized[typeId] || _componentStorages[typeId] == null)
 1432            {
 01433                ClearComponentMaskBit(entity.Index, typeId);
 01434                return;
 1435            }
 1436
 7971437            ComponentRegistry.GetRemoveInvoker(typeId)(this, entity);
 7971438        }
 1439
 1440        private int EnqueuePendingRemoval(EntityRef entity, int typeId)
 1441        {
 81442            EnsurePendingRemovalCapacity(_pendingRemovalCount + 1);
 81443            _pendingRemovalEntities[_pendingRemovalCount] = entity;
 81444            _pendingRemovalTypeIds[_pendingRemovalCount] = (ushort)typeId;
 81445            return _pendingRemovalCount++;
 1446        }
 1447
 1448        private void RemovePendingRemovalAt(int queueIndex)
 1449        {
 11450            if ((uint)queueIndex >= (uint)_pendingRemovalCount)
 1451            {
 01452                return;
 1453            }
 1454
 11455            int lastIndex = _pendingRemovalCount - 1;
 11456            if (queueIndex != lastIndex)
 1457            {
 01458                EntityRef swappedEntity = _pendingRemovalEntities[lastIndex];
 01459                int swappedTypeId = _pendingRemovalTypeIds[lastIndex];
 1460
 01461                _pendingRemovalEntities[queueIndex] = swappedEntity;
 01462                _pendingRemovalTypeIds[queueIndex] = (ushort)swappedTypeId;
 1463
 01464                if (_storageInitialized[swappedTypeId] && _componentStorages[swappedTypeId] != null)
 1465                {
 01466                    ComponentRegistry.GetPendingQueueIndexSetter(swappedTypeId)(
 01467                        _componentStorages[swappedTypeId],
 01468                        swappedEntity,
 01469                        queueIndex);
 1470                }
 1471            }
 1472
 11473            _pendingRemovalEntities[lastIndex] = EntityRef.None;
 11474            _pendingRemovalTypeIds[lastIndex] = 0;
 11475            _pendingRemovalCount--;
 11476        }
 1477
 1478        private void EnsurePendingRemovalCapacity(int required)
 1479        {
 7781480            if (required <= _pendingRemovalCapacity)
 1481            {
 7781482                return;
 1483            }
 1484
 01485            int newCapacity = _pendingRemovalCapacity * 2;
 01486            while (newCapacity < required)
 1487            {
 01488                newCapacity *= 2;
 1489            }
 1490
 01491            var newEntities = (EntityRef*)_allocator->Alloc(sizeof(EntityRef) * newCapacity);
 01492            var newTypeIds = (ushort*)_allocator->Alloc(sizeof(ushort) * newCapacity);
 1493
 01494            Buffer.MemoryCopy(_pendingRemovalEntities, newEntities, sizeof(EntityRef) * newCapacity, sizeof(EntityRef) *
 01495            Buffer.MemoryCopy(_pendingRemovalTypeIds, newTypeIds, sizeof(ushort) * newCapacity, sizeof(ushort) * _pendin
 1496
 01497            _pendingRemovalEntities = newEntities;
 01498            _pendingRemovalTypeIds = newTypeIds;
 01499            _pendingRemovalCapacity = newCapacity;
 01500        }
 1501
 1502        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1503        private void SetComponentMask(int entityIndex, int typeId)
 1504        {
 12851505            int block = typeId >> 6;
 12851506            int bit = typeId & 0x3F;
 12851507            _entityComponentMasks[entityIndex * ComponentMaskBlockCount + block] |= (1UL << bit);
 12851508        }
 1509
 1510        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1511        private void ClearComponentMaskBit(int entityIndex, int typeId)
 1512        {
 8081513            int block = typeId >> 6;
 8081514            int bit = typeId & 0x3F;
 8081515            _entityComponentMasks[entityIndex * ComponentMaskBlockCount + block] &= ~(1UL << bit);
 8081516        }
 1517
 1518        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1519        private void ClearComponentMask(int entityIndex)
 1520        {
 3871521            ulong* mask = GetComponentMaskPointer(entityIndex);
 69661522            for (int i = 0; i < ComponentMaskBlockCount; i++)
 30961523                mask[i] = 0;
 3871524        }
 1525
 1526        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1527        private bool HasComponentMask(int entityIndex, int typeId)
 1528        {
 23741529            int block = typeId >> 6;
 23741530            int bit = typeId & 0x3F;
 23741531            return (_entityComponentMasks[entityIndex * ComponentMaskBlockCount + block] & (1UL << bit)) != 0;
 1532        }
 1533
 1534        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1535        private void InvokeOnAdded<T>(EntityRef entity, Storage<T>* storage) where T : unmanaged, IComponent
 1536        {
 12851537            ComponentChangedDelegate? onAdded = ComponentTypeId<T>.Callbacks.OnAdded;
 12851538            if (onAdded == null)
 1539            {
 12841540                return;
 1541            }
 1542
 11543            T* addedComponent = storage->GetPointer(entity);
 11544            if (addedComponent != null)
 1545            {
 11546                onAdded(entity, addedComponent, this);
 1547            }
 11548        }
 1549
 1550        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1551        private void NotifyOwningGroups(EntityRef entity, int typeId)
 1552        {
 21971553            if (_owningGroupBindings == null || _owningGroupBindings.Count == 0)
 1554            {
 21851555                return;
 1556            }
 1557
 481558            for (int i = 0; i < _owningGroupBindings.Count; i++)
 1559            {
 121560                IFrameOwningGroup binding = _owningGroupBindings[i];
 121561                if (binding.DependsOn(typeId))
 1562                {
 121563                    binding.SyncEntity(this, entity, typeId);
 1564                }
 1565            }
 121566        }
 1567
 1568        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1569        private static void EnsureSingletonComponentType<T>(int typeId) where T : unmanaged, IComponent
 1570        {
 3711571            if ((ComponentRegistry.GetStorageFlags(typeId) & StorageFlags.Singleton) == 0)
 1572            {
 41573                throw new InvalidOperationException(
 41574                    $"Component {typeof(T).Name} is not registered as a singleton/global component.");
 1575            }
 3671576        }
 1577
 1578        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1579        private bool EntityHasOnlyComponent(EntityRef entity, int typeId)
 1580        {
 21581            if (!IsValid(entity))
 1582            {
 01583                return false;
 1584            }
 1585
 21586            ulong* mask = GetComponentMaskPointer(entity.Index);
 21587            int targetBlock = typeId >> 6;
 21588            ulong targetBit = 1UL << (typeId & 0x3F);
 1589
 201590            for (int block = 0; block < ComponentMaskBlockCount; block++)
 1591            {
 91592                ulong value = mask[block];
 91593                if (block == targetBlock)
 1594                {
 21595                    if (value != targetBit)
 1596                    {
 11597                        return false;
 1598                    }
 1599
 1600                    continue;
 1601                }
 1602
 71603                if (value != 0)
 1604                {
 01605                    return false;
 1606                }
 1607            }
 1608
 11609            return true;
 1610        }
 1611
 1612        private void RebuildOwningGroups()
 1613        {
 7691614            if (_owningGroupBindings == null || _owningGroupBindings.Count == 0)
 1615            {
 7681616                return;
 1617            }
 1618
 41619            for (int i = 0; i < _owningGroupBindings.Count; i++)
 1620            {
 11621                _owningGroupBindings[i].Rebuild(this);
 1622            }
 11623        }
 1624
 1625        private ComponentSchemaManifest WritePackedState(FrameStateWriter writer, ComponentSerializationMode mode)
 1626        {
 2451627            writer.WriteInt32(Tick);
 2451628            writer.WriteInt64(DeltaTime.RawValue);
 2451629            writer.WriteInt32(_entityCapacity);
 2451630            writer.WriteInt32(_entityCount);
 2451631            writer.WriteInt32(_freeListHead);
 1632
 2451633            int metadataCount = _entityCount;
 2451634            writer.WriteInt32(metadataCount);
 31441635            for (int i = 0; i < metadataCount; i++)
 1636            {
 13271637                writer.WriteUInt16(_entityVersions[i]);
 1638            }
 1639
 2451640            writer.WriteInt32(metadataCount);
 31441641            for (int i = 0; i < metadataCount; i++)
 1642            {
 13271643                writer.WriteInt32(_entityNextFree[i]);
 1644            }
 1645
 2451646            int maskCount = metadataCount * ComponentMaskBlockCount;
 2451647            writer.WriteInt32(maskCount);
 2451648            if (maskCount > 0)
 1649            {
 2451650                writer.WriteBytes(_entityComponentMasks, maskCount * sizeof(ulong));
 1651            }
 1652
 2451653            writer.WriteInt32(_pendingRemovalCount);
 4901654            for (int i = 0; i < _pendingRemovalCount; i++)
 1655            {
 01656                writer.WriteUInt64(_pendingRemovalEntities[i].Raw);
 1657            }
 1658
 2451659            writer.WriteInt32(_pendingRemovalCount);
 4901660            for (int i = 0; i < _pendingRemovalCount; i++)
 1661            {
 01662                writer.WriteUInt16(_pendingRemovalTypeIds[i]);
 1663            }
 1664
 2451665            Span<int> serializableTypeIds = stackalloc int[MaxComponentTypes];
 2451666            int storageCount = 0;
 236901667            for (int typeId = 1; typeId <= ComponentRegistry.Count; typeId++)
 1668            {
 116001669                if (!_storageInitialized[typeId] || _componentStorages[typeId] == null)
 1670                {
 1671                    continue;
 1672                }
 1673
 10851674                if (!ComponentRegistry.CanSerializeComponent(typeId, mode))
 1675                {
 1676                    continue;
 1677                }
 1678
 10851679                if (!ComponentRegistry.GetPackedStatePresenceChecker(typeId)(_componentStorages[typeId], mode))
 1680                {
 1681                    continue;
 1682                }
 1683
 10851684                serializableTypeIds[storageCount++] = typeId;
 1685            }
 1686
 2451687            ComponentSchemaManifest schemaManifest = ComponentRegistry.CreateSchemaManifest(serializableTypeIds[..storag
 1688
 2451689            writer.WriteInt32(storageCount);
 26601690            for (int i = 0; i < storageCount; i++)
 1691            {
 10851692                int typeId = serializableTypeIds[i];
 10851693                ComponentRegistry.GetPackedStateWriter(typeId)(_componentStorages[typeId], writer, mode);
 1694            }
 1695
 2451696            return schemaManifest;
 1697        }
 1698
 1699        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1700        private static ulong ComposeOwningGroupKey(int arity, int typeId1, int typeId2, int typeId3)
 1701        {
 71702            return ((ulong)(uint)arity << 48)
 71703                | ((ulong)(uint)typeId1 << 32)
 71704                | ((ulong)(uint)typeId2 << 16)
 71705                | (uint)typeId3;
 1706        }
 1707
 1708        private void InitializeState(int maxEntities, bool preserveOwningGroups = false)
 1709        {
 4721710            _entityCapacity = maxEntities;
 4721711            _entityCount = 0;
 4721712            _freeListHead = -1;
 4721713            Tick = 0;
 4721714            DeltaTime = FP.Zero;
 1715
 4721716            _allocator = Allocator.Create();
 1717
 4721718            _entities = (EntityRef*)_allocator->Alloc(sizeof(EntityRef) * maxEntities);
 4721719            _entityVersions = (ushort*)_allocator->Alloc(sizeof(ushort) * maxEntities);
 4721720            _entityNextFree = (int*)_allocator->Alloc(sizeof(int) * maxEntities);
 4721721            _entityComponentMasks = (ulong*)_allocator->Alloc(sizeof(ulong) * maxEntities * ComponentMaskBlockCount);
 1722
 509899121723            for (int i = 0; i < maxEntities; i++)
 1724            {
 254944841725                _entityVersions[i] = 1;
 254944841726                _entityNextFree[i] = -1;
 1727            }
 1728
 4721729            _componentStorages = (void**)_allocator->Alloc(sizeof(void*) * MaxComponentTypes);
 4721730            _storageInitialized = (bool*)_allocator->Alloc(sizeof(bool) * MaxComponentTypes);
 1731
 4842721732            for (int i = 0; i < MaxComponentTypes; i++)
 1733            {
 2416641734                _componentStorages[i] = null;
 2416641735                _storageInitialized[i] = false;
 1736            }
 1737
 4721738            _pendingRemovalCapacity = 64;
 4721739            _pendingRemovalCount = 0;
 4721740            _pendingRemovalEntities = (EntityRef*)_allocator->Alloc(sizeof(EntityRef) * _pendingRemovalCapacity);
 4721741            _pendingRemovalTypeIds = (ushort*)_allocator->Alloc(sizeof(ushort) * _pendingRemovalCapacity);
 1742
 4721743            if (!preserveOwningGroups || _owningGroups == null || _owningGroupBindings == null)
 1744            {
 4711745                _owningGroups = new Dictionary<ulong, object>();
 4711746                _owningGroupBindings = new List<IFrameOwningGroup>();
 1747            }
 1748
 4721749            _structuralCommandBuffer = default;
 4721750            _structuralCommandBufferInitialized = false;
 4721751            _deferStructuralChanges = false;
 4721752            _isReplayingStructuralChanges = false;
 4721753            ResetSystemAuthoringGuard();
 4721754        }
 1755
 1756        private void PrepareForSnapshotRestore(int entityCapacity, bool reuseExistingState)
 1757        {
 791758            bool preserveOwningGroups = _owningGroupBindings != null && _owningGroupBindings.Count > 0;
 791759            if (reuseExistingState)
 1760            {
 761761                EnsureCompatibleStateForCopy(entityCapacity, preserveOwningGroups);
 761762                return;
 1763            }
 1764
 31765            ReleaseState(preserveOwningGroups);
 31766            InitializeState(entityCapacity, preserveOwningGroups);
 1767
 31768            if (preserveOwningGroups)
 1769            {
 11770                ReinitializeOwningGroups();
 1771            }
 31772        }
 1773
 1774        private void ResetInitializedStorages()
 1775        {
 72481776            for (int typeId = 1; typeId <= ComponentRegistry.Count; typeId++)
 1777            {
 35481778                if (_storageInitialized[typeId] && _componentStorages[typeId] != null)
 1779                {
 621780                    ComponentRegistry.GetStorageResetter(typeId)(_componentStorages[typeId]);
 1781                }
 1782            }
 761783        }
 1784
 1785        private void FinalizeSnapshotRestore()
 1786        {
 781787            ResetStructuralChangeTracking();
 1788
 1561789            for (int i = 0; i < _pendingRemovalCount; i++)
 1790            {
 01791                int typeId = _pendingRemovalTypeIds[i];
 01792                if (_storageInitialized[typeId] && _componentStorages[typeId] != null)
 1793                {
 01794                    ComponentRegistry.GetPendingRemovalMarker(typeId)(_componentStorages[typeId], _pendingRemovalEntitie
 1795                }
 1796            }
 1797
 781798            RebuildOwningGroups();
 781799        }
 1800
 1801        private void EnsureCompatibleStateForCopy(int sourceEntityCapacity, bool preserveOwningGroups)
 1802        {
 7671803            if (_allocator != null && _entityCapacity == sourceEntityCapacity)
 1804            {
 7671805                return;
 1806            }
 1807
 01808            ReleaseState(preserveOwningGroups);
 01809            InitializeState(sourceEntityCapacity, preserveOwningGroups);
 1810
 01811            if (preserveOwningGroups)
 1812            {
 01813                ReinitializeOwningGroups();
 1814            }
 01815        }
 1816
 1817        private void ReleaseState(bool preserveOwningGroups = false)
 1818        {
 4711819            ReleaseStructuralCommandBuffer();
 1820
 4711821            if (!preserveOwningGroups)
 1822            {
 4701823                _owningGroups?.Clear();
 4701824                _owningGroupBindings?.Clear();
 4701825                _owningGroups = null;
 4701826                _owningGroupBindings = null;
 1827            }
 1828
 4711829            if (_storageInitialized != null && _componentStorages != null)
 1830            {
 4832461831                for (int i = 0; i < MaxComponentTypes; i++)
 1832                {
 2411521833                    _componentStorages[i] = null;
 2411521834                    _storageInitialized[i] = false;
 1835                }
 1836            }
 1837
 4711838            if (_allocator != null)
 1839            {
 4711840                Allocator.Destroy(_allocator);
 4711841                _allocator = null;
 1842            }
 1843
 4711844            _entities = null;
 4711845            _entityVersions = null;
 4711846            _entityNextFree = null;
 4711847            _entityComponentMasks = null;
 4711848            _componentStorages = null;
 4711849            _storageInitialized = null;
 4711850            _pendingRemovalEntities = null;
 4711851            _pendingRemovalTypeIds = null;
 4711852            _pendingRemovalCount = 0;
 4711853            _pendingRemovalCapacity = 0;
 4711854            _entityCapacity = 0;
 4711855            _entityCount = 0;
 4711856            _freeListHead = -1;
 4711857            Tick = 0;
 4711858            DeltaTime = FP.Zero;
 4711859        }
 1860
 1861        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1862        private bool ShouldDeferStructuralChanges()
 1863        {
 47091864            return _deferStructuralChanges && !_isReplayingStructuralChanges;
 1865        }
 1866
 1867        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1868        private bool ShouldDeferSet<T>(EntityRef entity) where T : unmanaged, IComponent
 1869        {
 1051870            if (!ShouldDeferStructuralChanges())
 1871            {
 1051872                return false;
 1873            }
 1874
 01875            if (entity.Index < 0)
 1876            {
 01877                return true;
 1878            }
 1879
 01880            if (!IsValid(entity))
 1881            {
 01882                return false;
 1883            }
 1884
 01885            return !Has<T>(entity);
 1886        }
 1887
 1888        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1889        private EntityRef QueueCreateEntity()
 1890        {
 2021891            EnsureStructuralCommandBuffer();
 2021892            return _structuralCommandBuffer.CreateEntity();
 1893        }
 1894
 1895        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1896        private void QueueDestroyEntity(EntityRef entity)
 1897        {
 1661898            if (entity.Index >= 0 && !IsValid(entity))
 1899            {
 01900                return;
 1901            }
 1902
 1661903            EnsureStructuralCommandBuffer();
 1661904            _structuralCommandBuffer.DestroyEntity(entity);
 1661905        }
 1906
 1907        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1908        private void QueueAddComponent<T>(EntityRef entity, in T component) where T : unmanaged, IComponent
 1909        {
 9501910            if (entity.Index >= 0 && !IsValid(entity))
 1911            {
 01912                throw new ArgumentException($"Invalid entity: {entity}");
 1913            }
 1914
 9501915            EnsureStructuralCommandBuffer();
 9501916            _structuralCommandBuffer.AddComponent(entity, component);
 9501917        }
 1918
 1919        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1920        private void QueueSetComponent<T>(EntityRef entity, in T component) where T : unmanaged, IComponent
 1921        {
 01922            if (entity.Index >= 0 && !IsValid(entity))
 1923            {
 01924                throw new ArgumentException($"Invalid entity: {entity}");
 1925            }
 1926
 01927            EnsureStructuralCommandBuffer();
 01928            _structuralCommandBuffer.SetComponent(entity, component);
 01929        }
 1930
 1931        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1932        private void QueueRemoveComponent<T>(EntityRef entity) where T : unmanaged, IComponent
 1933        {
 11934            if (entity.Index >= 0 && !IsValid(entity))
 1935            {
 01936                return;
 1937            }
 1938
 11939            EnsureStructuralCommandBuffer();
 11940            _structuralCommandBuffer.RemoveComponent<T>(entity);
 11941        }
 1942
 1943        private void EnsureStructuralCommandBuffer()
 1944        {
 19451945            if (_structuralCommandBufferInitialized)
 1946            {
 16951947                return;
 1948            }
 1949
 2501950            _structuralCommandBuffer.Initialize(capacity: 1024);
 2501951            _structuralCommandBufferInitialized = true;
 2501952        }
 1953
 1954        private void ResetStructuralChangeTracking()
 1955        {
 7691956            if (_structuralCommandBufferInitialized)
 1957            {
 3601958                _structuralCommandBuffer.Clear();
 1959            }
 1960
 7691961            _deferStructuralChanges = false;
 7691962            _isReplayingStructuralChanges = false;
 7691963            ResetSystemAuthoringGuard();
 7691964        }
 1965
 1966        private void ReleaseStructuralCommandBuffer()
 1967        {
 4711968            if (_structuralCommandBufferInitialized)
 1969            {
 2501970                _structuralCommandBuffer.Dispose();
 2501971                _structuralCommandBufferInitialized = false;
 1972            }
 1973
 4711974            _structuralCommandBuffer = default;
 4711975            _deferStructuralChanges = false;
 4711976            _isReplayingStructuralChanges = false;
 4711977            ResetSystemAuthoringGuard();
 4711978        }
 1979
 1980        private void EnsureGlobalReadAllowed(string apiName)
 1981        {
 1121982            if (!_hasActiveSystemAuthoringContract || _activeSystemAuthoringContract.AllowsGlobalReads)
 1983            {
 1111984                return;
 1985            }
 1986
 11987            throw new InvalidOperationException(
 11988                $"System {_activeSystemName} cannot call {apiName} because its contract does not allow global state acce
 1989        }
 1990
 1991        private void EnsureGlobalWriteAllowed(string apiName)
 1992        {
 2611993            if (!_hasActiveSystemAuthoringContract || _activeSystemAuthoringContract.AllowsGlobalWrites)
 1994            {
 2601995                return;
 1996            }
 1997
 11998            throw new InvalidOperationException(
 11999                $"System {_activeSystemName} cannot call {apiName} because its contract does not allow writable global s
 2000        }
 2001
 2002        private void EnsureStructuralChangesAllowed(string apiName)
 2003        {
 39722004            if (!_hasActiveSystemAuthoringContract || _activeSystemAuthoringContract.AllowsStructuralChanges)
 2005            {
 39712006                return;
 2007            }
 2008
 12009            throw new InvalidOperationException(
 12010                $"System {_activeSystemName} cannot call {apiName} because its contract does not allow structural change
 2011        }
 2012
 2013        private void ResetSystemAuthoringGuard()
 2014        {
 27162015            _hasActiveSystemAuthoringContract = false;
 27162016            _activeSystemAuthoringContract = SystemAuthoringContract.Default;
 27162017            _activeSystemName = null;
 27162018        }
 2019
 2020        private void ReinitializeOwningGroups()
 2021        {
 12022            if (_owningGroupBindings == null || _owningGroupBindings.Count == 0)
 2023            {
 02024                return;
 2025            }
 2026
 42027            for (int i = 0; i < _owningGroupBindings.Count; i++)
 2028            {
 12029                _owningGroupBindings[i].Reinitialize(_allocator, _entityCapacity);
 2030            }
 12031        }
 2032
 2033        #endregion
 2034    }
 2035}

Methods/Properties

get_Tick()
get_DeltaTime()
set_DeltaTime(Lattice.Math.FP)
get_EntityCount()
get_EntityCapacity()
get_PendingDeferredRemovalCount()
get_HasPendingStructuralChanges()
.ctor(System.Int32)
CreateSnapshot(Lattice.ECS.Core.ComponentSerializationMode)
CapturePackedSnapshot(Lattice.ECS.Core.ComponentSerializationMode)
RestoreFromSnapshot(Lattice.ECS.Core.FrameSnapshot,Lattice.ECS.Core.ComponentSerializationMode)
RestoreFromPackedSnapshot(Lattice.ECS.Core.PackedFrameSnapshot,Lattice.ECS.Core.ComponentSerializationMode)
Clone(Lattice.ECS.Core.ComponentSerializationMode)
CloneState()
CopyFrom(Lattice.ECS.Core.Frame,Lattice.ECS.Core.ComponentSerializationMode)
CopyStateFrom(Lattice.ECS.Core.Frame)
CalculateChecksum(Lattice.ECS.Core.ComponentSerializationMode)
CreateEntity()
DestroyEntity(Lattice.Core.EntityRef)
IsValid(Lattice.Core.EntityRef)
Add(Lattice.Core.EntityRef,T&)
Set(Lattice.Core.EntityRef,T&)
Remove(Lattice.Core.EntityRef)
Get(Lattice.Core.EntityRef)
GetPointer(Lattice.Core.EntityRef)
TryGet(Lattice.Core.EntityRef,T&)
Has(Lattice.Core.EntityRef)
HasGlobal()
GetGlobal()
TryGetGlobal(T&)
GetGlobalEntity()
TryGetGlobalEntity(Lattice.Core.EntityRef&)
SetGlobal(T&)
RemoveGlobal()
GetStorage(System.Int32)
GetOrCreateStorageForSnapshotRestore(System.Int32)
GetComponentMaskPointer(System.Int32)
HasComponentBit(System.Int32,System.Int32)
MatchesFilter(Lattice.Core.EntityRef,Lattice.ECS.Core.ComponentFilter&)
CommitDeferredRemovals()
BeginDeferredStructuralChanges()
CommitStructuralChanges()
AbortStructuralChanges()
BeginSystemAuthoringScope(Lattice.ECS.Framework.ISystem)
EndSystemAuthoringScope()
GetComponentBlockIterator()
GetComponentBlockIterator(System.Int32,System.Int32)
Query()
Query()
Query()
Query()
RegisterOwningGroup()
RegisterOwningGroup()
GetOwningGroup()
GetOwningGroup()
TryGetOwningGroup(Lattice.ECS.Core.OwningGroup`2<T1,T2>&)
TryGetOwningGroup(Lattice.ECS.Core.OwningGroup`3<T1,T2,T3>&)
GetStoragePointer()
GetAllocatorPointer()
Dispose()
GetOrCreateStorage(System.Int32)
RemoveComponentInternal(Lattice.Core.EntityRef,System.Int32)
EnqueuePendingRemoval(Lattice.Core.EntityRef,System.Int32)
RemovePendingRemovalAt(System.Int32)
EnsurePendingRemovalCapacity(System.Int32)
SetComponentMask(System.Int32,System.Int32)
ClearComponentMaskBit(System.Int32,System.Int32)
ClearComponentMask(System.Int32)
HasComponentMask(System.Int32,System.Int32)
InvokeOnAdded(Lattice.Core.EntityRef,Lattice.ECS.Core.Storage`1<T>*)
NotifyOwningGroups(Lattice.Core.EntityRef,System.Int32)
EnsureSingletonComponentType(System.Int32)
EntityHasOnlyComponent(Lattice.Core.EntityRef,System.Int32)
RebuildOwningGroups()
WritePackedState(Lattice.ECS.Core.FrameStateWriter,Lattice.ECS.Core.ComponentSerializationMode)
ComposeOwningGroupKey(System.Int32,System.Int32,System.Int32,System.Int32)
InitializeState(System.Int32,System.Boolean)
PrepareForSnapshotRestore(System.Int32,System.Boolean)
ResetInitializedStorages()
FinalizeSnapshotRestore()
EnsureCompatibleStateForCopy(System.Int32,System.Boolean)
ReleaseState(System.Boolean)
ShouldDeferStructuralChanges()
ShouldDeferSet(Lattice.Core.EntityRef)
QueueCreateEntity()
QueueDestroyEntity(Lattice.Core.EntityRef)
QueueAddComponent(Lattice.Core.EntityRef,T&)
QueueSetComponent(Lattice.Core.EntityRef,T&)
QueueRemoveComponent(Lattice.Core.EntityRef)
EnsureStructuralCommandBuffer()
ResetStructuralChangeTracking()
ReleaseStructuralCommandBuffer()
EnsureGlobalReadAllowed(System.String)
EnsureGlobalWriteAllowed(System.String)
EnsureStructuralChangesAllowed(System.String)
ResetSystemAuthoringGuard()
ReinitializeOwningGroups()