addComponents method

void addComponents(
  1. EntityID entityID,
  2. List<Component> components
)

Implementation

void addComponents(EntityID entityID, List<Component> components) {
  final componentIDs = <ComponentID>{};

  for (final component in components) {
    component.entityID = entityID;
    final id = _getOrCreateComponentID(component.runtimeType);
    componentIDs.add(id);
    _componentIndex[id] ??= {};
  }

  final record = _entityIndex.remove(entityID);

  if (record == null) {
    final hash = SetHash(componentIDs);
    final archetype = _getOrCreateArchetype(hash);

    for (final component in components) {
      final id = _componentTypes[component.runtimeType]!;
      final indexMap = _componentIndex[id]!;

      if (indexMap[hash] == null) {
        indexMap[hash] = archetype.components.length;
        archetype.components.add([]);
      }

      archetype.components[indexMap[hash]!].add(component);
    }

    _entityIndex[entityID] = Record(
      archetype: archetype,
      entityRow: archetype.components[0].length - 1,
    );
  } else {
    final oldArchetype = record.archetype;
    final hash = oldArchetype.setHash.copy()..addAll(componentIDs);
    final archetype = _getOrCreateArchetype(hash);

    _moveEntity(
      entityID,
      oldArchetype,
      record.entityRow,
      archetype,
      toAdd: components,
    );
  }
}