Search in sources :

Example 46 with Component

use of org.terasology.gestalt.entitysystem.component.Component in project Terasology by MovingBlocks.

the class SaveTransaction method applyDeltaToPrivateEntityManager.

private void applyDeltaToPrivateEntityManager() {
    deltaToSave.getEntityDeltas().forEachEntry((entityId, delta) -> {
        if (entityId >= privateEntityManager.getNextId()) {
            privateEntityManager.setNextId(entityId + 1);
        }
        return true;
    });
    deltaToSave.getDestroyedEntities().forEach(entityId -> {
        if (entityId >= privateEntityManager.getNextId()) {
            privateEntityManager.setNextId(entityId + 1);
        }
        return true;
    });
    deltaToSave.getEntityDeltas().forEachEntry((entityId, delta) -> {
        if (privateEntityManager.isActiveEntity(entityId)) {
            EntityRef entity = privateEntityManager.getEntity(entityId);
            for (Component changedComponent : delta.getChangedComponents().values()) {
                entity.removeComponent(changedComponent.getClass());
                entity.addComponent(changedComponent);
            }
            delta.getRemovedComponents().forEach(entity::removeComponent);
        } else {
            privateEntityManager.createEntityWithId(entityId, delta.getChangedComponents().values());
        }
        return true;
    });
    final List<EntityRef> entitiesToDestroy = Lists.newArrayList();
    deltaToSave.getDestroyedEntities().forEach(entityId -> {
        EntityRef entityToDestroy;
        if (privateEntityManager.isActiveEntity(entityId)) {
            entityToDestroy = privateEntityManager.getEntity(entityId);
        } else {
            /*
                 * Create the entity as theere could be a component that references a {@link DelayedEntityRef}
                 * with the specified id. It is important that the {@link DelayedEntityRef} will reference
                 * a destroyed {@link EntityRef} instance. That is why a entity will be created, potentially
                 * bound to one or more {@link DelayedEntityRef}s and then destroyed.
                 *
                 */
            entityToDestroy = privateEntityManager.createEntityWithId(entityId, Collections.<Component>emptyList());
        }
        entitiesToDestroy.add(entityToDestroy);
        return true;
    });
    /*
         * Bind the delayed entities refs, before destroying the entities:
         *
         * That way delayed entity refs will reference the enttiy refs that got marked as destroyed and now new
         * unloaded ones.
         */
    deltaToSave.bindAllDelayedEntityRefsTo(privateEntityManager);
    entitiesToDestroy.forEach(EntityRef::destroy);
    deltaToSave.getDeactivatedEntities().forEach(entityId -> {
        EntityRef entityRef = privateEntityManager.getEntity(entityId);
        privateEntityManager.deactivateForStorage(entityRef);
        return true;
    });
}
Also used : Component(org.terasology.gestalt.entitysystem.component.Component) LocationComponent(org.terasology.engine.logic.location.LocationComponent) ClientComponent(org.terasology.engine.network.ClientComponent) EntityRef(org.terasology.engine.entitySystem.entity.EntityRef)

Example 47 with Component

use of org.terasology.gestalt.entitysystem.component.Component in project Terasology by MovingBlocks.

the class ReadWriteStorageManager method addGameManifestToSaveTransaction.

private void addGameManifestToSaveTransaction(SaveTransactionBuilder saveTransactionBuilder) {
    BlockManager blockManager = CoreRegistry.get(BlockManager.class);
    UniverseConfig universeConfig = config.getUniverseConfig();
    Time time = CoreRegistry.get(Time.class);
    Game game = CoreRegistry.get(Game.class);
    GameManifest gameManifest = new GameManifest(game.getName(), game.getSeed(), time.getGameTimeInMs());
    for (Module module : CoreRegistry.get(ModuleManager.class).getEnvironment()) {
        gameManifest.addModule(module.getId(), module.getVersion());
    }
    List<String> registeredBlockFamilies = Lists.newArrayList();
    for (BlockFamily family : blockManager.listRegisteredBlockFamilies()) {
        registeredBlockFamilies.add(family.getURI().toString());
    }
    gameManifest.setRegisteredBlockFamilies(registeredBlockFamilies);
    gameManifest.setBlockIdMap(blockManager.getBlockIdMap());
    List<WorldInfo> worlds = universeConfig.getWorlds();
    for (WorldInfo worldInfo : worlds) {
        gameManifest.addWorld(worldInfo);
    }
    WorldGenerator worldGenerator = CoreRegistry.get(WorldGenerator.class);
    if (worldGenerator != null) {
        WorldConfigurator worldConfigurator = worldGenerator.getConfigurator();
        Map<String, Component> params = worldConfigurator.getProperties();
        gameManifest.setModuleConfigs(worldGenerator.getUri(), params);
    }
    saveTransactionBuilder.setGameManifest(gameManifest);
}
Also used : WorldGenerator(org.terasology.engine.world.generator.WorldGenerator) WorldConfigurator(org.terasology.engine.world.generator.WorldConfigurator) Time(org.terasology.engine.core.Time) UniverseConfig(org.terasology.engine.config.UniverseConfig) ModuleManager(org.terasology.engine.core.module.ModuleManager) Game(org.terasology.engine.game.Game) GameManifest(org.terasology.engine.game.GameManifest) BlockManager(org.terasology.engine.world.block.BlockManager) WorldInfo(org.terasology.engine.world.internal.WorldInfo) BlockFamily(org.terasology.engine.world.block.family.BlockFamily) Module(org.terasology.gestalt.module.Module) Component(org.terasology.gestalt.entitysystem.component.Component) LocationComponent(org.terasology.engine.logic.location.LocationComponent) ClientComponent(org.terasology.engine.network.ClientComponent)

