addComponents method

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

Implementation

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

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

  final record = _entityIndex.remove(entityID);
  if (record == null) {
    final hash = SetHash(componentIDs);
    final archetype = _getOrCreateArchetype(hash);

    for (int i = 0; i < components.length; i++) {
      final componentID = componentIDs.elementAt(i);
      final component = components[i];

      if (_componentIndex[componentID]![hash] == null) {
        _componentIndex[componentID]![hash] = archetype.components.length;
        archetype.components.add([]);
      }
      final componentsList = archetype.components[_componentIndex[componentID]![hash]!];
      componentsList.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,
    );
  }
}