< Summary

Information
Class: Lattice.ECS.Framework.CommandBuffer
Assembly: Lattice
File(s): /home/runner/work/Sideline/Sideline/godot/scripts/lattice/ECS/Framework/CommandBuffer.cs
Line coverage
69%
Covered lines: 151
Uncovered lines: 66
Coverable lines: 217
Total lines: 516
Line coverage: 69.5%
Branch coverage
44%
Covered branches: 30
Total branches: 68
Branch coverage: 44.1%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
get_IsEmpty()100%11100%
get_CreatedEntityCount()100%210%
Initialize(...)100%11100%
Initialize(...)100%11100%
Initialize(...)50%2290.9%
Dispose()100%44100%
Clear()100%11100%
CreateEntity()50%2270.58%
DestroyEntity(...)100%11100%
AddComponent(...)100%11100%
RemoveComponent(...)100%11100%
SetComponent(...)100%11100%
Playback(...)87.5%161693.93%
Serialize()0%2040%
Deserialize(...)0%156120%
EnsureSpace(...)25%12422.22%
EnsureCreatedCapacity(...)0%4260%
WriteHeader(...)100%11100%
WriteData(...)100%11100%
PlaybackAddComponent(...)100%11100%
PlaybackRemoveComponent(...)100%11100%
PlaybackSetComponent(...)100%11100%
ResolveEntity(...)75%4485.71%
ValidatePayloadSize(...)75%9876.92%
RecountCreatedEntities()0%4260%

File(s)

/home/runner/work/Sideline/Sideline/godot/scripts/lattice/ECS/Framework/CommandBuffer.cs

