Search in sources :

Example 1 with Component

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

the class ComponentSerializerTest method testComponentTypeIdUsedWhenLookupTableEnabled.

@Test
public void testComponentTypeIdUsedWhenLookupTableEnabled() throws Exception {
    componentSerializer.setIdMapping(ImmutableMap.<Class<? extends Component>, Integer>builder().put(StringComponent.class, 1).build());
    Component stringComponent = new StringComponent("Test");
    EntityData.Component compData = componentSerializer.serialize(stringComponent);
    assertEquals(1, compData.getTypeIndex());
    assertFalse(compData.hasType());
}
Also used : StringComponent(org.terasology.unittest.stubs.StringComponent) EntityData(org.terasology.protobuf.EntityData) Component(org.terasology.gestalt.entitysystem.component.Component) GetterSetterComponent(org.terasology.unittest.stubs.GetterSetterComponent) IntegerComponent(org.terasology.unittest.stubs.IntegerComponent) StringComponent(org.terasology.unittest.stubs.StringComponent) Test(org.junit.jupiter.api.Test)

Example 2 with Component

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

the class ComponentSerializerTest method testComponentTypeIdDeserializes.

@Test
public void testComponentTypeIdDeserializes() throws Exception {
    componentSerializer.setIdMapping(ImmutableMap.<Class<? extends Component>, Integer>builder().put(StringComponent.class, 1).build());
    EntityData.Component compData = EntityData.Component.newBuilder().setTypeIndex(1).addField(EntityData.NameValue.newBuilder().setName("value").setValue(EntityData.Value.newBuilder().addString("item"))).build();
    Component comp = componentSerializer.deserialize(compData);
    assertTrue(comp instanceof StringComponent);
    assertEquals("item", ((StringComponent) comp).value);
}
Also used : StringComponent(org.terasology.unittest.stubs.StringComponent) EntityData(org.terasology.protobuf.EntityData) Component(org.terasology.gestalt.entitysystem.component.Component) GetterSetterComponent(org.terasology.unittest.stubs.GetterSetterComponent) IntegerComponent(org.terasology.unittest.stubs.IntegerComponent) StringComponent(org.terasology.unittest.stubs.StringComponent) Test(org.junit.jupiter.api.Test)

Example 3 with Component

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

the class ConditionAction method condition.

protected boolean condition(Actor actor) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
    boolean passing = true;
    if (componentAbsent != null && actor.hasComponent(componentLibrary.resolve(componentAbsent).getType())) {
        passing = false;
    }
    if (componentPresent != null) {
        Component component = actor.getComponent(componentLibrary.resolve(componentPresent).getType());
        if (component == null) {
            passing = false;
        } else {
            // Check values
            if (values != null) {
                for (String value : values) {
                    String[] tokens = value.split(" ");
                    Object fieldValue = component.getClass().getDeclaredField(tokens[1]).get(component);
                    String secondValue;
                    switch(tokens[0]) {
                        // Read second value from the definition
                        case "V":
                            secondValue = tokens[3];
                            break;
                        // Read second value from a field of the component
                        case "F":
                            secondValue = component.getClass().getDeclaredField(tokens[3]).get(component).toString();
                            break;
                        // No second value needed.
                        case "N":
                            secondValue = "";
                            break;
                        default:
                            logger.error("Unsupported guard value type: {}", tokens[0]);
                            secondValue = "";
                    }
                    // Can't use a switch for this :(
                    if (fieldValue instanceof Boolean) {
                        switch(tokens[2]) {
                            case "=":
                            case "==":
                                passing = (Boolean) fieldValue == Boolean.parseBoolean(secondValue);
                                break;
                            case "!":
                            case "!=":
                                passing = (Boolean) fieldValue != Boolean.parseBoolean(secondValue);
                                break;
                            default:
                                logger.error("Unsupported operation for boolean values: {}", tokens[2]);
                        }
                    } else if (fieldValue instanceof Number) {
                        switch(tokens[2]) {
                            case "=":
                            case "==":
                                passing = (Double) fieldValue == Double.parseDouble(secondValue);
                                break;
                            case "!":
                            case "!=":
                                passing = (Double) fieldValue == Double.parseDouble(secondValue);
                                break;
                            case "<=":
                                passing = ((Number) fieldValue).doubleValue() <= Double.parseDouble(secondValue);
                                break;
                            case ">=":
                                passing = ((Number) fieldValue).doubleValue() >= Double.parseDouble(secondValue);
                                break;
                            case ">":
                                passing = ((Number) fieldValue).doubleValue() > Double.parseDouble(secondValue);
                                break;
                            case "<":
                                passing = ((Number) fieldValue).doubleValue() < Double.parseDouble(secondValue);
                                break;
                            default:
                                logger.error("Unsupported operation for numeric values: {}", tokens[2]);
                        }
                    } else if (fieldValue instanceof String) {
                        switch(tokens[2]) {
                            case "=":
                            case "==":
                                passing = fieldValue.equals(secondValue);
                                break;
                            case "!":
                            case "!=":
                                passing = !fieldValue.equals(secondValue);
                                break;
                            default:
                                logger.error("Unsupported operation for strings: {}", tokens[2]);
                        }
                    } else {
                        if (fieldValue == null) {
                            if (!tokens[2].equals("null")) {
                                // If a more complex check is requested and the field is null, fail
                                passing = false;
                            }
                        } else {
                            switch(tokens[2]) {
                                // Null check
                                case "exists":
                                    if (fieldValue instanceof EntityRef && fieldValue == EntityRef.NULL) {
                                        passing = false;
                                    }
                                    break;
                                // Collection checks
                                case "empty":
                                    if (fieldValue instanceof Collection) {
                                        passing = ((Collection<?>) fieldValue).isEmpty();
                                    }
                                    break;
                                case "nonEmpty":
                                    if (fieldValue instanceof Collection) {
                                        passing = !((Collection<?>) fieldValue).isEmpty();
                                    }
                                    break;
                                default:
                                    logger.error("Unknown field type or operation: {} {}", fieldValue.getClass(), tokens[2]);
                            }
                        }
                    }
                }
            }
        }
    }
    return passing;
}
Also used : Collection(java.util.Collection) Component(org.terasology.gestalt.entitysystem.component.Component) EntityRef(org.terasology.engine.entitySystem.entity.EntityRef)

