| | | 1 | | // Copyright (c) 2026 Sideline Authors. All rights reserved. |
| | | 2 | | // Licensed under GPL-3.0. |
| | | 3 | | |
| | | 4 | | using System; |
| | | 5 | | using System.Numerics; |
| | | 6 | | using System.Runtime.CompilerServices; |
| | | 7 | | using Lattice.Core; |
| | | 8 | | |
| | | 9 | | namespace Lattice.ECS.Core |
| | | 10 | | { |
| | | 11 | | /// <summary> |
| | | 12 | | /// 存储标志 - 定义组件存储的特殊行为 |
| | | 13 | | /// |
| | | 14 | | /// 设计说明: |
| | | 15 | | /// - 使用 ushort 节省内存(2 字节),足够表示 16 种标志 |
| | | 16 | | /// - 单例和延迟删除是预测回滚模型的核心需求 |
| | | 17 | | /// </summary> |
| | | 18 | | [Flags] |
| | | 19 | | public enum StorageFlags : ushort |
| | | 20 | | { |
| | | 21 | | /// <summary>无特殊标志</summary> |
| | | 22 | | None = 0, |
| | | 23 | | |
| | | 24 | | /// <summary> |
| | | 25 | | /// 单例组件(只允许一个实例) |
| | | 26 | | /// |
| | | 27 | | /// 应用场景: |
| | | 28 | | /// - 全局配置(如 GameConfig) |
| | | 29 | | /// - 唯一的游戏状态(如 GameState) |
| | | 30 | | /// - 避免多个实例导致的逻辑错误 |
| | | 31 | | /// </summary> |
| | | 32 | | Singleton = 1 << 0, |
| | | 33 | | |
| | | 34 | | /// <summary> |
| | | 35 | | /// 延迟删除(Remove 时标记,需要 Commit 才真正删除) |
| | | 36 | | /// |
| | | 37 | | /// 设计原因: |
| | | 38 | | /// - 预测回滚需要延迟删除,避免预测期间的状态不一致 |
| | | 39 | | /// - 允许在帧结束时批量处理删除,减少内存抖动 |
| | | 40 | | /// - FrameSync 使用相同的模式(_pendingRemoval) |
| | | 41 | | /// </summary> |
| | | 42 | | DeferredRemoval = 1 << 1, |
| | | 43 | | } |
| | | 44 | | |
| | | 45 | | /// <summary> |
| | | 46 | | /// Block-based 高性能组件存储 - 超越 FrameSync 的内存效率与迭代性能 |
| | | 47 | | /// |
| | | 48 | | /// ============================================================ |
| | | 49 | | /// 架构设计决策 |
| | | 50 | | /// ============================================================ |
| | | 51 | | /// |
| | | 52 | | /// Q: 为什么选择分离存储(SOA)而不是联合存储(AOS)? |
| | | 53 | | /// A: |
| | | 54 | | /// 1. 预测回滚友好:可以单独快照/恢复单个组件类型 |
| | | 55 | | /// 2. Delta 压缩高效:只传输变化的组件 |
| | | 56 | | /// 3. SIMD 友好:连续的同类型数据便于向量化 |
| | | 57 | | /// 4. 缓存局部性:批量访问同类型组件时命中率更高 |
| | | 58 | | /// 5. 与 FrameSync 不同:FrameSync 使用联合存储(ComponentDataBuffer) |
| | | 59 | | /// |
| | | 60 | | /// Q: 为什么 Block 容量固定为 128? |
| | | 61 | | /// A: |
| | | 62 | | /// 1. 与 FrameSync 保持一致,便于对比和迁移 |
| | | 63 | | /// 2. 128 * sizeof(T) 通常能填满多个缓存行(假设 T=16 字节,128*16=2048 字节) |
| | | 64 | | /// 3. 128 是 2 的幂,可以用位运算替代除法/取模(block = index >> 7, offset = index & 127) |
| | | 65 | | /// 4. 足够大的批次用于 SIMD 处理(AVX2 可以一次处理 4 个 Vector4FP) |
| | | 66 | | /// |
| | | 67 | | /// Q: 为什么稀疏数组使用 ushort(2 字节)而不是 int(4 字节)? |
| | | 68 | | /// A: |
| | | 69 | | /// 1. 内存节省 50%:65536 个实体的稀疏数组只需 128KB,而 int 需要 256KB |
| | | 70 | | /// 2. 65535 的最大索引足够大多数游戏使用(支持 64K 个组件实例) |
| | | 71 | | /// 3. 缓存行利用更好:同一代码可以追踪更多实体 |
| | | 72 | | /// 4. 与 FrameSync 相同的选择(ComponentDataBuffer._sparse 也是 ushort*) |
| | | 73 | | /// |
| | | 74 | | /// Q: 为什么需要版本号(_version)? |
| | | 75 | | /// A: |
| | | 76 | | /// 1. 防止迭代中修改:快速检测并发修改,抛出异常而非崩溃 |
| | | 77 | | /// 2. 调试友好:在 DEBUG 模式下提供清晰的错误信息 |
| | | 78 | | /// 3. 与 C# 的 IEnumerator 模式一致(检查集合修改) |
| | | 79 | | /// |
| | | 80 | | /// ============================================================ |
| | | 81 | | /// 性能特性 |
| | | 82 | | /// ============================================================ |
| | | 83 | | /// |
| | | 84 | | /// 1. O(1) 添加/删除/访问:稀疏数组保证常数时间 |
| | | 85 | | /// 2. 缓存友好:Block 内数据连续,预取友好 |
| | | 86 | | /// 3. 内存对齐:16 字节对齐,支持 SIMD |
| | | 87 | | /// 4. 无 GC:完全非托管内存,通过 Allocator 管理 |
| | | 88 | | /// |
| | | 89 | | /// ============================================================ |
| | | 90 | | /// 内存布局 |
| | | 91 | | /// ============================================================ |
| | | 92 | | /// |
| | | 93 | | /// Storage<T> (SOA - Structure of Arrays): |
| | | 94 | | /// |
| | | 95 | | /// Block 0 Block 1 Block 2 |
| | | 96 | | /// ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ |
| | | 97 | | /// │ EntityRef │ │ EntityRef │ │ EntityRef │ ← 实体引用数组 |
| | | 98 | | /// │ [128] │ │ [128] │ │ [128] │ (密集存储) |
| | | 99 | | /// └─────────────┘ └─────────────┘ └─────────────┘ |
| | | 100 | | /// ↓ ↓ ↓ |
| | | 101 | | /// ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ |
| | | 102 | | /// │ T[128] │ │ T[128] │ │ T[128] │ ← 组件数据数组 |
| | | 103 | | /// │ (强类型) │ │ (强类型) │ │ (强类型) │ (密集存储) |
| | | 104 | | /// └─────────────┘ └─────────────┘ └─────────────┘ |
| | | 105 | | /// ↓ ↓ ↓ |
| | | 106 | | /// _sparse[Entity.Index] → GlobalIndex (ushort, 2 字节) |
| | | 107 | | /// |
| | | 108 | | /// 对比 FrameSync (AOS - Array of Structures): |
| | | 109 | | /// |
| | | 110 | | /// Block 内存布局: |
| | | 111 | | /// ┌─────────────────────────────────────────┐ |
| | | 112 | | /// │ EntityRef[0] | Padding | T[0] │ ← 同一 Block 内混合存储 |
| | | 113 | | /// │ EntityRef[1] | Padding | T[1] │ 需要 _blockDataOffset |
| | | 114 | | /// │ ... │ 计算数据偏移 |
| | | 115 | | /// └─────────────────────────────────────────┘ |
| | | 116 | | /// |
| | | 117 | | /// 我们的优势: |
| | | 118 | | /// - 类型安全:T* 而不是 byte* |
| | | 119 | | /// - 更简单的偏移计算:直接 array[index] 而不是 ptr + stride * index |
| | | 120 | | /// - 更好的 SIMD 支持:连续的同类型数据 |
| | | 121 | | /// </summary> |
| | | 122 | | public unsafe struct Storage<T> where T : unmanaged, IComponent |
| | | 123 | | { |
| | | 124 | | #region 常量 |
| | | 125 | | |
| | | 126 | | /// <summary>自动推导 Block 容量。</summary> |
| | | 127 | | public const int DefaultBlockCapacity = 0; |
| | | 128 | | |
| | | 129 | | /// <summary>Block 数据面的目标字节数。</summary> |
| | | 130 | | public const int TargetBlockBytes = 2048; |
| | | 131 | | |
| | | 132 | | /// <summary>Block 列表初始容量</summary> |
| | | 133 | | public const int InitialBlockListCapacity = 4; |
| | | 134 | | |
| | | 135 | | /// <summary>自动推导时允许的最小 Block 容量。</summary> |
| | | 136 | | public const int MinBlockCapacity = 8; |
| | | 137 | | |
| | | 138 | | /// <summary>自动推导时允许的最大 Block 容量。</summary> |
| | | 139 | | public const int MaxBlockCapacity = 512; |
| | | 140 | | |
| | | 141 | | /// <summary>稀疏数组 Tombstone 标记</summary> |
| | | 142 | | public const ushort TOMBSTONE = 0; |
| | | 143 | | |
| | | 144 | | #endregion |
| | | 145 | | |
| | | 146 | | #region Block 结构 |
| | | 147 | | |
| | | 148 | | /// <summary> |
| | | 149 | | /// 数据块 - 包含固定数量的实体引用和组件数据 |
| | | 150 | | /// </summary> |
| | | 151 | | public struct Block |
| | | 152 | | { |
| | | 153 | | /// <summary>实体引用数组(紧密排列)</summary> |
| | | 154 | | public EntityRef* PackedHandles; |
| | | 155 | | |
| | | 156 | | /// <summary>组件数据数组(紧密排列)</summary> |
| | | 157 | | public T* PackedData; |
| | | 158 | | |
| | | 159 | | /// <summary>Block 是否已分配</summary> |
| | 0 | 160 | | public bool IsAllocated => PackedData != null; |
| | | 161 | | } |
| | | 162 | | |
| | | 163 | | #endregion |
| | | 164 | | |
| | | 165 | | #region 字段 |
| | | 166 | | |
| | | 167 | | // Block 管理 |
| | | 168 | | private Block* _blocks; |
| | | 169 | | private int _blockCount; |
| | | 170 | | private int _blockCapacity; |
| | | 171 | | private int _blockItemCapacity; |
| | | 172 | | |
| | | 173 | | // 稀疏数组:Entity.Index → GlobalIndex (1-based, 0 = empty) |
| | | 174 | | private ushort* _sparse; |
| | | 175 | | private int _sparseCapacity; |
| | | 176 | | private byte* _entryStates; |
| | | 177 | | private ushort* _pendingQueueIndices; |
| | | 178 | | |
| | | 179 | | // 状态 |
| | | 180 | | private int _count; |
| | | 181 | | private int _stride; |
| | | 182 | | private int _version; |
| | | 183 | | private int _componentTypeId; |
| | | 184 | | |
| | | 185 | | // 内存分配器 |
| | | 186 | | private Allocator* _allocator; |
| | | 187 | | private bool _ownsAllocator; |
| | | 188 | | |
| | | 189 | | // 标志和特殊功能 |
| | | 190 | | private StorageFlags _flags; |
| | | 191 | | private ushort _singletonSparse; // 单例的全局索引(0 = 无单例) |
| | | 192 | | private int _pendingRemoval; // 待删除计数(延迟删除模式) |
| | | 193 | | |
| | | 194 | | #endregion |
| | | 195 | | |
| | | 196 | | #region 属性 |
| | | 197 | | |
| | | 198 | | /// <summary>当前组件数量(不包括索引0)</summary> |
| | 14873 | 199 | | public int Count => _count - 1; |
| | | 200 | | |
| | | 201 | | /// <summary>是否为空</summary> |
| | 0 | 202 | | public bool IsEmpty => _count <= 1; |
| | | 203 | | |
| | | 204 | | /// <summary>当前版本号(用于迭代检测)</summary> |
| | 3026 | 205 | | public int Version => _version; |
| | | 206 | | |
| | | 207 | | /// <summary>Block 数量</summary> |
| | 104109 | 208 | | public int BlockCount => _blockCount; |
| | | 209 | | |
| | | 210 | | /// <summary>每个 Block 的容量</summary> |
| | 3032 | 211 | | public int BlockItemCapacity => _blockItemCapacity; |
| | | 212 | | |
| | | 213 | | /// <summary>组件类型ID</summary> |
| | 0 | 214 | | public int ComponentTypeId => _componentTypeId; |
| | | 215 | | |
| | | 216 | | /// <summary>存储标志</summary> |
| | 0 | 217 | | public StorageFlags Flags => _flags; |
| | | 218 | | |
| | | 219 | | /// <summary>是否为单例存储</summary> |
| | 45896 | 220 | | public bool IsSingleton => (_flags & StorageFlags.Singleton) != 0; |
| | | 221 | | |
| | | 222 | | /// <summary>是否启用延迟删除</summary> |
| | 12987 | 223 | | public bool IsDeferredRemoval => (_flags & StorageFlags.DeferredRemoval) != 0; |
| | | 224 | | |
| | | 225 | | /// <summary>待删除组件数量(延迟删除模式)</summary> |
| | 0 | 226 | | public int PendingRemovalCount => _pendingRemoval; |
| | | 227 | | |
| | | 228 | | /// <summary>实际使用中的组件数量(减去待删除)</summary> |
| | 5042 | 229 | | public int UsedCount => Count - _pendingRemoval; |
| | | 230 | | |
| | | 231 | | /// <summary>是否为条目状态分配了独立跟踪存储。</summary> |
| | 2 | 232 | | internal bool HasEntryStateTracking => _entryStates != null; |
| | | 233 | | |
| | | 234 | | /// <summary>是否为延迟删除队列索引分配了独立跟踪存储。</summary> |
| | 2 | 235 | | internal bool HasPendingQueueTracking => _pendingQueueIndices != null; |
| | | 236 | | |
| | | 237 | | /// <summary>单例实体引用(仅单例模式有效)</summary> |
| | | 238 | | public EntityRef SingletonEntity |
| | | 239 | | { |
| | | 240 | | get |
| | | 241 | | { |
| | 449 | 242 | | if (!IsSingleton || _singletonSparse == 0) |
| | 4 | 243 | | return EntityRef.None; |
| | 445 | 244 | | return GetEntityRefByGlobalIndex(_singletonSparse); |
| | | 245 | | } |
| | | 246 | | } |
| | | 247 | | |
| | | 248 | | #endregion |
| | | 249 | | |
| | | 250 | | #region 生命周期 |
| | | 251 | | |
| | | 252 | | /// <summary> |
| | | 253 | | /// 初始化存储(使用内部Allocator) |
| | | 254 | | /// </summary> |
| | | 255 | | public void Initialize(int maxEntities, int blockCapacity = DefaultBlockCapacity, int componentTypeId = 0) |
| | | 256 | | { |
| | 8 | 257 | | Initialize(maxEntities, StorageFlags.None, blockCapacity, componentTypeId); |
| | 8 | 258 | | } |
| | | 259 | | |
| | | 260 | | /// <summary> |
| | | 261 | | /// 初始化存储(使用内部Allocator,带标志) |
| | | 262 | | /// </summary> |
| | | 263 | | public void Initialize(int maxEntities, StorageFlags flags, int blockCapacity = DefaultBlockCapacity, int compon |
| | | 264 | | { |
| | 9 | 265 | | var allocatorPtr = Allocator.Create(); |
| | 9 | 266 | | Initialize(maxEntities, allocatorPtr, flags, blockCapacity, componentTypeId); |
| | 9 | 267 | | _ownsAllocator = true; |
| | 9 | 268 | | } |
| | | 269 | | |
| | | 270 | | /// <summary> |
| | | 271 | | /// 初始化存储(使用外部Allocator) |
| | | 272 | | /// </summary> |
| | | 273 | | public void Initialize(int maxEntities, Allocator* allocator, int blockCapacity = DefaultBlockCapacity, int comp |
| | | 274 | | { |
| | 0 | 275 | | Initialize(maxEntities, allocator, StorageFlags.None, blockCapacity, componentTypeId); |
| | 0 | 276 | | } |
| | | 277 | | |
| | | 278 | | /// <summary> |
| | | 279 | | /// 初始化存储(使用外部Allocator,带标志) |
| | | 280 | | /// </summary> |
| | | 281 | | public void Initialize(int maxEntities, Allocator* allocator, StorageFlags flags, int blockCapacity = DefaultBlo |
| | | 282 | | { |
| | 1369 | 283 | | _sparseCapacity = maxEntities; |
| | 1369 | 284 | | _blockItemCapacity = ResolveBlockCapacity(blockCapacity); |
| | 1369 | 285 | | _stride = sizeof(T); |
| | 1369 | 286 | | _componentTypeId = componentTypeId; |
| | 1369 | 287 | | _count = 1; // 索引0保留为无效值 |
| | 1369 | 288 | | _version = 0; |
| | 1369 | 289 | | _allocator = allocator; |
| | 1369 | 290 | | _ownsAllocator = false; |
| | 1369 | 291 | | _flags = flags; |
| | 1369 | 292 | | _singletonSparse = 0; |
| | 1369 | 293 | | _pendingRemoval = 0; |
| | | 294 | | |
| | | 295 | | // 分配稀疏数组(初始化为0,即TOMBSTONE) |
| | 1369 | 296 | | _sparse = (ushort*)_allocator->AllocAndClear(sizeof(ushort) * maxEntities); |
| | | 297 | | |
| | 1369 | 298 | | if (IsDeferredRemoval) |
| | | 299 | | { |
| | 14 | 300 | | _entryStates = (byte*)_allocator->AllocAndClear(maxEntities + 1); |
| | 14 | 301 | | _pendingQueueIndices = (ushort*)_allocator->Alloc(sizeof(ushort) * (maxEntities + 1)); |
| | 576 | 302 | | for (int i = 0; i <= maxEntities; i++) |
| | | 303 | | { |
| | 274 | 304 | | _pendingQueueIndices[i] = PendingQueueIndexNone; |
| | | 305 | | } |
| | | 306 | | } |
| | | 307 | | else |
| | | 308 | | { |
| | 1355 | 309 | | _entryStates = null; |
| | 1355 | 310 | | _pendingQueueIndices = null; |
| | | 311 | | } |
| | | 312 | | |
| | | 313 | | // 分配 Block 列表 |
| | 1369 | 314 | | _blockCapacity = InitialBlockListCapacity; |
| | 1369 | 315 | | _blockCount = 0; |
| | 1369 | 316 | | _blocks = (Block*)_allocator->Alloc(sizeof(Block) * _blockCapacity); |
| | 13690 | 317 | | for (int i = 0; i < _blockCapacity; i++) |
| | | 318 | | { |
| | 5476 | 319 | | _blocks[i].PackedHandles = null; |
| | 5476 | 320 | | _blocks[i].PackedData = null; |
| | | 321 | | } |
| | 1369 | 322 | | } |
| | | 323 | | |
| | | 324 | | /// <summary> |
| | | 325 | | /// 释放所有内存 |
| | | 326 | | /// </summary> |
| | | 327 | | public void Dispose() |
| | | 328 | | { |
| | 9 | 329 | | if (_ownsAllocator && _allocator != null) |
| | | 330 | | { |
| | 9 | 331 | | Allocator.Destroy(_allocator); |
| | | 332 | | } |
| | | 333 | | |
| | 9 | 334 | | _blocks = null; |
| | 9 | 335 | | _sparse = null; |
| | 9 | 336 | | _entryStates = null; |
| | 9 | 337 | | _pendingQueueIndices = null; |
| | 9 | 338 | | _count = 0; |
| | 9 | 339 | | _blockCount = 0; |
| | 9 | 340 | | _allocator = null; |
| | 9 | 341 | | } |
| | | 342 | | |
| | | 343 | | #endregion |
| | | 344 | | |
| | | 345 | | #region 预测回滚支持(快照/恢复) |
| | | 346 | | |
| | | 347 | | /// <summary> |
| | | 348 | | /// 计算快照大小(字节) |
| | | 349 | | /// </summary> |
| | | 350 | | public int GetSnapshotSize() |
| | | 351 | | { |
| | 0 | 352 | | int denseCount = Count; |
| | 0 | 353 | | int size = |
| | 0 | 354 | | sizeof(int) * 6 + // _count, _version, _blockCount, _blockItemCapacity, _componentTypeId, _sparseCapa |
| | 0 | 355 | | sizeof(ushort) * 4 + // _singletonSparse, _pendingRemoval, _flags, reserved |
| | 0 | 356 | | sizeof(EntityRef) * denseCount + |
| | 0 | 357 | | sizeof(T) * denseCount; |
| | | 358 | | |
| | 0 | 359 | | if (_entryStates != null) |
| | | 360 | | { |
| | 0 | 361 | | size += denseCount; |
| | | 362 | | } |
| | | 363 | | |
| | 0 | 364 | | return size; |
| | | 365 | | } |
| | | 366 | | |
| | | 367 | | /// <summary> |
| | | 368 | | /// 创建快照(用于预测回滚) |
| | | 369 | | /// </summary> |
| | | 370 | | public void WriteSnapshot(byte* buffer, int bufferSize) |
| | | 371 | | { |
| | 0 | 372 | | byte* ptr = buffer; |
| | | 373 | | |
| | | 374 | | // 写入元数据 |
| | 0 | 375 | | *(int*)ptr = _count; ptr += sizeof(int); |
| | 0 | 376 | | *(int*)ptr = _version; ptr += sizeof(int); |
| | 0 | 377 | | *(int*)ptr = _blockCount; ptr += sizeof(int); |
| | 0 | 378 | | *(int*)ptr = _blockItemCapacity; ptr += sizeof(int); |
| | 0 | 379 | | *(int*)ptr = _componentTypeId; ptr += sizeof(int); |
| | 0 | 380 | | *(int*)ptr = _sparseCapacity; ptr += sizeof(int); |
| | 0 | 381 | | *(ushort*)ptr = _singletonSparse; ptr += sizeof(ushort); |
| | 0 | 382 | | *(ushort*)ptr = (ushort)_pendingRemoval; ptr += sizeof(ushort); |
| | 0 | 383 | | *(ushort*)ptr = (ushort)_flags; ptr += sizeof(ushort); |
| | 0 | 384 | | *(ushort*)ptr = 0; ptr += sizeof(ushort); |
| | | 385 | | |
| | 0 | 386 | | int denseCount = Count; |
| | 0 | 387 | | int handlesBytes = sizeof(EntityRef) * denseCount; |
| | 0 | 388 | | int dataBytes = sizeof(T) * denseCount; |
| | | 389 | | |
| | 0 | 390 | | CopyDenseEntities((EntityRef*)ptr, denseCount); |
| | 0 | 391 | | ptr += handlesBytes; |
| | | 392 | | |
| | 0 | 393 | | CopyDenseComponentBytes(ptr, denseCount); |
| | 0 | 394 | | ptr += dataBytes; |
| | | 395 | | |
| | 0 | 396 | | if (_entryStates != null && denseCount > 0) |
| | | 397 | | { |
| | 0 | 398 | | Buffer.MemoryCopy(_entryStates + 1, ptr, denseCount, denseCount); |
| | | 399 | | } |
| | 0 | 400 | | } |
| | | 401 | | |
| | | 402 | | /// <summary> |
| | | 403 | | /// 从快照恢复(用于回滚) |
| | | 404 | | /// </summary> |
| | | 405 | | public void ReadSnapshot(byte* buffer, int bufferSize) |
| | | 406 | | { |
| | 0 | 407 | | byte* ptr = buffer; |
| | | 408 | | |
| | | 409 | | // 读取元数据 |
| | 0 | 410 | | int savedCount = *(int*)ptr; ptr += sizeof(int); |
| | 0 | 411 | | int savedVersion = *(int*)ptr; ptr += sizeof(int); |
| | 0 | 412 | | int savedBlockCount = *(int*)ptr; ptr += sizeof(int); |
| | 0 | 413 | | int savedBlockItemCapacity = *(int*)ptr; ptr += sizeof(int); |
| | 0 | 414 | | int savedComponentTypeId = *(int*)ptr; ptr += sizeof(int); |
| | 0 | 415 | | int savedSparseCapacity = *(int*)ptr; ptr += sizeof(int); |
| | 0 | 416 | | ushort savedSingletonSparse = *(ushort*)ptr; ptr += sizeof(ushort); |
| | 0 | 417 | | ushort savedPendingRemoval = *(ushort*)ptr; ptr += sizeof(ushort); |
| | 0 | 418 | | StorageFlags savedFlags = (StorageFlags)(*(ushort*)ptr); ptr += sizeof(ushort); |
| | 0 | 419 | | ptr += sizeof(ushort); // reserved |
| | | 420 | | |
| | 0 | 421 | | if (savedSparseCapacity != _sparseCapacity) |
| | | 422 | | { |
| | 0 | 423 | | throw new InvalidOperationException( |
| | 0 | 424 | | $"Storage<{typeof(T).Name}> 快照容量不匹配。 Snapshot={savedSparseCapacity}, Current={_sparseCapacity}。"); |
| | | 425 | | } |
| | | 426 | | |
| | 0 | 427 | | _blockItemCapacity = savedBlockItemCapacity; |
| | 0 | 428 | | _componentTypeId = savedComponentTypeId; |
| | 0 | 429 | | _flags = savedFlags; |
| | | 430 | | |
| | | 431 | | // 确保容量足够 |
| | 0 | 432 | | EnsureEntityCapacity(savedBlockCount * savedBlockItemCapacity); |
| | | 433 | | |
| | | 434 | | // 恢复元数据 |
| | 0 | 435 | | _count = savedCount; |
| | 0 | 436 | | _version = savedVersion; |
| | 0 | 437 | | _blockCount = savedBlockCount; |
| | 0 | 438 | | _singletonSparse = savedSingletonSparse; |
| | 0 | 439 | | _pendingRemoval = 0; |
| | | 440 | | |
| | 0 | 441 | | ClearSparseAndStates(); |
| | 0 | 442 | | EnsureEntityCapacity(savedCount); |
| | | 443 | | |
| | 0 | 444 | | int denseCount = System.Math.Max(savedCount - 1, 0); |
| | 0 | 445 | | RestoreDenseEntities((EntityRef*)ptr, denseCount); |
| | 0 | 446 | | ptr += sizeof(EntityRef) * denseCount; |
| | | 447 | | |
| | 0 | 448 | | RestoreDenseComponentBytes(ptr, denseCount); |
| | 0 | 449 | | ptr += sizeof(T) * denseCount; |
| | | 450 | | |
| | 0 | 451 | | if (denseCount > 0) |
| | | 452 | | { |
| | 0 | 453 | | if (_entryStates != null) |
| | | 454 | | { |
| | 0 | 455 | | Buffer.MemoryCopy(ptr, _entryStates + 1, denseCount, denseCount); |
| | 0 | 456 | | ptr += denseCount; |
| | | 457 | | } |
| | | 458 | | else |
| | | 459 | | { |
| | 0 | 460 | | for (int i = 1; i <= denseCount; i++) |
| | | 461 | | { |
| | 0 | 462 | | SetEntryStateByIndex(i, EntryStateActive); |
| | | 463 | | } |
| | | 464 | | } |
| | | 465 | | } |
| | | 466 | | |
| | 0 | 467 | | for (int globalIndex = 1; globalIndex <= denseCount; globalIndex++) |
| | | 468 | | { |
| | 0 | 469 | | EntityRef entity = GetEntityRefByIndex(globalIndex); |
| | 0 | 470 | | _sparse[entity.Index] = (ushort)globalIndex; |
| | | 471 | | } |
| | | 472 | | |
| | 0 | 473 | | _pendingRemoval = savedPendingRemoval; |
| | 0 | 474 | | } |
| | | 475 | | |
| | | 476 | | /// <summary> |
| | | 477 | | /// 重置存储内容但保留已分配容量,供热路径复用。 |
| | | 478 | | /// </summary> |
| | | 479 | | internal void Reset() |
| | | 480 | | { |
| | 62 | 481 | | _count = 1; |
| | 62 | 482 | | _version = 0; |
| | 62 | 483 | | _singletonSparse = 0; |
| | 62 | 484 | | _pendingRemoval = 0; |
| | 62 | 485 | | ClearSparseAndStates(); |
| | 62 | 486 | | } |
| | | 487 | | |
| | | 488 | | /// <summary> |
| | | 489 | | /// 从同类型存储直接复制状态,避免走托管快照分配。 |
| | | 490 | | /// </summary> |
| | | 491 | | internal void CopyFrom(Storage<T>* source) |
| | | 492 | | { |
| | 2113 | 493 | | if (source == null) |
| | | 494 | | { |
| | 0 | 495 | | throw new ArgumentNullException(nameof(source)); |
| | | 496 | | } |
| | | 497 | | |
| | 2113 | 498 | | if (_componentTypeId != source->_componentTypeId) |
| | | 499 | | { |
| | 0 | 500 | | throw new InvalidOperationException("Cannot copy storage state from a different component type."); |
| | | 501 | | } |
| | | 502 | | |
| | 2113 | 503 | | if (_flags != source->_flags) |
| | | 504 | | { |
| | 0 | 505 | | throw new InvalidOperationException("Cannot copy storage state from a storage with different flags."); |
| | | 506 | | } |
| | | 507 | | |
| | 2113 | 508 | | if (_blockItemCapacity != source->_blockItemCapacity) |
| | | 509 | | { |
| | 0 | 510 | | throw new InvalidOperationException("Cannot copy storage state from a storage with different block layou |
| | | 511 | | } |
| | | 512 | | |
| | 2113 | 513 | | _count = source->_count; |
| | 2113 | 514 | | _version = source->_version; |
| | 2113 | 515 | | _singletonSparse = source->_singletonSparse; |
| | 2113 | 516 | | _pendingRemoval = source->_pendingRemoval; |
| | | 517 | | |
| | 2113 | 518 | | ClearSparseAndStates(); |
| | 2113 | 519 | | EnsureEntityCapacity(source->_count); |
| | | 520 | | |
| | 2113 | 521 | | int denseCount = source->Count; |
| | 2113 | 522 | | if (denseCount <= 0) |
| | | 523 | | { |
| | 2 | 524 | | return; |
| | | 525 | | } |
| | | 526 | | |
| | 2111 | 527 | | CopyDenseEntitiesFrom(source, denseCount); |
| | 2111 | 528 | | CopyDenseComponentBytesFrom(source, denseCount); |
| | | 529 | | |
| | 2111 | 530 | | if (_entryStates != null) |
| | | 531 | | { |
| | 0 | 532 | | if (source->_entryStates != null) |
| | | 533 | | { |
| | 0 | 534 | | Buffer.MemoryCopy(source->_entryStates + 1, _entryStates + 1, denseCount, denseCount); |
| | | 535 | | } |
| | | 536 | | else |
| | | 537 | | { |
| | 0 | 538 | | Unsafe.InitBlockUnaligned(_entryStates + 1, EntryStateActive, (uint)denseCount); |
| | | 539 | | } |
| | | 540 | | } |
| | | 541 | | |
| | 2111 | 542 | | int pendingQueueIndex = 0; |
| | 14308 | 543 | | for (int i = 1; i <= denseCount; i++) |
| | | 544 | | { |
| | 5043 | 545 | | EntityRef entity = GetEntityRefByGlobalIndex(i); |
| | 5043 | 546 | | _sparse[entity.Index] = (ushort)i; |
| | | 547 | | |
| | 5043 | 548 | | if (_pendingQueueIndices != null) |
| | | 549 | | { |
| | 0 | 550 | | if (GetEntryStateByIndex(i) == EntryStatePendingRemoval) |
| | | 551 | | { |
| | 0 | 552 | | _pendingQueueIndices[i] = (ushort)pendingQueueIndex++; |
| | | 553 | | } |
| | | 554 | | else |
| | | 555 | | { |
| | 0 | 556 | | _pendingQueueIndices[i] = PendingQueueIndexNone; |
| | | 557 | | } |
| | | 558 | | } |
| | | 559 | | } |
| | 2111 | 560 | | } |
| | | 561 | | |
| | | 562 | | /// <summary> |
| | | 563 | | /// 确保有足够的实体容量 |
| | | 564 | | /// </summary> |
| | | 565 | | private void EnsureEntityCapacity(int requiredCount) |
| | | 566 | | { |
| | 2355 | 567 | | int requiredBlocks = (requiredCount + _blockItemCapacity - 1) / _blockItemCapacity; |
| | | 568 | | |
| | | 569 | | // 扩展 Block 列表 |
| | 2355 | 570 | | if (requiredBlocks > _blockCapacity) |
| | | 571 | | { |
| | 0 | 572 | | int newCapacity = _blockCapacity; |
| | 0 | 573 | | while (newCapacity < requiredBlocks) |
| | 0 | 574 | | newCapacity *= 2; |
| | | 575 | | |
| | 0 | 576 | | var newBlocks = (Block*)_allocator->Alloc(sizeof(Block) * newCapacity); |
| | 0 | 577 | | Buffer.MemoryCopy(_blocks, newBlocks, sizeof(Block) * newCapacity, sizeof(Block) * _blockCapacity); |
| | | 578 | | |
| | 0 | 579 | | for (int i = _blockCapacity; i < newCapacity; i++) |
| | | 580 | | { |
| | 0 | 581 | | newBlocks[i].PackedHandles = null; |
| | 0 | 582 | | newBlocks[i].PackedData = null; |
| | | 583 | | } |
| | | 584 | | |
| | 0 | 585 | | _blocks = newBlocks; |
| | 0 | 586 | | _blockCapacity = newCapacity; |
| | | 587 | | } |
| | | 588 | | |
| | | 589 | | // 分配缺少的 Blocks |
| | 3430 | 590 | | while (_blockCount < requiredBlocks) |
| | | 591 | | { |
| | 1075 | 592 | | int blockIndex = _blockCount++; |
| | 1075 | 593 | | _blocks[blockIndex].PackedHandles = (EntityRef*)_allocator->Alloc(sizeof(EntityRef) * _blockItemCapacity |
| | 1075 | 594 | | _blocks[blockIndex].PackedData = (T*)_allocator->Alloc(sizeof(T) * _blockItemCapacity); |
| | | 595 | | |
| | 1075 | 596 | | if (blockIndex == 0) |
| | | 597 | | { |
| | 1075 | 598 | | _blocks[0].PackedHandles[0] = EntityRef.None; |
| | 1075 | 599 | | _blocks[0].PackedData[0] = default; |
| | | 600 | | } |
| | | 601 | | } |
| | 2355 | 602 | | } |
| | | 603 | | |
| | | 604 | | #endregion |
| | | 605 | | |
| | | 606 | | #region 核心操作 |
| | | 607 | | |
| | | 608 | | /// <summary> |
| | | 609 | | /// 添加组件 - O(1) 均摊 |
| | | 610 | | /// </summary> |
| | | 611 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 612 | | public void Add(EntityRef entity, in T component) |
| | | 613 | | { |
| | 14086 | 614 | | int index = entity.Index; |
| | | 615 | | |
| | | 616 | | #if DEBUG |
| | | 617 | | if ((uint)index >= (uint)_sparseCapacity) |
| | | 618 | | throw new ArgumentOutOfRangeException(nameof(entity), "Entity index out of range"); |
| | | 619 | | if (GetSparseIndex(entity) != TOMBSTONE) |
| | | 620 | | throw new InvalidOperationException($"Component already exists for entity {entity}"); |
| | | 621 | | #endif |
| | | 622 | | |
| | | 623 | | // 单例检查 |
| | 14086 | 624 | | if (IsSingleton) |
| | | 625 | | { |
| | 26 | 626 | | if (_singletonSparse != 0) |
| | | 627 | | { |
| | 0 | 628 | | throw new InvalidOperationException( |
| | 0 | 629 | | $"Cannot add multiple instances of singleton component {typeof(T).Name}. " + |
| | 0 | 630 | | $"Existing entity: {GetEntityRefByGlobalIndex(_singletonSparse)}"); |
| | | 631 | | } |
| | | 632 | | } |
| | | 633 | | |
| | | 634 | | // 确保有空间 |
| | 14086 | 635 | | if (_count >= (_blockCount * _blockItemCapacity)) |
| | 314 | 636 | | EnsureBlockSpace(); |
| | | 637 | | |
| | 14086 | 638 | | int globalIndex = _count++; |
| | 14086 | 639 | | int block = globalIndex / _blockItemCapacity; |
| | 14086 | 640 | | int offset = globalIndex % _blockItemCapacity; |
| | | 641 | | |
| | | 642 | | // 写入数据 |
| | 14086 | 643 | | Block* b = &_blocks[block]; |
| | 14086 | 644 | | b->PackedHandles[offset] = entity; |
| | 14086 | 645 | | b->PackedData[offset] = component; |
| | | 646 | | |
| | | 647 | | // 更新稀疏数组 |
| | 14086 | 648 | | _sparse[index] = (ushort)globalIndex; |
| | 14086 | 649 | | SetEntryStateByIndex(globalIndex, EntryStateActive); |
| | 14086 | 650 | | SetPendingQueueIndexByIndex(globalIndex, PendingQueueIndexNone); |
| | | 651 | | |
| | | 652 | | // 更新单例索引 |
| | 14086 | 653 | | if (IsSingleton) |
| | | 654 | | { |
| | 26 | 655 | | _singletonSparse = (ushort)globalIndex; |
| | | 656 | | } |
| | | 657 | | |
| | 14086 | 658 | | _version++; |
| | 14086 | 659 | | } |
| | | 660 | | |
| | | 661 | | /// <summary> |
| | | 662 | | /// 删除组件 - O(1) |
| | | 663 | | /// 如果启用延迟删除,则标记为待删除,需要调用 CommitRemovals 才真正删除 |
| | | 664 | | /// </summary> |
| | | 665 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 666 | | public void Remove(EntityRef entity) |
| | | 667 | | { |
| | 10800 | 668 | | int index = entity.Index; |
| | 10800 | 669 | | ushort globalIndex = GetSparseIndex(entity); |
| | | 670 | | |
| | | 671 | | #if DEBUG |
| | | 672 | | if ((uint)index >= (uint)_sparseCapacity || globalIndex == TOMBSTONE) |
| | | 673 | | throw new InvalidOperationException($"Component not found for entity {entity}"); |
| | | 674 | | #endif |
| | | 675 | | |
| | | 676 | | // 延迟删除模式:只标记,不立即删除 |
| | 10800 | 677 | | if (IsDeferredRemoval) |
| | | 678 | | { |
| | 0 | 679 | | if (GetEntryStateByIndex(globalIndex) == EntryStatePendingRemoval) |
| | | 680 | | { |
| | 0 | 681 | | return; |
| | | 682 | | } |
| | | 683 | | |
| | 0 | 684 | | SetEntryStateByIndex(globalIndex, EntryStatePendingRemoval); |
| | 0 | 685 | | _pendingRemoval++; |
| | | 686 | | |
| | | 687 | | // 清除单例索引 |
| | 0 | 688 | | if (IsSingleton && _singletonSparse == globalIndex) |
| | | 689 | | { |
| | 0 | 690 | | _singletonSparse = 0; |
| | | 691 | | } |
| | | 692 | | |
| | 0 | 693 | | _version++; |
| | 0 | 694 | | return; |
| | | 695 | | } |
| | | 696 | | |
| | | 697 | | // 立即删除模式 |
| | 10800 | 698 | | RemoveImmediate(index, globalIndex); |
| | 10800 | 699 | | } |
| | | 700 | | |
| | | 701 | | /// <summary> |
| | | 702 | | /// 立即删除组件(内部方法) |
| | | 703 | | /// </summary> |
| | | 704 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 705 | | private void RemoveImmediate(int entityIndex, ushort globalIndex) |
| | | 706 | | { |
| | 10801 | 707 | | int lastGlobalIndex = --_count; |
| | | 708 | | |
| | | 709 | | // 如果不是最后一个,与末尾交换 |
| | 10801 | 710 | | if (globalIndex != lastGlobalIndex) |
| | | 711 | | { |
| | 5742 | 712 | | int lastBlock = lastGlobalIndex / _blockItemCapacity; |
| | 5742 | 713 | | int lastOffset = lastGlobalIndex % _blockItemCapacity; |
| | | 714 | | |
| | 5742 | 715 | | int block = globalIndex / _blockItemCapacity; |
| | 5742 | 716 | | int offset = globalIndex % _blockItemCapacity; |
| | | 717 | | |
| | 5742 | 718 | | EntityRef lastEntity = _blocks[lastBlock].PackedHandles[lastOffset]; |
| | 5742 | 719 | | T lastComponent = _blocks[lastBlock].PackedData[lastOffset]; |
| | 5742 | 720 | | byte lastState = GetEntryStateByIndex(lastGlobalIndex); |
| | | 721 | | |
| | 5742 | 722 | | _blocks[block].PackedHandles[offset] = lastEntity; |
| | 5742 | 723 | | _blocks[block].PackedData[offset] = lastComponent; |
| | 5742 | 724 | | SetEntryStateByIndex(globalIndex, lastState); |
| | 5742 | 725 | | SetPendingQueueIndexByIndex(globalIndex, GetPendingQueueIndexByIndex(lastGlobalIndex)); |
| | | 726 | | |
| | | 727 | | // 更新被移动实体的稀疏索引 |
| | 5742 | 728 | | _sparse[lastEntity.Index] = globalIndex; |
| | | 729 | | |
| | | 730 | | // 更新单例索引(如果被移动的是单例) |
| | 5742 | 731 | | if (IsSingleton && _singletonSparse == lastGlobalIndex) |
| | | 732 | | { |
| | 0 | 733 | | _singletonSparse = globalIndex; |
| | | 734 | | } |
| | | 735 | | } |
| | | 736 | | |
| | 10801 | 737 | | _sparse[entityIndex] = TOMBSTONE; |
| | 10801 | 738 | | SetEntryStateByIndex(lastGlobalIndex, EntryStateEmpty); |
| | 10801 | 739 | | SetPendingQueueIndexByIndex(lastGlobalIndex, PendingQueueIndexNone); |
| | | 740 | | |
| | | 741 | | // 清除单例索引 |
| | 10801 | 742 | | if (IsSingleton && _singletonSparse == globalIndex) |
| | | 743 | | { |
| | 2 | 744 | | _singletonSparse = 0; |
| | | 745 | | } |
| | | 746 | | |
| | 10801 | 747 | | _version++; |
| | 10801 | 748 | | } |
| | | 749 | | |
| | | 750 | | /// <summary> |
| | | 751 | | /// 提交所有待删除(延迟删除模式) |
| | | 752 | | /// 注意:此实现需要 Frame 层维护待删除列表来配合 |
| | | 753 | | /// </summary> |
| | | 754 | | public void CommitRemovals(Span<EntityRef> entitiesToRemove) |
| | | 755 | | { |
| | 0 | 756 | | if (!IsDeferredRemoval || entitiesToRemove.IsEmpty) |
| | 0 | 757 | | return; |
| | | 758 | | |
| | 0 | 759 | | foreach (var entity in entitiesToRemove) |
| | | 760 | | { |
| | 0 | 761 | | CommitRemoval(entity); |
| | | 762 | | } |
| | 0 | 763 | | } |
| | | 764 | | |
| | | 765 | | /// <summary> |
| | | 766 | | /// 标记组件为待删除(延迟删除模式) |
| | | 767 | | /// </summary> |
| | | 768 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 769 | | public void MarkForRemoval(EntityRef entity) |
| | | 770 | | { |
| | 8 | 771 | | if (!IsDeferredRemoval) |
| | | 772 | | { |
| | 0 | 773 | | Remove(entity); |
| | 0 | 774 | | return; |
| | | 775 | | } |
| | | 776 | | |
| | | 777 | | int index = entity.Index; |
| | 8 | 778 | | ushort globalIndex = GetSparseIndex(entity); |
| | | 779 | | |
| | | 780 | | #if DEBUG |
| | | 781 | | if ((uint)index >= (uint)_sparseCapacity || globalIndex == TOMBSTONE) |
| | | 782 | | throw new InvalidOperationException($"Component not found for entity {entity}"); |
| | | 783 | | #endif |
| | | 784 | | |
| | 8 | 785 | | _pendingRemoval++; |
| | 8 | 786 | | SetEntryStateByIndex(globalIndex, EntryStatePendingRemoval); |
| | | 787 | | |
| | | 788 | | // 清除单例索引 |
| | 8 | 789 | | if (IsSingleton && _singletonSparse == globalIndex) |
| | | 790 | | { |
| | 0 | 791 | | _singletonSparse = 0; |
| | | 792 | | } |
| | | 793 | | |
| | 8 | 794 | | _version++; |
| | 8 | 795 | | } |
| | | 796 | | |
| | | 797 | | /// <summary> |
| | | 798 | | /// 取消待删除状态,允许组件在同一帧内恢复。 |
| | | 799 | | /// </summary> |
| | | 800 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 801 | | internal void CancelPendingRemoval(EntityRef entity) |
| | | 802 | | { |
| | 1 | 803 | | if (!IsDeferredRemoval) |
| | | 804 | | { |
| | 0 | 805 | | return; |
| | | 806 | | } |
| | | 807 | | |
| | 1 | 808 | | int index = entity.Index; |
| | 1 | 809 | | if ((uint)index >= (uint)_sparseCapacity) |
| | | 810 | | { |
| | 0 | 811 | | return; |
| | | 812 | | } |
| | | 813 | | |
| | 1 | 814 | | ushort globalIndex = GetSparseIndex(entity); |
| | 1 | 815 | | if (globalIndex == TOMBSTONE) |
| | | 816 | | { |
| | 0 | 817 | | return; |
| | | 818 | | } |
| | | 819 | | |
| | 1 | 820 | | if (_pendingRemoval > 0) |
| | | 821 | | { |
| | 1 | 822 | | _pendingRemoval--; |
| | | 823 | | } |
| | | 824 | | |
| | 1 | 825 | | SetEntryStateByIndex(globalIndex, EntryStateActive); |
| | 1 | 826 | | SetPendingQueueIndexByIndex(globalIndex, PendingQueueIndexNone); |
| | | 827 | | |
| | 1 | 828 | | if (IsSingleton) |
| | | 829 | | { |
| | 0 | 830 | | _singletonSparse = globalIndex; |
| | | 831 | | } |
| | | 832 | | |
| | 1 | 833 | | _version++; |
| | 1 | 834 | | } |
| | | 835 | | |
| | | 836 | | /// <summary> |
| | | 837 | | /// 提交单个待删除组件。 |
| | | 838 | | /// </summary> |
| | | 839 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 840 | | internal void CommitRemoval(EntityRef entity) |
| | | 841 | | { |
| | 1 | 842 | | int index = entity.Index; |
| | 1 | 843 | | if ((uint)index >= (uint)_sparseCapacity) |
| | | 844 | | { |
| | 0 | 845 | | return; |
| | | 846 | | } |
| | | 847 | | |
| | 1 | 848 | | ushort globalIndex = GetSparseIndex(entity); |
| | 1 | 849 | | if (globalIndex == TOMBSTONE) |
| | | 850 | | { |
| | 0 | 851 | | return; |
| | | 852 | | } |
| | | 853 | | |
| | 1 | 854 | | if (GetEntryStateByIndex(globalIndex) != EntryStatePendingRemoval) |
| | | 855 | | { |
| | 0 | 856 | | return; |
| | | 857 | | } |
| | | 858 | | |
| | 1 | 859 | | RemoveImmediate(index, globalIndex); |
| | 1 | 860 | | if (_pendingRemoval > 0) |
| | | 861 | | { |
| | 1 | 862 | | _pendingRemoval--; |
| | | 863 | | } |
| | 1 | 864 | | } |
| | | 865 | | |
| | | 866 | | /// <summary> |
| | | 867 | | /// 获取单例组件指针(仅单例模式有效) |
| | | 868 | | /// </summary> |
| | | 869 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 870 | | public T* GetSingletonPointer() |
| | | 871 | | { |
| | 0 | 872 | | if (!IsSingleton || _singletonSparse == 0) |
| | 0 | 873 | | return null; |
| | | 874 | | |
| | 0 | 875 | | int block = _singletonSparse / _blockItemCapacity; |
| | 0 | 876 | | int offset = _singletonSparse % _blockItemCapacity; |
| | 0 | 877 | | return &_blocks[block].PackedData[offset]; |
| | | 878 | | } |
| | | 879 | | |
| | | 880 | | /// <summary> |
| | | 881 | | /// 获取单例组件引用(仅单例模式有效) |
| | | 882 | | /// </summary> |
| | | 883 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 884 | | public ref T GetSingleton() |
| | | 885 | | { |
| | 227 | 886 | | if (!IsSingleton || _singletonSparse == 0) |
| | 0 | 887 | | throw new InvalidOperationException($"Singleton component {typeof(T).Name} not found"); |
| | | 888 | | |
| | 227 | 889 | | int block = _singletonSparse / _blockItemCapacity; |
| | 227 | 890 | | int offset = _singletonSparse % _blockItemCapacity; |
| | 227 | 891 | | return ref _blocks[block].PackedData[offset]; |
| | | 892 | | } |
| | | 893 | | |
| | | 894 | | /// <summary> |
| | | 895 | | /// 获取组件引用 - O(1) |
| | | 896 | | /// </summary> |
| | | 897 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 898 | | public ref T Get(EntityRef entity) |
| | | 899 | | { |
| | 10243 | 900 | | ushort globalIndex = GetSparseIndex(entity); |
| | | 901 | | #if DEBUG |
| | | 902 | | if ((uint)entity.Index >= (uint)_sparseCapacity || globalIndex == TOMBSTONE) |
| | | 903 | | throw new InvalidOperationException($"Component not found for entity {entity}"); |
| | | 904 | | #endif |
| | 10243 | 905 | | int block = globalIndex / _blockItemCapacity; |
| | 10243 | 906 | | int offset = globalIndex % _blockItemCapacity; |
| | 10243 | 907 | | return ref _blocks[block].PackedData[offset]; |
| | | 908 | | } |
| | | 909 | | |
| | | 910 | | /// <summary> |
| | | 911 | | /// 获取组件指针 - O(1) |
| | | 912 | | /// </summary> |
| | | 913 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 914 | | public T* GetPointer(EntityRef entity) |
| | | 915 | | { |
| | 16 | 916 | | ushort globalIndex = GetSparseIndex(entity); |
| | 16 | 917 | | if (globalIndex == TOMBSTONE) return null; |
| | 16 | 918 | | int block = globalIndex / _blockItemCapacity; |
| | 16 | 919 | | int offset = globalIndex % _blockItemCapacity; |
| | 16 | 920 | | return &_blocks[block].PackedData[offset]; |
| | | 921 | | } |
| | | 922 | | |
| | | 923 | | /// <summary> |
| | | 924 | | /// 在调用方已经通过 Frame 位图确认组件存在时,直接按实体索引读取组件指针。 |
| | | 925 | | /// 该路径跳过额外的 EntityRef 回读校验,用于 Query 热路径。 |
| | | 926 | | /// </summary> |
| | | 927 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 928 | | internal T* GetPointerAssumePresent(EntityRef entity) |
| | | 929 | | { |
| | 2426 | 930 | | uint entityIndex = (uint)entity.Index; |
| | 2426 | 931 | | if (entityIndex >= (uint)_sparseCapacity) |
| | | 932 | | { |
| | 0 | 933 | | return null; |
| | | 934 | | } |
| | | 935 | | |
| | 2426 | 936 | | ushort globalIndex = _sparse[entityIndex]; |
| | 2426 | 937 | | if (globalIndex == TOMBSTONE) |
| | | 938 | | { |
| | 0 | 939 | | return null; |
| | | 940 | | } |
| | | 941 | | |
| | | 942 | | #if DEBUG |
| | | 943 | | if (GetEntityRefByGlobalIndex(globalIndex).Raw != entity.Raw) |
| | | 944 | | { |
| | | 945 | | throw new InvalidOperationException( |
| | | 946 | | $"Storage<{typeof(T).Name}> 检测到实体位图与稀疏索引不一致,Entity={entity}。"); |
| | | 947 | | } |
| | | 948 | | |
| | | 949 | | if (GetEntryStateByIndex(globalIndex) != EntryStateActive) |
| | | 950 | | { |
| | | 951 | | throw new InvalidOperationException( |
| | | 952 | | $"Storage<{typeof(T).Name}> 检测到非 Active 条目进入 Query 热路径,Entity={entity}。"); |
| | | 953 | | } |
| | | 954 | | #endif |
| | | 955 | | |
| | 2426 | 956 | | int block = globalIndex / _blockItemCapacity; |
| | 2426 | 957 | | int offset = globalIndex % _blockItemCapacity; |
| | 2426 | 958 | | return &_blocks[block].PackedData[offset]; |
| | | 959 | | } |
| | | 960 | | |
| | | 961 | | /// <summary> |
| | | 962 | | /// 尝试获取组件 - O(1) |
| | | 963 | | /// </summary> |
| | | 964 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 965 | | public bool TryGet(EntityRef entity, out T component) |
| | | 966 | | { |
| | 0 | 967 | | int index = entity.Index; |
| | 0 | 968 | | if ((uint)index < (uint)_sparseCapacity) |
| | | 969 | | { |
| | 0 | 970 | | ushort globalIndex = GetSparseIndex(entity); |
| | 0 | 971 | | if (globalIndex != TOMBSTONE) |
| | | 972 | | { |
| | 0 | 973 | | int block = globalIndex / _blockItemCapacity; |
| | 0 | 974 | | int offset = globalIndex % _blockItemCapacity; |
| | 0 | 975 | | component = _blocks[block].PackedData[offset]; |
| | 0 | 976 | | return true; |
| | | 977 | | } |
| | | 978 | | } |
| | 0 | 979 | | component = default; |
| | 0 | 980 | | return false; |
| | | 981 | | } |
| | | 982 | | |
| | | 983 | | /// <summary> |
| | | 984 | | /// 检查是否存在 - O(1) |
| | | 985 | | /// </summary> |
| | | 986 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 987 | | public bool Has(EntityRef entity) |
| | | 988 | | { |
| | 22217 | 989 | | uint index = (uint)entity.Index; |
| | 22217 | 990 | | return index < (uint)_sparseCapacity && GetSparseIndex(entity) != TOMBSTONE; |
| | | 991 | | } |
| | | 992 | | |
| | | 993 | | /// <summary> |
| | | 994 | | /// 检查组件是否处于待删除状态。 |
| | | 995 | | /// </summary> |
| | | 996 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 997 | | internal bool IsPendingRemoval(EntityRef entity) |
| | | 998 | | { |
| | 0 | 999 | | ushort globalIndex = GetSparseIndex(entity); |
| | 0 | 1000 | | return globalIndex != TOMBSTONE && GetEntryStateByIndex(globalIndex) == EntryStatePendingRemoval; |
| | | 1001 | | } |
| | | 1002 | | |
| | | 1003 | | /// <summary> |
| | | 1004 | | /// 获取待删除队列索引。 |
| | | 1005 | | /// </summary> |
| | | 1006 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1007 | | internal int GetPendingQueueIndex(EntityRef entity) |
| | | 1008 | | { |
| | 1 | 1009 | | ushort globalIndex = GetSparseIndex(entity); |
| | 1 | 1010 | | return globalIndex == TOMBSTONE ? PendingQueueIndexNone : GetPendingQueueIndexByIndex(globalIndex); |
| | | 1011 | | } |
| | | 1012 | | |
| | | 1013 | | /// <summary> |
| | | 1014 | | /// 设置待删除队列索引。 |
| | | 1015 | | /// </summary> |
| | | 1016 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1017 | | internal void SetPendingQueueIndex(EntityRef entity, int queueIndex) |
| | | 1018 | | { |
| | 8 | 1019 | | ushort globalIndex = GetSparseIndex(entity); |
| | 8 | 1020 | | if (globalIndex == TOMBSTONE) |
| | | 1021 | | { |
| | 0 | 1022 | | return; |
| | | 1023 | | } |
| | | 1024 | | |
| | 8 | 1025 | | SetPendingQueueIndexByIndex(globalIndex, queueIndex); |
| | 8 | 1026 | | } |
| | | 1027 | | |
| | | 1028 | | #endregion |
| | | 1029 | | |
| | | 1030 | | #region Block 访问 API |
| | | 1031 | | |
| | | 1032 | | /// <summary> |
| | | 1033 | | /// 获取指定 Block 的数据指针 |
| | | 1034 | | /// </summary> |
| | | 1035 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1036 | | public T* GetBlockData(int blockIndex) |
| | | 1037 | | { |
| | | 1038 | | #if DEBUG |
| | | 1039 | | if ((uint)blockIndex >= (uint)_blockCount) |
| | | 1040 | | throw new ArgumentOutOfRangeException(nameof(blockIndex)); |
| | | 1041 | | #endif |
| | 104108 | 1042 | | return _blocks[blockIndex].PackedData; |
| | | 1043 | | } |
| | | 1044 | | |
| | | 1045 | | /// <summary> |
| | | 1046 | | /// 获取指定 Block 的实体引用指针 |
| | | 1047 | | /// </summary> |
| | | 1048 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1049 | | public EntityRef* GetBlockEntityRefs(int blockIndex) |
| | | 1050 | | { |
| | | 1051 | | #if DEBUG |
| | | 1052 | | if ((uint)blockIndex >= (uint)_blockCount) |
| | | 1053 | | throw new ArgumentOutOfRangeException(nameof(blockIndex)); |
| | | 1054 | | #endif |
| | 104108 | 1055 | | return _blocks[blockIndex].PackedHandles; |
| | | 1056 | | } |
| | | 1057 | | |
| | | 1058 | | /// <summary> |
| | | 1059 | | /// 获取 Block 中有效项的数量 |
| | | 1060 | | /// </summary> |
| | | 1061 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1062 | | public int GetBlockItemCount(int blockIndex) |
| | | 1063 | | { |
| | 104108 | 1064 | | if (blockIndex < 0 || blockIndex >= _blockCount) return 0; |
| | | 1065 | | |
| | 104108 | 1066 | | int startIndex = blockIndex * _blockItemCapacity; |
| | 104108 | 1067 | | int endIndex = System.Math.Min(startIndex + _blockItemCapacity, _count); |
| | 104108 | 1068 | | return System.Math.Max(0, endIndex - startIndex); |
| | | 1069 | | } |
| | | 1070 | | |
| | | 1071 | | /// <summary> |
| | | 1072 | | /// 获取指定全局索引上的实体引用。 |
| | | 1073 | | /// </summary> |
| | | 1074 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1075 | | internal EntityRef GetEntityRefByIndex(int globalIndex) |
| | | 1076 | | { |
| | 8 | 1077 | | return GetEntityRefByGlobalIndex(globalIndex); |
| | | 1078 | | } |
| | | 1079 | | |
| | | 1080 | | /// <summary> |
| | | 1081 | | /// 获取指定全局索引上的组件数据指针。 |
| | | 1082 | | /// </summary> |
| | | 1083 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1084 | | internal T* GetDataPointerByIndex(int globalIndex) |
| | | 1085 | | { |
| | | 1086 | | #if DEBUG |
| | | 1087 | | if (globalIndex <= 0 || globalIndex >= _count) |
| | | 1088 | | throw new ArgumentOutOfRangeException(nameof(globalIndex)); |
| | | 1089 | | #endif |
| | 8 | 1090 | | int block = globalIndex / _blockItemCapacity; |
| | 8 | 1091 | | int offset = globalIndex % _blockItemCapacity; |
| | 8 | 1092 | | return &_blocks[block].PackedData[offset]; |
| | | 1093 | | } |
| | | 1094 | | |
| | | 1095 | | /// <summary> |
| | | 1096 | | /// 按 0 基 dense 索引访问条目。 |
| | | 1097 | | /// 该辅助方法用于把对外的连续遍历索引映射到内部 1 基稠密存储布局。 |
| | | 1098 | | /// </summary> |
| | | 1099 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1100 | | internal void GetDenseEntryByLinearIndex(int denseIndex, out EntityRef entity, out T* component) |
| | | 1101 | | { |
| | | 1102 | | #if DEBUG |
| | | 1103 | | if ((uint)denseIndex >= (uint)Count) |
| | | 1104 | | throw new ArgumentOutOfRangeException(nameof(denseIndex)); |
| | | 1105 | | #endif |
| | 4 | 1106 | | int globalIndex = denseIndex + 1; |
| | 4 | 1107 | | int block = globalIndex / _blockItemCapacity; |
| | 4 | 1108 | | int offset = globalIndex % _blockItemCapacity; |
| | 4 | 1109 | | entity = _blocks[block].PackedHandles[offset]; |
| | 4 | 1110 | | component = &_blocks[block].PackedData[offset]; |
| | 4 | 1111 | | } |
| | | 1112 | | |
| | | 1113 | | /// <summary> |
| | | 1114 | | /// 检查指定全局索引上的条目是否为 active。 |
| | | 1115 | | /// 没有启用状态跟踪时,非空 dense 条目都视为 active。 |
| | | 1116 | | /// </summary> |
| | | 1117 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1118 | | internal bool IsDenseEntryActive(int globalIndex) |
| | | 1119 | | { |
| | 4106 | 1120 | | return GetEntryStateByIndex(globalIndex) == EntryStateActive; |
| | | 1121 | | } |
| | | 1122 | | |
| | | 1123 | | /// <summary> |
| | | 1124 | | /// 将密集实体数组复制到托管缓冲区。 |
| | | 1125 | | /// </summary> |
| | | 1126 | | internal void CopyDenseEntities(EntityRef[] destination) |
| | | 1127 | | { |
| | 6 | 1128 | | if (destination == null) |
| | | 1129 | | { |
| | 0 | 1130 | | throw new ArgumentNullException(nameof(destination)); |
| | | 1131 | | } |
| | | 1132 | | |
| | 6 | 1133 | | if (destination.Length < Count) |
| | | 1134 | | { |
| | 0 | 1135 | | throw new ArgumentException("Destination buffer is too small.", nameof(destination)); |
| | | 1136 | | } |
| | | 1137 | | |
| | 6 | 1138 | | fixed (EntityRef* dest = destination) |
| | | 1139 | | { |
| | 6 | 1140 | | CopyDenseEntities(dest, Count); |
| | | 1141 | | } |
| | 6 | 1142 | | } |
| | | 1143 | | |
| | | 1144 | | /// <summary> |
| | | 1145 | | /// 将密集实体数组直接写入状态写入器。 |
| | | 1146 | | /// </summary> |
| | | 1147 | | internal void WriteDenseEntities(FrameStateWriter writer) |
| | | 1148 | | { |
| | 1081 | 1149 | | if (writer == null) |
| | | 1150 | | { |
| | 0 | 1151 | | throw new ArgumentNullException(nameof(writer)); |
| | | 1152 | | } |
| | | 1153 | | |
| | 1081 | 1154 | | int copied = 0; |
| | 4324 | 1155 | | for (int blockIndex = 0; blockIndex < _blockCount && copied < Count; blockIndex++) |
| | | 1156 | | { |
| | 1081 | 1157 | | int blockCount = GetDenseBlockCopyCount(blockIndex, Count - copied); |
| | 1081 | 1158 | | if (blockCount <= 0) |
| | | 1159 | | { |
| | | 1160 | | continue; |
| | | 1161 | | } |
| | | 1162 | | |
| | 1081 | 1163 | | int sourceOffset = blockIndex == 0 ? 1 : 0; |
| | 1081 | 1164 | | writer.WriteBytes(_blocks[blockIndex].PackedHandles + sourceOffset, sizeof(EntityRef) * blockCount); |
| | 1081 | 1165 | | copied += blockCount; |
| | | 1166 | | } |
| | 1081 | 1167 | | } |
| | | 1168 | | |
| | | 1169 | | /// <summary> |
| | | 1170 | | /// 将密集组件数据复制到字节缓冲区。 |
| | | 1171 | | /// </summary> |
| | | 1172 | | internal void CopyDenseComponentBytes(byte[] destination) |
| | | 1173 | | { |
| | 6 | 1174 | | if (destination == null) |
| | | 1175 | | { |
| | 0 | 1176 | | throw new ArgumentNullException(nameof(destination)); |
| | | 1177 | | } |
| | | 1178 | | |
| | 6 | 1179 | | int byteCount = Count * sizeof(T); |
| | 6 | 1180 | | if (destination.Length < byteCount) |
| | | 1181 | | { |
| | 0 | 1182 | | throw new ArgumentException("Destination buffer is too small.", nameof(destination)); |
| | | 1183 | | } |
| | | 1184 | | |
| | 6 | 1185 | | fixed (byte* dest = destination) |
| | | 1186 | | { |
| | 6 | 1187 | | CopyDenseComponentBytes(dest, Count); |
| | | 1188 | | } |
| | 6 | 1189 | | } |
| | | 1190 | | |
| | | 1191 | | /// <summary> |
| | | 1192 | | /// 将密集组件数据直接写入状态写入器。 |
| | | 1193 | | /// </summary> |
| | | 1194 | | internal void WriteDenseComponentBytes(FrameStateWriter writer) |
| | | 1195 | | { |
| | 1081 | 1196 | | if (writer == null) |
| | | 1197 | | { |
| | 0 | 1198 | | throw new ArgumentNullException(nameof(writer)); |
| | | 1199 | | } |
| | | 1200 | | |
| | 1081 | 1201 | | int copied = 0; |
| | 4324 | 1202 | | for (int blockIndex = 0; blockIndex < _blockCount && copied < Count; blockIndex++) |
| | | 1203 | | { |
| | 1081 | 1204 | | int blockCount = GetDenseBlockCopyCount(blockIndex, Count - copied); |
| | 1081 | 1205 | | if (blockCount <= 0) |
| | | 1206 | | { |
| | | 1207 | | continue; |
| | | 1208 | | } |
| | | 1209 | | |
| | 1081 | 1210 | | int sourceOffset = blockIndex == 0 ? 1 : 0; |
| | 1081 | 1211 | | writer.WriteBytes(_blocks[blockIndex].PackedData + sourceOffset, sizeof(T) * blockCount); |
| | 1081 | 1212 | | copied += blockCount; |
| | | 1213 | | } |
| | 1081 | 1214 | | } |
| | | 1215 | | |
| | | 1216 | | /// <summary> |
| | | 1217 | | /// 使用原始密集快照恢复组件存储。 |
| | | 1218 | | /// </summary> |
| | | 1219 | | internal void RestoreDenseSnapshot(EntityRef[] entities, byte[] componentData) |
| | | 1220 | | { |
| | 4 | 1221 | | if (entities == null) |
| | | 1222 | | { |
| | 0 | 1223 | | throw new ArgumentNullException(nameof(entities)); |
| | | 1224 | | } |
| | | 1225 | | |
| | 4 | 1226 | | if (componentData == null) |
| | | 1227 | | { |
| | 0 | 1228 | | throw new ArgumentNullException(nameof(componentData)); |
| | | 1229 | | } |
| | | 1230 | | |
| | 4 | 1231 | | int denseCount = entities.Length; |
| | 4 | 1232 | | if (componentData.Length != denseCount * sizeof(T)) |
| | | 1233 | | { |
| | 0 | 1234 | | throw new ArgumentException("Component snapshot data size does not match entity count.", nameof(componen |
| | | 1235 | | } |
| | | 1236 | | |
| | 4 | 1237 | | fixed (EntityRef* entityPtr = entities) |
| | 4 | 1238 | | fixed (byte* dataPtr = componentData) |
| | | 1239 | | { |
| | 4 | 1240 | | RestoreDenseSnapshot(entityPtr, dataPtr, denseCount); |
| | | 1241 | | } |
| | | 1242 | | |
| | 4 | 1243 | | _version++; |
| | 4 | 1244 | | } |
| | | 1245 | | |
| | | 1246 | | /// <summary> |
| | | 1247 | | /// 使用连续字节片段恢复组件存储。 |
| | | 1248 | | /// </summary> |
| | | 1249 | | internal void RestoreDenseSnapshot(ReadOnlySpan<byte> entityBytes, ReadOnlySpan<byte> componentBytes) |
| | | 1250 | | { |
| | 238 | 1251 | | if ((entityBytes.Length % sizeof(EntityRef)) != 0) |
| | | 1252 | | { |
| | 0 | 1253 | | throw new ArgumentException("Entity snapshot byte length is invalid.", nameof(entityBytes)); |
| | | 1254 | | } |
| | | 1255 | | |
| | 238 | 1256 | | int denseCount = entityBytes.Length / sizeof(EntityRef); |
| | 238 | 1257 | | if (componentBytes.Length != denseCount * sizeof(T)) |
| | | 1258 | | { |
| | 0 | 1259 | | throw new ArgumentException("Component snapshot byte length does not match entity count.", nameof(compon |
| | | 1260 | | } |
| | | 1261 | | |
| | | 1262 | | unsafe |
| | | 1263 | | { |
| | 238 | 1264 | | fixed (byte* entityPtrRaw = entityBytes) |
| | 238 | 1265 | | fixed (byte* componentPtr = componentBytes) |
| | | 1266 | | { |
| | 238 | 1267 | | RestoreDenseSnapshot((EntityRef*)entityPtrRaw, componentPtr, denseCount); |
| | | 1268 | | } |
| | | 1269 | | } |
| | | 1270 | | |
| | 238 | 1271 | | _version++; |
| | 238 | 1272 | | } |
| | | 1273 | | |
| | | 1274 | | #endregion |
| | | 1275 | | |
| | | 1276 | | #region 内部辅助 |
| | | 1277 | | |
| | | 1278 | | /// <summary> |
| | | 1279 | | /// 通过全局索引获取实体引用(内部辅助) |
| | | 1280 | | /// </summary> |
| | | 1281 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1282 | | private EntityRef GetEntityRefByGlobalIndex(int globalIndex) |
| | | 1283 | | { |
| | | 1284 | | #if DEBUG |
| | | 1285 | | if (globalIndex <= 0 || globalIndex >= _count) |
| | | 1286 | | throw new ArgumentOutOfRangeException(nameof(globalIndex)); |
| | | 1287 | | #endif |
| | 5496 | 1288 | | int block = globalIndex / _blockItemCapacity; |
| | 5496 | 1289 | | int offset = globalIndex % _blockItemCapacity; |
| | 5496 | 1290 | | return _blocks[block].PackedHandles[offset]; |
| | | 1291 | | } |
| | | 1292 | | |
| | | 1293 | | private static int ResolveBlockCapacity(int requestedCapacity) |
| | | 1294 | | { |
| | 1369 | 1295 | | if (requestedCapacity > 0) |
| | | 1296 | | { |
| | 0 | 1297 | | return System.Math.Clamp(requestedCapacity, MinBlockCapacity, MaxBlockCapacity); |
| | | 1298 | | } |
| | | 1299 | | |
| | 1369 | 1300 | | int ideal = TargetBlockBytes / System.Math.Max(sizeof(T), 1); |
| | 1369 | 1301 | | ideal = System.Math.Clamp(ideal, MinBlockCapacity, MaxBlockCapacity); |
| | 1369 | 1302 | | return RoundDownToPowerOfTwo(ideal); |
| | | 1303 | | } |
| | | 1304 | | |
| | | 1305 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1306 | | private ushort GetSparseIndex(EntityRef entity) |
| | | 1307 | | { |
| | 43295 | 1308 | | uint index = (uint)entity.Index; |
| | 43295 | 1309 | | if (index >= (uint)_sparseCapacity) |
| | | 1310 | | { |
| | 0 | 1311 | | return TOMBSTONE; |
| | | 1312 | | } |
| | | 1313 | | |
| | 43295 | 1314 | | ushort sparse = _sparse[index]; |
| | 43295 | 1315 | | if (sparse == TOMBSTONE) |
| | | 1316 | | { |
| | 1283 | 1317 | | return TOMBSTONE; |
| | | 1318 | | } |
| | | 1319 | | |
| | 42012 | 1320 | | int block = sparse / _blockItemCapacity; |
| | 42012 | 1321 | | int offset = sparse % _blockItemCapacity; |
| | 42012 | 1322 | | return _blocks[block].PackedHandles[offset].Raw == entity.Raw ? sparse : TOMBSTONE; |
| | | 1323 | | } |
| | | 1324 | | |
| | | 1325 | | private void CopyDenseEntities(EntityRef* destination, int denseCount) |
| | | 1326 | | { |
| | 6 | 1327 | | if (denseCount <= 0) |
| | | 1328 | | { |
| | 0 | 1329 | | return; |
| | | 1330 | | } |
| | | 1331 | | |
| | 6 | 1332 | | int copied = 0; |
| | 24 | 1333 | | for (int blockIndex = 0; blockIndex < _blockCount && copied < denseCount; blockIndex++) |
| | | 1334 | | { |
| | 6 | 1335 | | int blockCount = GetDenseBlockCopyCount(blockIndex, denseCount - copied); |
| | 6 | 1336 | | if (blockCount <= 0) |
| | | 1337 | | { |
| | | 1338 | | continue; |
| | | 1339 | | } |
| | | 1340 | | |
| | 6 | 1341 | | int sourceOffset = blockIndex == 0 ? 1 : 0; |
| | 6 | 1342 | | Buffer.MemoryCopy( |
| | 6 | 1343 | | _blocks[blockIndex].PackedHandles + sourceOffset, |
| | 6 | 1344 | | destination + copied, |
| | 6 | 1345 | | sizeof(EntityRef) * (denseCount - copied), |
| | 6 | 1346 | | sizeof(EntityRef) * blockCount); |
| | 6 | 1347 | | copied += blockCount; |
| | | 1348 | | } |
| | 6 | 1349 | | } |
| | | 1350 | | |
| | | 1351 | | private void CopyDenseComponentBytes(byte* destination, int denseCount) |
| | | 1352 | | { |
| | 6 | 1353 | | if (denseCount <= 0) |
| | | 1354 | | { |
| | 0 | 1355 | | return; |
| | | 1356 | | } |
| | | 1357 | | |
| | 6 | 1358 | | int copied = 0; |
| | 24 | 1359 | | for (int blockIndex = 0; blockIndex < _blockCount && copied < denseCount; blockIndex++) |
| | | 1360 | | { |
| | 6 | 1361 | | int blockCount = GetDenseBlockCopyCount(blockIndex, denseCount - copied); |
| | 6 | 1362 | | if (blockCount <= 0) |
| | | 1363 | | { |
| | | 1364 | | continue; |
| | | 1365 | | } |
| | | 1366 | | |
| | 6 | 1367 | | int sourceOffset = blockIndex == 0 ? 1 : 0; |
| | 6 | 1368 | | Buffer.MemoryCopy( |
| | 6 | 1369 | | _blocks[blockIndex].PackedData + sourceOffset, |
| | 6 | 1370 | | destination + (copied * sizeof(T)), |
| | 6 | 1371 | | sizeof(T) * (denseCount - copied), |
| | 6 | 1372 | | sizeof(T) * blockCount); |
| | 6 | 1373 | | copied += blockCount; |
| | | 1374 | | } |
| | 6 | 1375 | | } |
| | | 1376 | | |
| | | 1377 | | private void RestoreDenseEntities(EntityRef* source, int denseCount) |
| | | 1378 | | { |
| | 242 | 1379 | | int copied = 0; |
| | 968 | 1380 | | for (int blockIndex = 0; blockIndex < _blockCount && copied < denseCount; blockIndex++) |
| | | 1381 | | { |
| | 242 | 1382 | | int blockCount = GetDenseBlockCopyCount(blockIndex, denseCount - copied); |
| | 242 | 1383 | | if (blockCount <= 0) |
| | | 1384 | | { |
| | | 1385 | | continue; |
| | | 1386 | | } |
| | | 1387 | | |
| | 242 | 1388 | | int destinationOffset = blockIndex == 0 ? 1 : 0; |
| | 242 | 1389 | | Buffer.MemoryCopy( |
| | 242 | 1390 | | source + copied, |
| | 242 | 1391 | | _blocks[blockIndex].PackedHandles + destinationOffset, |
| | 242 | 1392 | | sizeof(EntityRef) * blockCount, |
| | 242 | 1393 | | sizeof(EntityRef) * blockCount); |
| | 242 | 1394 | | copied += blockCount; |
| | | 1395 | | } |
| | 242 | 1396 | | } |
| | | 1397 | | |
| | | 1398 | | private void RestoreDenseComponentBytes(byte* source, int denseCount) |
| | | 1399 | | { |
| | 242 | 1400 | | int copied = 0; |
| | 968 | 1401 | | for (int blockIndex = 0; blockIndex < _blockCount && copied < denseCount; blockIndex++) |
| | | 1402 | | { |
| | 242 | 1403 | | int blockCount = GetDenseBlockCopyCount(blockIndex, denseCount - copied); |
| | 242 | 1404 | | if (blockCount <= 0) |
| | | 1405 | | { |
| | | 1406 | | continue; |
| | | 1407 | | } |
| | | 1408 | | |
| | 242 | 1409 | | int destinationOffset = blockIndex == 0 ? 1 : 0; |
| | 242 | 1410 | | Buffer.MemoryCopy( |
| | 242 | 1411 | | source + (copied * sizeof(T)), |
| | 242 | 1412 | | _blocks[blockIndex].PackedData + destinationOffset, |
| | 242 | 1413 | | sizeof(T) * blockCount, |
| | 242 | 1414 | | sizeof(T) * blockCount); |
| | 242 | 1415 | | copied += blockCount; |
| | | 1416 | | } |
| | 242 | 1417 | | } |
| | | 1418 | | |
| | | 1419 | | private int GetDenseBlockCopyCount(int blockIndex, int remainingCount) |
| | | 1420 | | { |
| | 6880 | 1421 | | if (remainingCount <= 0) |
| | | 1422 | | { |
| | 0 | 1423 | | return 0; |
| | | 1424 | | } |
| | | 1425 | | |
| | 6880 | 1426 | | int blockCapacity = blockIndex == 0 ? _blockItemCapacity - 1 : _blockItemCapacity; |
| | 6880 | 1427 | | return System.Math.Min(blockCapacity, remainingCount); |
| | | 1428 | | } |
| | | 1429 | | |
| | | 1430 | | private void CopyDenseEntitiesFrom(Storage<T>* source, int denseCount) |
| | | 1431 | | { |
| | 2111 | 1432 | | int copied = 0; |
| | 8444 | 1433 | | for (int blockIndex = 0; blockIndex < _blockCount && copied < denseCount; blockIndex++) |
| | | 1434 | | { |
| | 2111 | 1435 | | int blockCount = GetDenseBlockCopyCount(blockIndex, denseCount - copied); |
| | 2111 | 1436 | | if (blockCount <= 0) |
| | | 1437 | | { |
| | | 1438 | | continue; |
| | | 1439 | | } |
| | | 1440 | | |
| | 2111 | 1441 | | int offset = blockIndex == 0 ? 1 : 0; |
| | 2111 | 1442 | | Buffer.MemoryCopy( |
| | 2111 | 1443 | | source->_blocks[blockIndex].PackedHandles + offset, |
| | 2111 | 1444 | | _blocks[blockIndex].PackedHandles + offset, |
| | 2111 | 1445 | | sizeof(EntityRef) * blockCount, |
| | 2111 | 1446 | | sizeof(EntityRef) * blockCount); |
| | 2111 | 1447 | | copied += blockCount; |
| | | 1448 | | } |
| | 2111 | 1449 | | } |
| | | 1450 | | |
| | | 1451 | | private void CopyDenseComponentBytesFrom(Storage<T>* source, int denseCount) |
| | | 1452 | | { |
| | 2111 | 1453 | | int copied = 0; |
| | 8444 | 1454 | | for (int blockIndex = 0; blockIndex < _blockCount && copied < denseCount; blockIndex++) |
| | | 1455 | | { |
| | 2111 | 1456 | | int blockCount = GetDenseBlockCopyCount(blockIndex, denseCount - copied); |
| | 2111 | 1457 | | if (blockCount <= 0) |
| | | 1458 | | { |
| | | 1459 | | continue; |
| | | 1460 | | } |
| | | 1461 | | |
| | 2111 | 1462 | | int offset = blockIndex == 0 ? 1 : 0; |
| | 2111 | 1463 | | Buffer.MemoryCopy( |
| | 2111 | 1464 | | source->_blocks[blockIndex].PackedData + offset, |
| | 2111 | 1465 | | _blocks[blockIndex].PackedData + offset, |
| | 2111 | 1466 | | sizeof(T) * blockCount, |
| | 2111 | 1467 | | sizeof(T) * blockCount); |
| | 2111 | 1468 | | copied += blockCount; |
| | | 1469 | | } |
| | 2111 | 1470 | | } |
| | | 1471 | | |
| | | 1472 | | private void ClearSparseAndStates() |
| | | 1473 | | { |
| | 2417 | 1474 | | Unsafe.InitBlockUnaligned(_sparse, 0, checked((uint)(sizeof(ushort) * _sparseCapacity))); |
| | 2417 | 1475 | | if (_entryStates != null) |
| | | 1476 | | { |
| | 1 | 1477 | | Unsafe.InitBlockUnaligned(_entryStates, 0, checked((uint)(_sparseCapacity + 1))); |
| | | 1478 | | } |
| | | 1479 | | |
| | 2417 | 1480 | | if (_pendingQueueIndices != null) |
| | | 1481 | | { |
| | 20 | 1482 | | for (int i = 0; i <= _sparseCapacity; i++) |
| | | 1483 | | { |
| | 9 | 1484 | | _pendingQueueIndices[i] = PendingQueueIndexNone; |
| | | 1485 | | } |
| | | 1486 | | } |
| | 2417 | 1487 | | } |
| | | 1488 | | |
| | | 1489 | | private void RestoreDenseSnapshot(EntityRef* entityPtr, byte* dataPtr, int denseCount) |
| | | 1490 | | { |
| | 242 | 1491 | | ClearSparseAndStates(); |
| | 242 | 1492 | | _count = denseCount + 1; |
| | 242 | 1493 | | _pendingRemoval = 0; |
| | 242 | 1494 | | _singletonSparse = 0; |
| | | 1495 | | |
| | 242 | 1496 | | EnsureEntityCapacity(_count); |
| | | 1497 | | |
| | 242 | 1498 | | if (denseCount == 0) |
| | | 1499 | | { |
| | 0 | 1500 | | return; |
| | | 1501 | | } |
| | | 1502 | | |
| | 242 | 1503 | | RestoreDenseEntities(entityPtr, denseCount); |
| | 242 | 1504 | | RestoreDenseComponentBytes(dataPtr, denseCount); |
| | | 1505 | | |
| | 1476 | 1506 | | for (int i = 0; i < denseCount; i++) |
| | | 1507 | | { |
| | 496 | 1508 | | EntityRef entity = entityPtr[i]; |
| | 496 | 1509 | | int globalIndex = i + 1; |
| | 496 | 1510 | | _sparse[entity.Index] = (ushort)globalIndex; |
| | 496 | 1511 | | SetEntryStateByIndex(globalIndex, EntryStateActive); |
| | | 1512 | | |
| | 496 | 1513 | | if (IsSingleton) |
| | | 1514 | | { |
| | 28 | 1515 | | _singletonSparse = (ushort)globalIndex; |
| | | 1516 | | } |
| | | 1517 | | } |
| | 242 | 1518 | | } |
| | | 1519 | | |
| | | 1520 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1521 | | private byte GetEntryStateByIndex(int globalIndex) |
| | | 1522 | | { |
| | 9849 | 1523 | | return _entryStates != null ? _entryStates[globalIndex] : EntryStateActive; |
| | | 1524 | | } |
| | | 1525 | | |
| | | 1526 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1527 | | private void SetEntryStateByIndex(int globalIndex, byte state) |
| | | 1528 | | { |
| | 31134 | 1529 | | if (_entryStates != null) |
| | | 1530 | | { |
| | 37 | 1531 | | _entryStates[globalIndex] = state; |
| | | 1532 | | } |
| | 31134 | 1533 | | } |
| | | 1534 | | |
| | | 1535 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1536 | | private int GetPendingQueueIndexByIndex(int globalIndex) |
| | | 1537 | | { |
| | 5743 | 1538 | | return _pendingQueueIndices != null && _pendingQueueIndices[globalIndex] != PendingQueueIndexNone |
| | 5743 | 1539 | | ? _pendingQueueIndices[globalIndex] |
| | 5743 | 1540 | | : PendingQueueIndexNone; |
| | | 1541 | | } |
| | | 1542 | | |
| | | 1543 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1544 | | private void SetPendingQueueIndexByIndex(int globalIndex, int queueIndex) |
| | | 1545 | | { |
| | 30638 | 1546 | | if (_pendingQueueIndices != null) |
| | | 1547 | | { |
| | 36 | 1548 | | _pendingQueueIndices[globalIndex] = queueIndex >= 0 ? checked((ushort)queueIndex) : PendingQueueIndexNon |
| | | 1549 | | } |
| | 30638 | 1550 | | } |
| | | 1551 | | |
| | | 1552 | | private static int RoundDownToPowerOfTwo(int value) |
| | | 1553 | | { |
| | 1369 | 1554 | | if (value <= 1) |
| | | 1555 | | { |
| | 0 | 1556 | | return 1; |
| | | 1557 | | } |
| | | 1558 | | |
| | 1369 | 1559 | | return 1 << (BitOperations.Log2((uint)value)); |
| | | 1560 | | } |
| | | 1561 | | |
| | | 1562 | | private void EnsureBlockSpace() |
| | | 1563 | | { |
| | 314 | 1564 | | int requiredBlock = (_count / _blockItemCapacity) + 1; |
| | | 1565 | | |
| | | 1566 | | // 扩展 Block 列表 |
| | 314 | 1567 | | if (requiredBlock > _blockCapacity) |
| | | 1568 | | { |
| | 3 | 1569 | | int newCapacity = _blockCapacity * 2; |
| | 3 | 1570 | | while (newCapacity < requiredBlock) |
| | 0 | 1571 | | newCapacity *= 2; |
| | | 1572 | | |
| | 3 | 1573 | | var newBlocks = (Block*)_allocator->Alloc(sizeof(Block) * newCapacity); |
| | | 1574 | | |
| | | 1575 | | // 复制旧数据 |
| | 3 | 1576 | | Buffer.MemoryCopy(_blocks, newBlocks, |
| | 3 | 1577 | | sizeof(Block) * newCapacity, sizeof(Block) * _blockCapacity); |
| | | 1578 | | |
| | | 1579 | | // 初始化新 Block |
| | 30 | 1580 | | for (int i = _blockCapacity; i < newCapacity; i++) |
| | | 1581 | | { |
| | 12 | 1582 | | newBlocks[i].PackedHandles = null; |
| | 12 | 1583 | | newBlocks[i].PackedData = null; |
| | | 1584 | | } |
| | | 1585 | | |
| | 3 | 1586 | | _blocks = newBlocks; |
| | 3 | 1587 | | _blockCapacity = newCapacity; |
| | | 1588 | | } |
| | | 1589 | | |
| | | 1590 | | // 分配新 Block |
| | 628 | 1591 | | while (_blockCount < requiredBlock) |
| | | 1592 | | { |
| | 314 | 1593 | | int blockIndex = _blockCount++; |
| | 314 | 1594 | | _blocks[blockIndex].PackedHandles = (EntityRef*)_allocator->Alloc(sizeof(EntityRef) * _blockItemCapacity |
| | 314 | 1595 | | _blocks[blockIndex].PackedData = (T*)_allocator->Alloc(sizeof(T) * _blockItemCapacity); |
| | | 1596 | | |
| | | 1597 | | // 初始化第一个元素(索引0保留为无效) |
| | 314 | 1598 | | if (blockIndex == 0) |
| | | 1599 | | { |
| | 290 | 1600 | | _blocks[0].PackedHandles[0] = EntityRef.None; |
| | 290 | 1601 | | _blocks[0].PackedData[0] = default; |
| | | 1602 | | } |
| | | 1603 | | } |
| | 314 | 1604 | | } |
| | | 1605 | | |
| | | 1606 | | private const byte EntryStateEmpty = 0; |
| | | 1607 | | private const byte EntryStateActive = 1; |
| | | 1608 | | private const byte EntryStatePendingRemoval = 2; |
| | | 1609 | | private const ushort PendingQueueIndexNone = ushort.MaxValue; |
| | | 1610 | | |
| | | 1611 | | #endregion |
| | | 1612 | | } |
| | | 1613 | | } |