< Summary

Information
Class: Lattice.ECS.Core.ComponentRegistry
Assembly: Lattice
File(s): /home/runner/work/Sideline/Sideline/godot/scripts/lattice/ECS/Core/ComponentTypeId.cs
Line coverage
81%
Covered lines: 160
Uncovered lines: 37
Coverable lines: 197
Total lines: 915
Line coverage: 81.2%
Branch coverage
68%
Covered branches: 73
Total branches: 106
Branch coverage: 68.8%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

File(s)

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

#LineLine coverage
 1// Copyright (c) 2026 Sideline Authors. All rights reserved.
 2// Licensed under GPL-3.0.
 3
 4using System;
 5using System.Buffers.Binary;
 6using System.Collections.Generic;
 7using Lattice.Core;
 8using Lattice.ECS.Serialization;
 9
 10namespace Lattice.ECS.Core
 11{
 12    /// <summary>
 13    /// 组件类型元数据。
 14    /// </summary>
 15    public readonly struct ComponentTypeInfo
 16    {
 17        public ComponentTypeInfo(
 18            Type type,
 19            int id,
 20            int size,
 21            ComponentFlags flags,
 22            StorageFlags storageFlags,
 23            ComponentCallbacks callbacks)
 24        {
 25            Type = type;
 26            Id = id;
 27            Size = size;
 28            Flags = flags;
 29            StorageFlags = storageFlags;
 30            Callbacks = callbacks;
 31        }
 32
 33        public Type Type { get; }
 34
 35        public string Name => Type.Name;
 36
 37        public int Id { get; }
 38
 39        public int Size { get; }
 40
 41        public ComponentFlags Flags { get; }
 42
 43        public StorageFlags StorageFlags { get; }
 44
 45        public ComponentCallbacks Callbacks { get; }
 46
 47        public int SerializationVersion => Callbacks.SerializationVersion;
 48    }
 49
 50    /// <summary>
 51    /// 组件类型注册中心,负责维护运行期组件元数据。
 52    /// </summary>
 53    public static unsafe class ComponentRegistry
 54    {
 155        private static readonly object SyncRoot = new();
 156        private static readonly Type?[] Types = new Type[Frame.MaxComponentTypes];
 157        private static readonly int[] Sizes = new int[Frame.MaxComponentTypes];
 158        private static readonly ComponentFlags[] Flags = new ComponentFlags[Frame.MaxComponentTypes];
 159        private static readonly StorageFlags[] StorageFlagsByType = new StorageFlags[Frame.MaxComponentTypes];
 160        private static readonly ComponentCallbacks[] Callbacks = new ComponentCallbacks[Frame.MaxComponentTypes];
 161        private static readonly ComponentFrameRemoveDelegate?[] RemoveInvokers = new ComponentFrameRemoveDelegate[Frame.
 162        private static readonly ComponentCommandApplyDelegate?[] AddAppliers = new ComponentCommandApplyDelegate[Frame.M
 163        private static readonly ComponentCommandApplyDelegate?[] SetAppliers = new ComponentCommandApplyDelegate[Frame.M
 164        private static readonly ComponentDeferredCommitDelegate?[] DeferredCommitters = new ComponentDeferredCommitDeleg
 165        private static readonly ComponentSnapshotCaptureDelegate?[] SnapshotCapturers = new ComponentSnapshotCaptureDele
 166        private static readonly ComponentSnapshotRestoreDelegate?[] SnapshotRestorers = new ComponentSnapshotRestoreDele
 167        private static readonly ComponentPendingRemovalDelegate?[] PendingRemovalMarkers = new ComponentPendingRemovalDe
 168        private static readonly ComponentPendingQueueIndexSetterDelegate?[] PendingQueueIndexSetters = new ComponentPend
 169        private static readonly ComponentStorageCopyDelegate?[] StorageCopiers = new ComponentStorageCopyDelegate[Frame.
 170        private static readonly ComponentStorageResetDelegate?[] StorageResetters = new ComponentStorageResetDelegate[Fr
 171        private static readonly ComponentPackedStatePresenceDelegate?[] PackedStatePresenceCheckers = new ComponentPacke
 172        private static readonly ComponentPackedStateWriteDelegate?[] PackedStateWriters = new ComponentPackedStateWriteD
 173        private static readonly ComponentPackedStateRestoreDelegate?[] PackedStateRestorers = new ComponentPackedStateRe
 174        private static readonly int[] FixedPackedPayloadSizes = CreateFixedPackedPayloadSizes();
 175        private static readonly Dictionary<Type, int> ReverseLookup = new();
 176        private static readonly Dictionary<string, int> ReverseNameLookup = new(StringComparer.Ordinal);
 77
 178        private static int _nextId = 1;
 79
 4932880        public static int Count => _nextId - 1;
 81
 82        public static Builder CreateBuilder()
 83        {
 584            return new Builder();
 85        }
 86
 87        public static bool IsRegistered<T>() where T : unmanaged, IComponent
 88        {
 089            return ComponentTypeId<T>.IsRegistered;
 90        }
 91
 92        public static int Register<T>() where T : unmanaged, IComponent
 93        {
 5494            return Register<T>(ComponentFlags.None, ComponentCallbacks.Empty, StorageFlags.None);
 95        }
 96
 97        public static int Register<T>(ComponentFlags flags, ComponentCallbacks callbacks, StorageFlags storageFlags = St
 98            where T : unmanaged, IComponent
 99        {
 81100            lock (SyncRoot)
 101            {
 81102                StorageFlags resolvedStorageFlags = MapStorageFlags(flags, storageFlags);
 103
 81104                if (ReverseLookup.TryGetValue(typeof(T), out int existingId))
 105                {
 32106                    ValidateCompatibleRegistration(existingId, flags, resolvedStorageFlags, callbacks);
 32107                    return existingId;
 108                }
 109
 49110                if (_nextId >= Frame.MaxComponentTypes)
 111                {
 0112                    throw new InvalidOperationException($"Reached max components declared: {Frame.MaxComponentTypes - 1}
 113                }
 114
 49115                int id = _nextId++;
 116
 49117                Types[id] = typeof(T);
 49118                Sizes[id] = sizeof(T);
 49119                Flags[id] = flags;
 49120                StorageFlagsByType[id] = resolvedStorageFlags;
 49121                Callbacks[id] = callbacks;
 49122                FixedPackedPayloadSizes[id] = callbacks.Serialize != null
 49123                    ? ComponentRuntimeDispatch<T>.MeasurePackedPayloadSize(callbacks.Serialize)
 49124                    : sizeof(T);
 49125                RemoveInvokers[id] = ComponentRuntimeDispatch<T>.RemoveFromFrame;
 49126                AddAppliers[id] = ComponentRuntimeDispatch<T>.AddToFrame;
 49127                SetAppliers[id] = ComponentRuntimeDispatch<T>.SetInFrame;
 49128                DeferredCommitters[id] = ComponentRuntimeDispatch<T>.CommitDeferred;
 49129                SnapshotCapturers[id] = ComponentRuntimeDispatch<T>.CaptureSnapshot;
 49130                SnapshotRestorers[id] = ComponentRuntimeDispatch<T>.RestoreSnapshot;
 49131                PendingRemovalMarkers[id] = ComponentRuntimeDispatch<T>.MarkPendingRemoval;
 49132                PendingQueueIndexSetters[id] = ComponentRuntimeDispatch<T>.SetPendingQueueIndex;
 49133                StorageCopiers[id] = ComponentRuntimeDispatch<T>.CopyStorage;
 49134                StorageResetters[id] = ComponentRuntimeDispatch<T>.ResetStorage;
 49135                PackedStatePresenceCheckers[id] = ComponentRuntimeDispatch<T>.HasPackedState;
 49136                PackedStateWriters[id] = ComponentRuntimeDispatch<T>.WritePackedState;
 49137                PackedStateRestorers[id] = ComponentRuntimeDispatch<T>.RestorePackedState;
 138
 49139                ReverseLookup.Add(typeof(T), id);
 49140                ReverseNameLookup[typeof(T).Name] = id;
 141
 49142                ComponentTypeId<T>.SetRegistration(id, sizeof(T), flags, resolvedStorageFlags, callbacks);
 49143                ComponentCommandRegistry.Register<T>(id);
 49144                return id;
 145            }
 81146        }
 147
 148        /// <summary>
 149        /// 确保组件类型已注册。
 150        /// </summary>
 151        public static void EnsureRegistered<T>() where T : unmanaged, IComponent
 152        {
 5153            if (ComponentTypeId<T>.IsRegistered)
 154            {
 0155                return;
 156            }
 157
 5158            Register<T>();
 5159        }
 160
 161        public static int GetComponentIndex(Type type)
 162        {
 1163            if (ReverseLookup.TryGetValue(type, out int id))
 164            {
 1165                return id;
 166            }
 167
 0168            throw new InvalidOperationException($"Type not registered: {type.FullName}");
 169        }
 170
 171        public static int GetComponentIndex(string shortTypeName)
 172        {
 1173            if (ReverseNameLookup.TryGetValue(shortTypeName, out int id))
 174            {
 1175                return id;
 176            }
 177
 0178            throw new InvalidOperationException($"Type not registered: {shortTypeName}");
 179        }
 180
 181        public static ComponentTypeInfo GetTypeInfo(int id)
 182        {
 1183            EnsureValidTypeId(id);
 1184            return new ComponentTypeInfo(Types[id]!, id, Sizes[id], Flags[id], StorageFlagsByType[id], Callbacks[id]);
 185        }
 186
 187        internal static ComponentSchemaManifest CreateSchemaManifest(ReadOnlySpan<int> serializedTypeIds, ComponentSeria
 188        {
 321189            ulong hash = 0xCBF29CE484222325;
 190
 321191            AppendInt64(ref hash, ComponentSchemaManifest.CurrentVersion);
 321192            AppendInt64(ref hash, (int)mode);
 321193            AppendInt64(ref hash, serializedTypeIds.Length);
 194
 3290195            for (int i = 0; i < serializedTypeIds.Length; i++)
 196            {
 1324197                int typeId = serializedTypeIds[i];
 1324198                EnsureValidTypeId(typeId);
 199
 1324200                Type type = Types[typeId]!;
 1324201                ComponentCallbacks callbacks = Callbacks[typeId];
 202
 1324203                AppendInt64(ref hash, typeId);
 1324204                AppendString(ref hash, type.FullName ?? type.Name);
 1324205                AppendInt64(ref hash, Sizes[typeId]);
 1324206                AppendInt64(ref hash, (int)Flags[typeId]);
 1324207                AppendInt64(ref hash, (int)StorageFlagsByType[typeId]);
 1324208                AppendInt64(ref hash, callbacks.Serialize != null ? 1 : 0);
 1324209                AppendInt64(ref hash, callbacks.SerializationVersion);
 1324210                AppendInt64(ref hash, FixedPackedPayloadSizes[typeId]);
 211            }
 212
 321213            return new ComponentSchemaManifest(mode, hash, serializedTypeIds.Length);
 214        }
 215
 216        public static Type GetComponentType(int id)
 217        {
 0218            EnsureValidTypeId(id);
 0219            return Types[id]!;
 220        }
 221
 222        public static int GetComponentSize(int id)
 223        {
 0224            EnsureValidTypeId(id);
 0225            return Sizes[id];
 226        }
 227
 228        public static ComponentFlags GetComponentFlags(int id)
 229        {
 0230            EnsureValidTypeId(id);
 0231            return Flags[id];
 232        }
 233
 234        public static ComponentCallbacks GetComponentCallbacks(int id)
 235        {
 0236            EnsureValidTypeId(id);
 0237            return Callbacks[id];
 238        }
 239
 240        public static bool CanSerializeComponent(int id, ComponentSerializationMode mode = ComponentSerializationMode.De
 241        {
 2190242            EnsureValidTypeId(id);
 2190243            ComponentFlags flags = Flags[id];
 244
 2190245            if ((flags & ComponentFlags.DontSerialize) != 0)
 246            {
 0247                return false;
 248            }
 249
 2190250            if (mode == ComponentSerializationMode.Prediction &&
 2190251                (flags & ComponentFlags.ExcludeFromPrediction) != 0)
 252            {
 1253                return false;
 254            }
 255
 2189256            if (mode == ComponentSerializationMode.Checkpoint &&
 2189257                (flags & ComponentFlags.ExcludeFromCheckpoints) != 0)
 258            {
 1259                return false;
 260            }
 261
 2188262            return true;
 263        }
 264
 265        public static unsafe bool SerializeComponent(
 266            int id,
 267            void* component,
 268            IFrameSerializer serializer,
 269            ComponentSerializationMode mode = ComponentSerializationMode.Default)
 270        {
 13271            EnsureValidTypeId(id);
 272
 13273            if (!CanSerializeComponent(id, mode))
 274            {
 1275                return false;
 276            }
 277
 12278            ComponentCallbacks callbacks = Callbacks[id];
 12279            if (callbacks.Serialize != null)
 280            {
 12281                callbacks.Serialize(component, serializer);
 12282                return true;
 283            }
 284
 0285            serializer.Serialize(component, Sizes[id]);
 0286            return true;
 287        }
 288
 289        public static StorageFlags GetComponentStorageFlags(int id)
 290        {
 0291            EnsureValidTypeId(id);
 0292            return StorageFlagsByType[id];
 293        }
 294
 295        internal static ComponentFrameRemoveDelegate GetRemoveInvoker(int id)
 296        {
 797297            EnsureValidTypeId(id);
 797298            return RemoveInvokers[id] ?? throw new InvalidOperationException($"Remove invoker missing for component type
 299        }
 300
 301        internal static ComponentCommandApplyDelegate GetAddApplier(int id)
 302        {
 0303            EnsureValidTypeId(id);
 0304            return AddAppliers[id] ?? throw new InvalidOperationException($"Add applier missing for component type ID {i
 305        }
 306
 307        internal static ComponentCommandApplyDelegate GetSetApplier(int id)
 308        {
 0309            EnsureValidTypeId(id);
 0310            return SetAppliers[id] ?? throw new InvalidOperationException($"Set applier missing for component type ID {i
 311        }
 312
 313        internal static ComponentDeferredCommitDelegate GetDeferredCommitter(int id)
 314        {
 1315            EnsureValidTypeId(id);
 1316            return DeferredCommitters[id] ?? throw new InvalidOperationException($"Deferred committer missing for compon
 317        }
 318
 319        internal static ComponentSnapshotCaptureDelegate GetSnapshotCapturer(int id)
 320        {
 7321            EnsureValidTypeId(id);
 7322            return SnapshotCapturers[id] ?? throw new InvalidOperationException($"Snapshot capturer missing for componen
 323        }
 324
 325        internal static ComponentSnapshotRestoreDelegate GetSnapshotRestorer(int id)
 326        {
 4327            EnsureValidTypeId(id);
 4328            return SnapshotRestorers[id] ?? throw new InvalidOperationException($"Snapshot restorer missing for componen
 329        }
 330
 331        internal static ComponentPendingQueueIndexSetterDelegate GetPendingQueueIndexSetter(int id)
 332        {
 0333            EnsureValidTypeId(id);
 0334            return PendingQueueIndexSetters[id] ?? throw new InvalidOperationException($"Pending queue index setter miss
 335        }
 336
 337        internal static ComponentPendingRemovalDelegate GetPendingRemovalMarker(int id)
 338        {
 0339            EnsureValidTypeId(id);
 0340            return PendingRemovalMarkers[id] ?? throw new InvalidOperationException($"Pending removal marker missing for
 341        }
 342
 343        internal static ComponentStorageCopyDelegate GetStorageCopier(int id)
 344        {
 2113345            EnsureValidTypeId(id);
 2113346            return StorageCopiers[id] ?? throw new InvalidOperationException($"Storage copier missing for component type
 347        }
 348
 349        internal static ComponentStorageResetDelegate GetStorageResetter(int id)
 350        {
 62351            EnsureValidTypeId(id);
 62352            return StorageResetters[id] ?? throw new InvalidOperationException($"Storage resetter missing for component 
 353        }
 354
 355        internal static ComponentPackedStatePresenceDelegate GetPackedStatePresenceChecker(int id)
 356        {
 1085357            EnsureValidTypeId(id);
 1085358            return PackedStatePresenceCheckers[id] ?? throw new InvalidOperationException($"Packed state presence checke
 359        }
 360
 361        internal static ComponentPackedStateWriteDelegate GetPackedStateWriter(int id)
 362        {
 1085363            EnsureValidTypeId(id);
 1085364            return PackedStateWriters[id] ?? throw new InvalidOperationException($"Packed state writer missing for compo
 365        }
 366
 367        internal static ComponentPackedStateRestoreDelegate GetPackedStateRestorer(int id)
 368        {
 239369            EnsureValidTypeId(id);
 239370            return PackedStateRestorers[id] ?? throw new InvalidOperationException($"Packed state restorer missing for c
 371        }
 372
 373        internal static int GetFixedPackedPayloadSize(int id)
 374        {
 4375            EnsureValidTypeId(id);
 4376            return FixedPackedPayloadSizes[id];
 377        }
 378
 379        internal static StorageFlags GetStorageFlags(int id)
 380        {
 1731381            EnsureValidTypeId(id);
 1731382            return StorageFlagsByType[id];
 383        }
 384
 385        internal static StorageFlags MapStorageFlags(ComponentFlags componentFlags, StorageFlags storageFlags = StorageF
 386        {
 81387            StorageFlags mappedFlags = storageFlags;
 388
 81389            if ((componentFlags & ComponentFlags.Singleton) != 0)
 390            {
 9391                mappedFlags |= StorageFlags.Singleton;
 392            }
 393
 81394            return mappedFlags;
 395        }
 396
 397        private static int[] CreateFixedPackedPayloadSizes()
 398        {
 1399            int[] sizes = new int[Frame.MaxComponentTypes];
 1400            Array.Fill(sizes, -1);
 1401            return sizes;
 402        }
 403
 404        private static void EnsureValidTypeId(int id)
 405        {
 10656406            if (id <= 0 || id >= _nextId || Types[id] == null)
 407            {
 0408                throw new InvalidOperationException($"Component type ID not registered: {id}");
 409            }
 10656410        }
 411
 412        private static void ValidateCompatibleRegistration(
 413            int id,
 414            ComponentFlags flags,
 415            StorageFlags storageFlags,
 416            ComponentCallbacks callbacks)
 417        {
 32418            if (Flags[id] != flags)
 419            {
 0420                throw new InvalidOperationException(
 0421                    $"Component {Types[id]!.FullName} already registered with different flags. " +
 0422                    $"Existing={Flags[id]}, Requested={flags}");
 423            }
 424
 32425            if (StorageFlagsByType[id] != storageFlags)
 426            {
 0427                throw new InvalidOperationException(
 0428                    $"Component {Types[id]!.FullName} already registered with different storage flags. " +
 0429                    $"Existing={StorageFlagsByType[id]}, Requested={storageFlags}");
 430            }
 431
 32432            ComponentCallbacks existingCallbacks = Callbacks[id];
 32433            if (existingCallbacks.Serialize != callbacks.Serialize ||
 32434                existingCallbacks.OnAdded != callbacks.OnAdded ||
 32435                existingCallbacks.OnRemoved != callbacks.OnRemoved ||
 32436                existingCallbacks.SerializationVersion != callbacks.SerializationVersion)
 437            {
 0438                throw new InvalidOperationException(
 0439                    $"Component {Types[id]!.FullName} already registered with different callbacks.");
 440            }
 32441        }
 442
 443        private static void AppendInt64(ref ulong hash, int value)
 444        {
 11555445            Span<byte> buffer = stackalloc byte[sizeof(int)];
 11555446            BinaryPrimitives.WriteInt32LittleEndian(buffer, value);
 11555447            AppendBytes(ref hash, buffer);
 11555448        }
 449
 450        private static void AppendString(ref ulong hash, string value)
 451        {
 1324452            AppendInt64(ref hash, value.Length);
 1324453            Span<byte> buffer = stackalloc byte[sizeof(char)];
 454
 120658455            for (int i = 0; i < value.Length; i++)
 456            {
 59005457                BinaryPrimitives.WriteUInt16LittleEndian(buffer, value[i]);
 59005458                AppendBytes(ref hash, buffer);
 459            }
 1324460        }
 461
 462        private static void AppendBytes(ref ulong hash, ReadOnlySpan<byte> data)
 463        {
 464            const ulong fnvPrime = 0x00000100000001B3;
 465
 469580466            for (int i = 0; i < data.Length; i++)
 467            {
 164230468                hash ^= data[i];
 164230469                hash *= fnvPrime;
 470            }
 70560471        }
 472
 473        /// <summary>
 474        /// 增量式注册 Builder,接口形态向 FrameSync 对齐。
 475        /// </summary>
 476        public readonly struct Builder
 477        {
 478            public Builder Add<T>(
 479                ComponentCallbacks callbacks,
 480                ComponentFlags flags = ComponentFlags.None,
 481                StorageFlags storageFlags = StorageFlags.None)
 482                where T : unmanaged, IComponent
 483            {
 0484                Register<T>(flags, callbacks, storageFlags);
 0485                return this;
 486            }
 487
 488            public Builder Add<T>(
 489                ComponentSerializeDelegate? serialize = null,
 490                ComponentChangedDelegate? onAdded = null,
 491                ComponentChangedDelegate? onRemoved = null,
 492                ComponentFlags flags = ComponentFlags.None,
 493                StorageFlags storageFlags = StorageFlags.None)
 494                where T : unmanaged, IComponent
 495            {
 6496                Register<T>(flags, new ComponentCallbacks(serialize, onAdded, onRemoved), storageFlags);
 6497                return this;
 498            }
 499
 500            public void Finish()
 501            {
 5502            }
 503        }
 504    }
 505
 506    /// <summary>
 507    /// 组件类型 ID 与元数据缓存(FrameSync 风格)。
 508    /// </summary>
 509    public static unsafe class ComponentTypeId<T> where T : unmanaged, IComponent
 510    {
 511        private static int _id;
 512        private static int _size;
 513        private static ComponentFlags _flags;
 514        private static StorageFlags _storageFlags;
 515        private static ComponentCallbacks _callbacks;
 516
 517        public static int Id
 518        {
 519            get
 520            {
 521                if (_id == 0)
 522                {
 523                    ComponentRegistry.Register<T>();
 524                }
 525
 526                return _id;
 527            }
 528        }
 529
 530        public static int Size
 531        {
 532            get
 533            {
 534                if (_size == 0)
 535                {
 536                    _ = Id;
 537                }
 538
 539                return _size;
 540            }
 541        }
 542
 543        public static ComponentFlags Flags
 544        {
 545            get
 546            {
 547                if (_id == 0)
 548                {
 549                    _ = Id;
 550                }
 551
 552                return _flags;
 553            }
 554        }
 555
 556        public static StorageFlags StorageFlags
 557        {
 558            get
 559            {
 560                if (_id == 0)
 561                {
 562                    _ = Id;
 563                }
 564
 565                return _storageFlags;
 566            }
 567        }
 568
 569        public static ComponentCallbacks Callbacks
 570        {
 571            get
 572            {
 573                if (_id == 0)
 574                {
 575                    _ = Id;
 576                }
 577
 578                return _callbacks;
 579            }
 580        }
 581
 582        public static bool IsRegistered => _id != 0;
 583
 584        internal static void SetRegistration(
 585            int id,
 586            int size,
 587            ComponentFlags flags,
 588            StorageFlags storageFlags,
 589            ComponentCallbacks callbacks)
 590        {
 591            if (_id != 0 && _id != id)
 592            {
 593                throw new InvalidOperationException($"Component type already registered with ID {_id}");
 594            }
 595
 596            _id = id;
 597            _size = size;
 598            _flags = flags;
 599            _storageFlags = storageFlags;
 600            _callbacks = callbacks;
 601        }
 602    }
 603
 604    internal static unsafe class ComponentRuntimeDispatch<T> where T : unmanaged, IComponent
 605    {
 606        public static int MeasurePackedPayloadSize(ComponentSerializeDelegate serialize)
 607        {
 608            if (serialize == null)
 609            {
 610                return sizeof(T);
 611            }
 612
 613            T component = default;
 614            var sizingStream = new FrameStateBitStreamWriter(new FrameStateSizingWriter());
 615            var serializer = new FrameSerializer(sizingStream, writing: true);
 616            sizingStream.BeginPayload();
 617            serialize(&component, serializer);
 618            return sizingStream.EndPayload();
 619        }
 620
 621        public static void RemoveFromFrame(Frame frame, EntityRef entity)
 622        {
 623            frame.Remove<T>(entity);
 624        }
 625
 626        public static void AddToFrame(Frame frame, EntityRef entity, void* componentData)
 627        {
 628            frame.Add(entity, *(T*)componentData);
 629        }
 630
 631        public static void SetInFrame(Frame frame, EntityRef entity, void* componentData)
 632        {
 633            frame.Set(entity, *(T*)componentData);
 634        }
 635
 636        public static void CommitDeferred(void* storage, EntityRef entity)
 637        {
 638            var typedStorage = (Storage<T>*)storage;
 639            if (typedStorage == null)
 640            {
 641                return;
 642            }
 643
 644            typedStorage->CommitRemoval(entity);
 645        }
 646
 647        public static ComponentStorageSnapshot? CaptureSnapshot(void* storage, ComponentSerializationMode mode)
 648        {
 649            int typeId = ComponentTypeId<T>.Id;
 650            if (!ComponentRegistry.CanSerializeComponent(typeId, mode))
 651            {
 652                return null;
 653            }
 654
 655            var typedStorage = (Storage<T>*)storage;
 656            if (typedStorage == null || typedStorage->Count == 0)
 657            {
 658                return null;
 659            }
 660
 661            if (ComponentTypeId<T>.Callbacks.Serialize == null)
 662            {
 663                int rawCount = typedStorage->Count;
 664                var entities = new EntityRef[rawCount];
 665                var data = new byte[rawCount * sizeof(T)];
 666
 667                typedStorage->CopyDenseEntities(entities);
 668                typedStorage->CopyDenseComponentBytes(data);
 669
 670                return new ComponentStorageSnapshot(typeId, entities, data);
 671            }
 672
 673            int count = typedStorage->Count;
 674            var entries = new ComponentEntrySnapshot[count];
 675
 676            for (int index = 1; index <= count; index++)
 677            {
 678                EntityRef entity = typedStorage->GetEntityRefByIndex(index);
 679                T* componentData = typedStorage->GetDataPointerByIndex(index);
 680                var serializer = new FrameSerializer(new BitStream(), writing: true);
 681                ComponentRegistry.SerializeComponent(typeId, componentData, serializer, mode);
 682                entries[index - 1] = new ComponentEntrySnapshot(entity, serializer.Stream.ToArray());
 683            }
 684
 685            return new ComponentStorageSnapshot(typeId, entries);
 686        }
 687
 688        public static void RestoreSnapshot(Frame frame, ComponentStorageSnapshot snapshot, ComponentSerializationMode mo
 689        {
 690            int typeId = ComponentTypeId<T>.Id;
 691            var storage = frame.GetOrCreateStorageForSnapshotRestore<T>(typeId);
 692
 693            if (snapshot.Kind == ComponentSnapshotDataKind.RawDense)
 694            {
 695                storage->RestoreDenseSnapshot(snapshot.DenseEntities, snapshot.DenseData);
 696                return;
 697            }
 698
 699            if (snapshot.Entries.Length == 0)
 700            {
 701                return;
 702            }
 703
 704            for (int i = 0; i < snapshot.Entries.Length; i++)
 705            {
 706                ComponentEntrySnapshot entry = snapshot.Entries[i];
 707                T component = default;
 708
 709                if (entry.Payload.Length > 0)
 710                {
 711                    var serializer = new FrameSerializer(new BitStream(entry.Payload), writing: false);
 712                    ComponentRegistry.SerializeComponent(typeId, &component, serializer, mode);
 713                }
 714
 715                storage->Add(entry.Entity, component);
 716            }
 717        }
 718
 719        public static void MarkPendingRemoval(void* storage, EntityRef entity)
 720        {
 721            var typedStorage = (Storage<T>*)storage;
 722            if (typedStorage == null)
 723            {
 724                return;
 725            }
 726
 727            typedStorage->MarkForRemoval(entity);
 728        }
 729
 730        public static void SetPendingQueueIndex(void* storage, EntityRef entity, int queueIndex)
 731        {
 732            var typedStorage = (Storage<T>*)storage;
 733            if (typedStorage == null)
 734            {
 735                return;
 736            }
 737
 738            typedStorage->SetPendingQueueIndex(entity, queueIndex);
 739        }
 740
 741        public static void CopyStorage(Frame destinationFrame, void* sourceStorage)
 742        {
 743            var destination = destinationFrame.GetOrCreateStorageForSnapshotRestore<T>(ComponentTypeId<T>.Id);
 744            var source = (Storage<T>*)sourceStorage;
 745            if (source == null)
 746            {
 747                return;
 748            }
 749
 750            destination->CopyFrom(source);
 751        }
 752
 753        public static void ResetStorage(void* storage)
 754        {
 755            var typedStorage = (Storage<T>*)storage;
 756            if (typedStorage == null)
 757            {
 758                return;
 759            }
 760
 761            typedStorage->Reset();
 762        }
 763
 764        public static bool HasPackedState(void* storage, ComponentSerializationMode mode)
 765        {
 766            int typeId = ComponentTypeId<T>.Id;
 767            if (!ComponentRegistry.CanSerializeComponent(typeId, mode))
 768            {
 769                return false;
 770            }
 771
 772            var typedStorage = (Storage<T>*)storage;
 773            return typedStorage != null && typedStorage->Count > 0;
 774        }
 775
 776        public static bool WritePackedState(void* storage, FrameStateWriter writer, ComponentSerializationMode mode)
 777        {
 778            var typedStorage = (Storage<T>*)storage;
 779            if (typedStorage == null || typedStorage->Count == 0)
 780            {
 781                return false;
 782            }
 783
 784            int typeId = ComponentTypeId<T>.Id;
 785
 786            writer.WriteInt32(typeId);
 787
 788            if (ComponentTypeId<T>.Callbacks.Serialize == null)
 789            {
 790                writer.WriteByte((byte)ComponentSnapshotDataKind.RawDense);
 791
 792                int denseCount = typedStorage->Count;
 793                writer.WriteInt32(denseCount);
 794                typedStorage->WriteDenseEntities(writer);
 795
 796                int dataLength = denseCount * sizeof(T);
 797                writer.WriteInt32(dataLength);
 798                typedStorage->WriteDenseComponentBytes(writer);
 799                return true;
 800            }
 801
 802            int entryCount = typedStorage->Count;
 803            int fixedPayloadBytes = ComponentRegistry.GetFixedPackedPayloadSize(typeId);
 804            if (fixedPayloadBytes >= 0)
 805            {
 806                writer.WriteByte((byte)ComponentSnapshotDataKind.FixedSizeEntryPayloads);
 807                writer.WriteInt32(entryCount);
 808                writer.WriteInt32(fixedPayloadBytes);
 809
 810                var payloadStream = new FrameStateBitStreamWriter(writer);
 811                var serializer = new FrameSerializer(payloadStream, writing: true);
 812
 813                for (int index = 1; index <= entryCount; index++)
 814                {
 815                    EntityRef entity = typedStorage->GetEntityRefByIndex(index);
 816                    T* componentData = typedStorage->GetDataPointerByIndex(index);
 817
 818                    writer.WriteUInt64(entity.Raw);
 819                    payloadStream.BeginPayload();
 820                    ComponentRegistry.SerializeComponent(typeId, componentData, serializer, mode);
 821                    int actualPayloadBytes = payloadStream.EndPayload();
 822                    if (actualPayloadBytes != fixedPayloadBytes)
 823                    {
 824                        throw new InvalidOperationException(
 825                            $"Component {typeof(T).Name} produced variable-sized serialized payloads. " +
 826                            $"Expected={fixedPayloadBytes}, Actual={actualPayloadBytes}.");
 827                    }
 828                }
 829
 830                return true;
 831            }
 832
 833            writer.WriteByte((byte)ComponentSnapshotDataKind.EntryPayloads);
 834            writer.WriteInt32(entryCount);
 835
 836            var fallbackPayloadStream = new BitStream();
 837            var fallbackSerializer = new FrameSerializer(fallbackPayloadStream, writing: true);
 838
 839            for (int index = 1; index <= entryCount; index++)
 840            {
 841                EntityRef entity = typedStorage->GetEntityRefByIndex(index);
 842                T* componentData = typedStorage->GetDataPointerByIndex(index);
 843
 844                fallbackPayloadStream.Reset();
 845                ComponentRegistry.SerializeComponent(typeId, componentData, fallbackSerializer, mode);
 846
 847                writer.WriteUInt64(entity.Raw);
 848                ReadOnlySpan<byte> payload = fallbackPayloadStream.GetWrittenSpan();
 849                writer.WriteInt32(payload.Length);
 850                writer.WriteBytes(payload);
 851            }
 852
 853            return true;
 854        }
 855
 856        public static void RestorePackedState(Frame frame, FrameStateReader reader, ComponentSerializationMode mode)
 857        {
 858            int typeId = ComponentTypeId<T>.Id;
 859            byte kind = reader.ReadByte();
 860            var storage = frame.GetOrCreateStorageForSnapshotRestore<T>(typeId);
 861
 862            if (kind == (byte)ComponentSnapshotDataKind.RawDense)
 863            {
 864                int denseCount = reader.ReadInt32();
 865                ReadOnlySpan<byte> entityBytes = reader.ReadBytes(denseCount * sizeof(EntityRef));
 866                int dataLength = reader.ReadInt32();
 867                ReadOnlySpan<byte> componentBytes = reader.ReadBytes(dataLength);
 868                storage->RestoreDenseSnapshot(entityBytes, componentBytes);
 869                return;
 870            }
 871
 872            if (kind == (byte)ComponentSnapshotDataKind.FixedSizeEntryPayloads)
 873            {
 874                int fixedEntryCount = reader.ReadInt32();
 875                int payloadLength = reader.ReadInt32();
 876                var stream = new FrameStateBitStreamReader(reader);
 877                var serializer = new FrameSerializer(stream, writing: false);
 878
 879                for (int i = 0; i < fixedEntryCount; i++)
 880                {
 881                    EntityRef entity = EntityRef.FromRaw(reader.ReadUInt64());
 882                    T component = default;
 883
 884                    if (payloadLength > 0)
 885                    {
 886                        stream.BeginPayload(payloadLength);
 887                        ComponentRegistry.SerializeComponent(typeId, &component, serializer, mode);
 888                        stream.EndPayload();
 889                    }
 890
 891                    storage->Add(entity, component);
 892                }
 893
 894                return;
 895            }
 896
 897            int entryCount = reader.ReadInt32();
 898            for (int i = 0; i < entryCount; i++)
 899            {
 900                EntityRef entity = EntityRef.FromRaw(reader.ReadUInt64());
 901                int payloadLength = reader.ReadInt32();
 902                T component = default;
 903
 904                if (payloadLength > 0)
 905                {
 906                    var stream = reader.CreateBitStreamSlice(payloadLength);
 907                    var serializer = new FrameSerializer(stream, writing: false);
 908                    ComponentRegistry.SerializeComponent(typeId, &component, serializer, mode);
 909                }
 910
 911                storage->Add(entity, component);
 912            }
 913        }
 914    }
 915}

Methods/Properties

.cctor()
get_Count()
CreateBuilder()
IsRegistered()
Register()
Register(Lattice.ECS.Core.ComponentFlags,Lattice.ECS.Core.ComponentCallbacks,Lattice.ECS.Core.StorageFlags)
EnsureRegistered()
GetComponentIndex(System.Type)
GetComponentIndex(System.String)
GetTypeInfo(System.Int32)
CreateSchemaManifest(System.ReadOnlySpan`1<System.Int32>,Lattice.ECS.Core.ComponentSerializationMode)
GetComponentType(System.Int32)
GetComponentSize(System.Int32)
GetComponentFlags(System.Int32)
GetComponentCallbacks(System.Int32)
CanSerializeComponent(System.Int32,Lattice.ECS.Core.ComponentSerializationMode)
SerializeComponent(System.Int32,System.Void*,Lattice.ECS.Serialization.IFrameSerializer,Lattice.ECS.Core.ComponentSerializationMode)
GetComponentStorageFlags(System.Int32)
GetRemoveInvoker(System.Int32)
GetAddApplier(System.Int32)
GetSetApplier(System.Int32)
GetDeferredCommitter(System.Int32)
GetSnapshotCapturer(System.Int32)
GetSnapshotRestorer(System.Int32)
GetPendingQueueIndexSetter(System.Int32)
GetPendingRemovalMarker(System.Int32)
GetStorageCopier(System.Int32)
GetStorageResetter(System.Int32)
GetPackedStatePresenceChecker(System.Int32)
GetPackedStateWriter(System.Int32)
GetPackedStateRestorer(System.Int32)
GetFixedPackedPayloadSize(System.Int32)
GetStorageFlags(System.Int32)
MapStorageFlags(Lattice.ECS.Core.ComponentFlags,Lattice.ECS.Core.StorageFlags)
CreateFixedPackedPayloadSizes()
EnsureValidTypeId(System.Int32)
ValidateCompatibleRegistration(System.Int32,Lattice.ECS.Core.ComponentFlags,Lattice.ECS.Core.StorageFlags,Lattice.ECS.Core.ComponentCallbacks)
AppendInt64(System.UInt64&,System.Int32)
AppendString(System.UInt64&,System.String)
AppendBytes(System.UInt64&,System.ReadOnlySpan`1<System.Byte>)
Add(Lattice.ECS.Core.ComponentCallbacks,Lattice.ECS.Core.ComponentFlags,Lattice.ECS.Core.StorageFlags)
Add(Lattice.ECS.Core.ComponentSerializeDelegate,Lattice.ECS.Core.ComponentChangedDelegate,Lattice.ECS.Core.ComponentChangedDelegate,Lattice.ECS.Core.ComponentFlags,Lattice.ECS.Core.StorageFlags)
Finish()