Example 4 with Component

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

the class NetworkEntitySerializer method deserializeOnto.

public void deserializeOnto(MutableComponentContainer entity, EntityData.PackedEntity entityData, FieldSerializeCheck<Component> fieldCheck) {
    int fieldPos = 0;
    for (int componentIndex = 0; componentIndex < entityData.getComponentIdCount(); ++componentIndex) {
        Integer componentId = entityData.getComponentId(componentIndex);
        Class<? extends Component> componentClass = idTable.inverse().get(componentId);
        ComponentMetadata<?> metadata = componentLibrary.getMetadata(componentClass);
        if (metadata == null) {
            logger.warn("Skipping unknown component {}", componentId);
            fieldPos += UnsignedBytes.toInt(entityData.getComponentFieldCounts().byteAt(componentIndex));
            continue;
        }
        if (!componentSerializeCheck.serialize(metadata)) {
            fieldPos += UnsignedBytes.toInt(entityData.getComponentFieldCounts().byteAt(componentIndex));
            continue;
        }
        Component component = entity.getComponent(metadata.getType());
        boolean createdNewComponent = false;
        if (component == null) {
            createdNewComponent = true;
            component = metadata.newInstance();
        }
        Serializer serializer = typeHandlerLibrary.getSerializerFor(metadata);
        for (int fieldIndex = 0; fieldIndex < UnsignedBytes.toInt(entityData.getComponentFieldCounts().byteAt(componentIndex)); ++fieldIndex) {
            byte fieldId = entityData.getFieldIds().byteAt(fieldPos);
            ReplicatedFieldMetadata fieldMetadata = metadata.getField(fieldId);
            if (fieldMetadata != null && fieldCheck.shouldDeserialize(metadata, fieldMetadata)) {
                logger.trace("Deserializing field {} of component {} as value {}", fieldMetadata, metadata, entityData.getFieldValue(fieldPos));
                serializer.deserializeOnto(component, fieldMetadata, new ProtobufPersistedData(entityData.getFieldValue(fieldPos)));
            }
            fieldPos++;
        }
        if (createdNewComponent) {
            entity.addComponent(component);
        } else {
            entity.saveComponent(component);
        }
    }
    for (int componentId : entityData.getRemovedComponentList()) {
        Class<? extends Component> componentClass = idTable.inverse().get(componentId);
        ComponentMetadata<?> metadata = componentLibrary.getMetadata(componentClass);
        if (componentSerializeCheck.serialize(metadata)) {
            entity.removeComponent(metadata.getType());
        }
    }
}
Also used : ProtobufPersistedData(org.terasology.engine.persistence.typeHandling.protobuf.ProtobufPersistedData) ReplicatedFieldMetadata(org.terasology.engine.entitySystem.metadata.ReplicatedFieldMetadata) Component(org.terasology.gestalt.entitysystem.component.Component) Serializer(org.terasology.persistence.typeHandling.Serializer) ProtobufPersistedDataSerializer(org.terasology.engine.persistence.typeHandling.protobuf.ProtobufPersistedDataSerializer)

Example 5 with Component

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

the class NetworkEntitySerializer method serialize.

public EntityData.PackedEntity serialize(EntityRef entityRef, Set<Class<? extends Component>> added, Set<Class<? extends Component>> changed, Set<Class<? extends Component>> removed, FieldSerializeCheck<Component> fieldCheck) {
    EntityData.PackedEntity.Builder entity = EntityData.PackedEntity.newBuilder();
    ByteString.Output fieldIds = ByteString.newOutput();
    ByteString.Output componentFieldCounts = ByteString.newOutput();
    for (Class<? extends Component> componentType : added) {
        Component component = entityRef.getComponent(componentType);
        if (component == null) {
            logger.error("Non-existent component marked as added: {}", componentType);
        }
        serializeComponentFull(entityRef.getComponent(componentType), false, fieldCheck, entity, fieldIds, componentFieldCounts, true);
    }
    for (Class<? extends Component> componentType : changed) {
        Component comp = entityRef.getComponent(componentType);
        if (comp != null) {
            serializeComponentFull(comp, true, fieldCheck, entity, fieldIds, componentFieldCounts, false);
        } else {
            logger.error("Non-existent component marked as changed: {}", componentType);
        }
    }
    for (Class<? extends Component> componentType : removed) {
        entity.addRemovedComponent(idTable.get(componentType));
    }
    entity.setFieldIds(fieldIds.toByteString());
    entity.setComponentFieldCounts(componentFieldCounts.toByteString());
    if (entity.getFieldIds().isEmpty() && entity.getRemovedComponentCount() == 0) {
        return null;
    } else {
        return entity.build();
    }
}
Also used : ByteString(com.google.protobuf.ByteString) Component(org.terasology.gestalt.entitysystem.component.Component)

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