#LineLine coverage
 1// Copyright (c) 2026 Sideline Authors. All rights reserved.
 2// Licensed under GPL-3.0.
 3
 4using System;
 5using System.Runtime.CompilerServices;
 6using System.Runtime.InteropServices;
 7using Lattice.Core;
 8using Lattice.ECS.Core;
 9
 10namespace Lattice.ECS.Framework
 11{
 12    /// <summary>
 13    /// 命令类型
 14    /// </summary>
 15    public enum CommandType : byte
 16    {
 17        CreateEntity,
 18        DestroyEntity,
 19        AddComponent,
 20        RemoveComponent,
 21        SetComponent,
 22    }
 23
 24    /// <summary>
 25    /// 命令头(变长命令的前4字节)
 26    /// </summary>
 27    [StructLayout(LayoutKind.Sequential, Pack = 1)]
 28    public unsafe struct CommandHeader
 29    {
 30        public CommandType Type;
 31        public ushort ComponentTypeId; // ushort.MaxValue = 无组件
 32        public ushort PayloadSize;
 33    }
 34
 35    /// <summary>
 36    /// 命令缓冲 - 预测回滚模型的核心组件
 37    ///
 38    /// 设计原理:
 39    /// 1. 所有修改 ECS 状态的操作都通过命令缓冲
 40    /// 2. 命令在帧结束时批量执行(Playback)
 41    /// 3. 支持命令的序列化(用于网络同步)
 42    /// 4. 支持命令的撤销(用于回滚)
 43    /// </summary>
 44    public unsafe struct CommandBuffer
 45    {
 46        // 命令数据缓冲区
 47        private byte* _buffer;
 48        private int _capacity;
 49        private int _writePosition;
 50
 51        // 实体创建追踪(用于映射临时索引)
 52        private EntityRef* _createdEntities;
 53        private int _createdCount;
 54        private int _createdCapacity;
 55
 56        // 分配器
 57        private Allocator* _allocator;
 58        private bool _ownsAllocator;
 59
 60        /// <summary>是否为空</summary>
 77061        public bool IsEmpty => _writePosition == 0;
 62
 63        /// <summary>命令数量</summary>
 064        public int CreatedEntityCount => _createdCount;
 65
 66        /// <summary>
 67        /// 初始化命令缓冲
 68        /// </summary>
 69        public void Initialize(int capacity = 4096)
 70        {
 25171            _allocator = Allocator.Create();
 25172            Initialize(_allocator, capacity);
 25173            _ownsAllocator = true;
 25174        }
 75
 76        /// <summary>
 77        /// 初始化命令缓冲
 78        /// </summary>
 79        public void Initialize(Frame frame, int capacity = 4096)
 80        {
 2381            ArgumentNullException.ThrowIfNull(frame);
 2382            Initialize(frame.GetAllocatorPointer(), capacity);
 2383        }
 84
 85        /// <summary>
 86        /// 初始化命令缓冲
 87        /// </summary>
 88        public void Initialize(Allocator* allocator, int capacity = 4096)
 89        {
 27490            if (allocator == null)
 91            {
 092                throw new ArgumentNullException(nameof(allocator));
 93            }
 94
 27495            _allocator = allocator;
 27496            _capacity = capacity;
 27497            _writePosition = 0;
 27498            _createdCount = 0;
 27499            _createdCapacity = 64;
 274100            _ownsAllocator = false;
 101
 274102            _buffer = (byte*)allocator->Alloc(capacity);
 274103            _createdEntities = (EntityRef*)allocator->Alloc(sizeof(EntityRef) * _createdCapacity);
 274104        }
 105
 106        /// <summary>
 107        /// 释放命令缓冲
 108        /// </summary>
 109        public void Dispose()
 110        {
 298111            _buffer = null;
 298112            _createdEntities = null;
 298113            _writePosition = 0;
 298114            _createdCount = 0;
 115
 298116            if (_ownsAllocator && _allocator != null)
 117            {
 251118                Allocator.Destroy(_allocator);
 119            }
 120
 298121            _allocator = null;
 298122            _ownsAllocator = false;
 298123        }
 124
 125        /// <summary>
 126        /// 清空缓冲
 127        /// </summary>
 128        public void Clear()
 129        {
 1107130            _writePosition = 0;
 1107131            _createdCount = 0;
 1107132        }
 133
 134        #region 命令写入
 135
 136        /// <summary>
 137        /// 创建实体命令
 138        /// </summary>
 139        public EntityRef CreateEntity()
 140        {
 204141            EnsureSpace(sizeof(CommandHeader));
 142
 204143            var header = new CommandHeader
 204144            {
 204145                Type = CommandType.CreateEntity,
 204146                ComponentTypeId = ushort.MaxValue,
 204147                PayloadSize = 0
 204148            };
 149
 204150            WriteHeader(&header);
 151
 152            // 记录临时实体引用(实际索引在 Playback 时确定)
 204153            var tempRef = new EntityRef(-(_createdCount + 1), 0);  // 负索引表示临时
 154
 155            // 扩展创建列表
 204156            if (_createdCount >= _createdCapacity)
 157            {
 0158                _createdCapacity *= 2;
 0159                var newArray = (EntityRef*)_allocator->Alloc(sizeof(EntityRef) * _createdCapacity);
 0160                Buffer.MemoryCopy(_createdEntities, newArray,
 0161                    sizeof(EntityRef) * _createdCapacity, sizeof(EntityRef) * _createdCount);
 0162                _createdEntities = newArray;
 163            }
 164
 204165            _createdEntities[_createdCount++] = tempRef;
 204166            return tempRef;
 167        }
 168
 169        /// <summary>
 170        /// 销毁实体命令
 171        /// </summary>
 172        public void DestroyEntity(EntityRef entity)
 173        {
 167174            int payloadSize = sizeof(EntityRef);
 167175            EnsureSpace(sizeof(CommandHeader) + payloadSize);
 176
 167177            var header = new CommandHeader
 167178            {
 167179                Type = CommandType.DestroyEntity,
 167180                ComponentTypeId = ushort.MaxValue,
 167181                PayloadSize = checked((ushort)payloadSize)
 167182            };
 183
 167184            WriteHeader(&header);
 167185            WriteData(&entity, payloadSize);
 167186        }
 187
 188        /// <summary>
 189        /// 添加组件命令(泛型版本,需要编译时知道类型)
 190        /// </summary>
 191        public void AddComponent<T>(EntityRef entity, T component) where T : unmanaged, IComponent
 192        {
 955193            int componentSize = sizeof(T);
 955194            int payloadSize = sizeof(EntityRef) + componentSize;
 955195            EnsureSpace(sizeof(CommandHeader) + payloadSize);
 196
 955197            var header = new CommandHeader
 955198            {
 955199                Type = CommandType.AddComponent,
 955200                ComponentTypeId = checked((ushort)ComponentTypeId<T>.Id),
 955201                PayloadSize = checked((ushort)payloadSize)
 955202            };
 203
 955204            WriteHeader(&header);
 955205            WriteData(&entity, sizeof(EntityRef));
 955206            WriteData(&component, componentSize);
 955207        }
 208
 209        /// <summary>
 210        /// 移除组件命令
 211        /// </summary>
 212        public void RemoveComponent<T>(EntityRef entity) where T : unmanaged, IComponent
 213        {
 3214            int payloadSize = sizeof(EntityRef);
 3215            EnsureSpace(sizeof(CommandHeader) + payloadSize);
 216
 3217            var header = new CommandHeader
 3218            {
 3219                Type = CommandType.RemoveComponent,
 3220                ComponentTypeId = checked((ushort)ComponentTypeId<T>.Id),
 3221                PayloadSize = checked((ushort)payloadSize)
 3222            };
 223
 3224            WriteHeader(&header);
 3225            WriteData(&entity, payloadSize);
 3226        }
 227
 228        /// <summary>
 229        /// 设置组件命令(替换现有组件)
 230        /// </summary>
 231        public void SetComponent<T>(EntityRef entity, T component) where T : unmanaged, IComponent
 232        {
 3233            int componentSize = sizeof(T);
 3234            int payloadSize = sizeof(EntityRef) + componentSize;
 3235            EnsureSpace(sizeof(CommandHeader) + payloadSize);
 236
 3237            var header = new CommandHeader
 3238            {
 3239                Type = CommandType.SetComponent,
 3240                ComponentTypeId = checked((ushort)ComponentTypeId<T>.Id),
 3241                PayloadSize = checked((ushort)payloadSize)
 3242            };
 243
 3244            WriteHeader(&header);
 3245            WriteData(&entity, sizeof(EntityRef));
 3246            WriteData(&component, componentSize);
 3247        }
 248
 249        #endregion
 250
 251        #region 命令执行
 252
 253        /// <summary>
 254        /// 执行所有命令(在帧开始时调用)
 255        /// </summary>
 256        public void Playback(Frame frame)
 257        {
 161258            if (IsEmpty) return;
 259
 121260            byte* ptr = _buffer;
 121261            byte* end = _buffer + _writePosition;
 121262            int createdIndex = 0;
 263
 1453264            while (ptr < end)
 265            {
 1332266                if (end - ptr < sizeof(CommandHeader))
 267                {
 0268                    throw new InvalidOperationException("Command buffer ended before a full header could be read.");
 269                }
 270
 1332271                var header = *(CommandHeader*)ptr;
 1332272                ptr += sizeof(CommandHeader);
 1332273                byte* payload = ptr;
 1332274                if (payload + header.PayloadSize > end)
 275                {
 0276                    throw new InvalidOperationException($"Command payload exceeds buffer bounds. Type={header.Type}, Pay
 277                }
 278
 1332279                ValidatePayloadSize(header);
 1332280                ptr += header.PayloadSize;
 281
 1332282                switch (header.Type)
 283                {
 284                    case CommandType.CreateEntity:
 285                        {
 204286                            var entity = frame.CreateEntity();
 204287                            if (createdIndex < _createdCount)
 288                            {
 204289                                _createdEntities[createdIndex++] = entity;
 290                            }
 204291                            break;
 292                        }
 293
 294                    case CommandType.DestroyEntity:
 295                        {
 167296                            EntityRef entity = ResolveEntity(payload);
 167297                            frame.DestroyEntity(entity);
 167298                            break;
 299                        }
 300
 301                    case CommandType.AddComponent:
 302                        {
 955303                            EntityRef entity = ResolveEntity(payload);
 955304                            PlaybackAddComponent(frame, entity, header.ComponentTypeId, payload + sizeof(EntityRef));
 955305                            break;
 306                        }
 307
 308                    case CommandType.RemoveComponent:
 309                        {
 3310                            EntityRef entity = ResolveEntity(payload);
 3311                            PlaybackRemoveComponent(frame, entity, header.ComponentTypeId);
 3312                            break;
 313                        }
 314
 315                    case CommandType.SetComponent:
 316                        {
 3317                            EntityRef entity = ResolveEntity(payload);
 3318                            PlaybackSetComponent(frame, entity, header.ComponentTypeId, payload + sizeof(EntityRef));
 319                            break;
 320                        }
 321                }
 322            }
 323
 121324            frame.CommitDeferredRemovals();
 121325            Clear();
 121326        }
 327
 328        #endregion
 329
 330        #region 序列化(网络同步)
 331
 332        /// <summary>
 333        /// 序列化命令缓冲到字节数组(用于网络同步)
 334        /// </summary>
 335        public byte[] Serialize()
 336        {
 0337            var result = new byte[_writePosition + sizeof(int)];
 0338            fixed (byte* ptr = result)
 339            {
 0340                *(int*)ptr = _writePosition;
 0341                Buffer.MemoryCopy(_buffer, ptr + sizeof(int), _writePosition, _writePosition);
 342            }
 0343            return result;
 344        }
 345
 346        /// <summary>
 347        /// 从字节数组反序列化
 348        /// </summary>
 349        public void Deserialize(byte[] data)
 350        {
 0351            if (data == null)
 352            {
 0353                throw new ArgumentNullException(nameof(data));
 354            }
 355
 0356            if (data.Length < sizeof(int))
 357            {
 0358                throw new InvalidOperationException("Serialized command buffer is too short.");
 359            }
 360
 0361            fixed (byte* ptr = data)
 362            {
 0363                int size = *(int*)ptr;
 0364                if (size < 0 || size > data.Length - sizeof(int))
 365                {
 0366                    throw new InvalidOperationException($"Serialized command buffer size is invalid: {size}");
 367                }
 368
 0369                EnsureSpace(size);
 0370                Buffer.MemoryCopy(ptr + sizeof(int), _buffer, size, size);
 0371                _writePosition = size;
 0372                RecountCreatedEntities();
 373            }
 0374        }
 375
 376        #endregion
 377
 378        #region 内部辅助
 379
 380        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 381        private void EnsureSpace(int size)
 382        {
 1332383            if (_writePosition + size > _capacity)
 384            {
 385                // 扩展缓冲区
 0386                int newCapacity = _capacity * 2;
 0387                while (newCapacity < _writePosition + size)
 0388                    newCapacity *= 2;
 389
 0390                var newBuffer = (byte*)_allocator->Alloc(newCapacity);
 0391                Buffer.MemoryCopy(_buffer, newBuffer, _capacity, _writePosition);
 0392                _buffer = newBuffer;
 0393                _capacity = newCapacity;
 394            }
 1332395        }
 396
 397        private void EnsureCreatedCapacity(int requiredCapacity)
 398        {
 0399            if (requiredCapacity <= _createdCapacity)
 400            {
 0401                return;
 402            }
 403
 0404            int newCapacity = _createdCapacity;
 0405            while (newCapacity < requiredCapacity)
 406            {
 0407                newCapacity *= 2;
 408            }
 409
 0410            var newArray = (EntityRef*)_allocator->Alloc(sizeof(EntityRef) * newCapacity);
 0411            if (_createdCount > 0)
 412            {
 0413                Buffer.MemoryCopy(
 0414                    _createdEntities,
 0415                    newArray,
 0416                    sizeof(EntityRef) * newCapacity,
 0417                    sizeof(EntityRef) * _createdCount);
 418            }
 419
 0420            _createdEntities = newArray;
 0421            _createdCapacity = newCapacity;
 0422        }
 423
 424        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 425        private void WriteHeader(CommandHeader* header)
 426        {
 1332427            *(CommandHeader*)(_buffer + _writePosition) = *header;
 1332428            _writePosition += sizeof(CommandHeader);
 1332429        }
 430
 431        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 432        private void WriteData(void* data, int size)
 433        {
 2086434            Buffer.MemoryCopy(data, _buffer + _writePosition, size, size);
 2086435            _writePosition += size;
 2086436        }
 437
 438        private void PlaybackAddComponent(Frame frame, EntityRef entity, ushort typeId, byte* ptr)
 439        {
 955440            ComponentCommandRegistry.PlaybackAdd(frame, entity, typeId, ptr);
 955441        }
 442
 443        private void PlaybackRemoveComponent(Frame frame, EntityRef entity, ushort typeId)
 444        {
 3445            ComponentCommandRegistry.PlaybackRemove(frame, entity, typeId);
 3446        }
 447
 448        private void PlaybackSetComponent(Frame frame, EntityRef entity, ushort typeId, byte* ptr)
 449        {
 3450            ComponentCommandRegistry.PlaybackSet(frame, entity, typeId, ptr);
 3451        }
 452
 453        private EntityRef ResolveEntity(byte* payload)
 454        {
 1128455            EntityRef entity = *(EntityRef*)payload;
 1128456            if (entity.Index >= 0)
 457            {
 172458                return entity;
 459            }
 460
 956461            int createdOrdinal = -entity.Index - 1;
 956462            if ((uint)createdOrdinal >= (uint)_createdCount)
 463            {
 0464                throw new InvalidOperationException($"未找到临时实体映射:{entity}。");
 465            }
 466
 956467            return _createdEntities[createdOrdinal];
 468        }
 469
 470        private static void ValidatePayloadSize(in CommandHeader header)
 471        {
 1332472            int expectedSize = header.Type switch
 1332473            {
 204474                CommandType.CreateEntity => 0,
 167475                CommandType.DestroyEntity => sizeof(EntityRef),
 3476                CommandType.RemoveComponent => sizeof(EntityRef),
 955477                CommandType.AddComponent => sizeof(EntityRef) + ComponentCommandRegistry.GetComponentSize(header.Compone
 3478                CommandType.SetComponent => sizeof(EntityRef) + ComponentCommandRegistry.GetComponentSize(header.Compone
 0479                _ => throw new InvalidOperationException($"Unknown command type: {header.Type}")
 1332480            };
 481
 1332482            if (header.PayloadSize != expectedSize)
 483            {
 0484                throw new InvalidOperationException(
 0485                    $"Command payload size mismatch. Type={header.Type}, ComponentTypeId={header.ComponentTypeId}, Expec
 486            }
 1332487        }
 488
 489        private void RecountCreatedEntities()
 490        {
 0491            _createdCount = 0;
 492
 0493            byte* ptr = _buffer;
 0494            byte* end = _buffer + _writePosition;
 0495            while (ptr < end)
 496            {
 0497                CommandHeader header = *(CommandHeader*)ptr;
 0498                ptr += sizeof(CommandHeader);
 499
 0500                if (header.Type == CommandType.CreateEntity)
 501                {
 0502                    EnsureCreatedCapacity(_createdCount + 1);
 0503                    _createdEntities[_createdCount++] = new EntityRef(-_createdCount, 0);
 504                }
 505
 0506                ptr += header.PayloadSize;
 0507                if (ptr > end)
 508                {
 0509                    throw new InvalidOperationException("Serialized command buffer is malformed.");
 510                }
 511            }
 0512        }
 513
 514        #endregion
 515    }
 516}