Example 48 with Component

use of org.terasology.gestalt.entitysystem.component.Component in project Terasology by MovingBlocks.

the class ComponentSerializer method serialize.

/**
 * Serializes the differences between two components.
 *
 * @param base  The base component to compare against.
 * @param delta The component whose differences will be serialized
 * @param check A check to use to see if each field should be serialized.
 * @return The serialized component, or null if it could not be serialized
 */
public EntityData.Component serialize(Component base, Component delta, FieldSerializeCheck<Component> check) {
    ComponentMetadata<?> componentMetadata = componentLibrary.getMetadata(base.getClass());
    if (componentMetadata == null) {
        logger.error("Unregistered component type: {}", base.getClass());
        return null;
    }
    EntityData.Component.Builder componentMessage = EntityData.Component.newBuilder();
    serializeComponentType(componentMetadata, componentMessage);
    Serializer serializer = typeHandlerLibrary.getSerializerFor(componentMetadata);
    boolean changed = false;
    for (ReplicatedFieldMetadata field : componentMetadata.getFields()) {
        if (check.shouldSerializeField(field, delta) && serializer.getHandlerFor(field) != null) {
            Object origValue = field.getValue(base);
            Object deltaValue = field.getValue(delta);
            if (!Objects.equal(origValue, deltaValue)) {
                PersistedData value = serializer.serializeValue(field, deltaValue, serializationContext);
                if (!value.isNull()) {
                    EntityData.Value dataValue = ((ProtobufPersistedData) value).getValue();
                    if (usingFieldIds) {
                        componentMessage.addField(EntityData.NameValue.newBuilder().setNameIndex(field.getId()).setValue(dataValue).build());
                    } else {
                        componentMessage.addField(EntityData.NameValue.newBuilder().setName(field.getName()).setValue(dataValue).build());
                    }
                    changed = true;
                }
            }
        }
    }
    if (changed) {
        return componentMessage.build();
    }
    return null;
}
Also used : ProtobufPersistedData(org.terasology.engine.persistence.typeHandling.protobuf.ProtobufPersistedData) EntityData(org.terasology.protobuf.EntityData) ReplicatedFieldMetadata(org.terasology.engine.entitySystem.metadata.ReplicatedFieldMetadata) PersistedData(org.terasology.persistence.typeHandling.PersistedData) ProtobufPersistedData(org.terasology.engine.persistence.typeHandling.protobuf.ProtobufPersistedData) Component(org.terasology.gestalt.entitysystem.component.Component) Serializer(org.terasology.persistence.typeHandling.Serializer) ProtobufPersistedDataSerializer(org.terasology.engine.persistence.typeHandling.protobuf.ProtobufPersistedDataSerializer)

Example 49 with Component

use of org.terasology.gestalt.entitysystem.component.Component in project Terasology by MovingBlocks.

the class EntitySerializer method deserializeOntoComponents.

/**
 * Deserializes the components from an EntityData onto a map of components
 *
 * @param entityData
 * @param componentMap
 */
private void deserializeOntoComponents(EntityData.Entity entityData, Map<Class<? extends Component>, Component> componentMap) {
    EntityInfoComponent entityInfo = (EntityInfoComponent) componentMap.get(EntityInfoComponent.class);
    if (entityInfo == null) {
        entityInfo = new EntityInfoComponent();
        componentMap.put(EntityInfoComponent.class, entityInfo);
    }
    if (entityData.hasOwner()) {
        entityInfo.owner = entityManager.getEntity(entityData.getOwner());
    }
    if (entityData.hasAlwaysRelevant()) {
        entityInfo.alwaysRelevant = entityData.getAlwaysRelevant();
    }
    switch(entityData.getScope()) {
        case GLOBAL:
            entityInfo.scope = EntityScope.GLOBAL;
            break;
        case SECTOR:
            entityInfo.scope = EntityScope.SECTOR;
            break;
        case CHUNK:
            entityInfo.scope = EntityScope.CHUNK;
            break;
    }
    for (EntityData.Component componentData : entityData.getComponentList()) {
        ComponentMetadata<? extends Component> metadata = componentSerializer.getComponentMetadata(componentData);
        if (metadata == null || !componentSerializeCheck.serialize(metadata)) {
            continue;
        }
        Component existingComponent = componentMap.get(metadata.getType());
        if (existingComponent == null) {
            Component newComponent = componentSerializer.deserialize(componentData);
            componentMap.put(metadata.getType(), newComponent);
        } else {
            componentSerializer.deserializeOnto(existingComponent, componentData, FieldSerializeCheck.NullCheck.<Component>newInstance());
        }
    }
}
Also used : EntityData(org.terasology.protobuf.EntityData) EntityInfoComponent(org.terasology.engine.entitySystem.entity.internal.EntityInfoComponent) Component(org.terasology.gestalt.entitysystem.component.Component) EntityInfoComponent(org.terasology.engine.entitySystem.entity.internal.EntityInfoComponent)

Example 50 with Component

use of org.terasology.gestalt.entitysystem.component.Component in project Terasology by MovingBlocks.

the class EntitySerializer method serializeEntityFull.

private EntityData.Entity serializeEntityFull(EntityRef entityRef, FieldSerializeCheck<Component> fieldCheck) {
    EntityData.Entity.Builder entity = EntityData.Entity.newBuilder();
    if (!ignoringEntityId) {
        entity.setId(entityRef.getId());
    }
    entity.setAlwaysRelevant(entityRef.isAlwaysRelevant());
    EntityRef owner = entityRef.getOwner();
    if (owner.exists()) {
        entity.setOwner(owner.getId());
    }
    EntityScope scope = entityRef.getScope();
    if (scope != null) {
        switch(scope) {
            case GLOBAL:
                entity.setScope(GLOBAL);
                break;
            case SECTOR:
                entity.setScope(SECTOR);
                break;
            case CHUNK:
                entity.setScope(CHUNK);
                break;
        }
    }
    for (Component component : entityRef.iterateComponents()) {
        if (!componentSerializeCheck.serialize(componentLibrary.getMetadata(component.getClass()))) {
            continue;
        }
        EntityData.Component componentData = componentSerializer.serialize(component, fieldCheck);
        if (componentData != null) {
            entity.addComponent(componentData);
        }
    }
    return entity.build();
}
Also used : EntityData(org.terasology.protobuf.EntityData) EntityInfoComponent(org.terasology.engine.entitySystem.entity.internal.EntityInfoComponent) Component(org.terasology.gestalt.entitysystem.component.Component) EntityRef(org.terasology.engine.entitySystem.entity.EntityRef) EntityScope(org.terasology.engine.entitySystem.entity.internal.EntityScope)

Aggregations

Component (org.terasology.gestalt.entitysystem.component.Component)57 EntityRef (org.terasology.engine.entitySystem.entity.EntityRef)20 Prefab (org.terasology.engine.entitySystem.prefab.Prefab)12 LocationComponent (org.terasology.engine.logic.location.LocationComponent)12 OnActivatedComponent (org.terasology.engine.entitySystem.entity.lifecycleEvents.OnActivatedComponent)11 NetworkComponent (org.terasology.engine.network.NetworkComponent)10 OnChangedComponent (org.terasology.engine.entitySystem.entity.lifecycleEvents.OnChangedComponent)9 EntityData (org.terasology.protobuf.EntityData)8 BeforeDeactivateComponent (org.terasology.engine.entitySystem.entity.lifecycleEvents.BeforeDeactivateComponent)7 OnAddedComponent (org.terasology.engine.entitySystem.entity.lifecycleEvents.OnAddedComponent)7 BlockComponent (org.terasology.engine.world.block.BlockComponent)7 EntityInfoComponent (org.terasology.engine.entitySystem.entity.internal.EntityInfoComponent)6 ReceiveEvent (org.terasology.engine.entitySystem.event.ReceiveEvent)6 EntityManager (org.terasology.engine.entitySystem.entity.EntityManager)5 ClientComponent (org.terasology.engine.network.ClientComponent)5 List (java.util.List)4 Map (java.util.Map)4 Optional (java.util.Optional)4 FieldMetadata (org.terasology.reflection.metadata.FieldMetadata)4 ByteString (com.google.protobuf.ByteString)3