private void doDamage(
     EntityRef entity,
     int damageAmount,
     Prefab damageType,
     EntityRef instigator,
     EntityRef directCause) {
   HealthComponent health = entity.getComponent(HealthComponent.class);
   CharacterMovementComponent characterMovementComponent =
       entity.getComponent(CharacterMovementComponent.class);
   boolean ghost = false;
   if (characterMovementComponent != null) {
     ghost = (characterMovementComponent.mode == MovementMode.GHOSTING);
   }
   if ((health != null) && !ghost) {
     int damagedAmount = health.currentHealth - Math.max(health.currentHealth - damageAmount, 0);
     health.currentHealth -= damagedAmount;
     health.nextRegenTick =
         time.getGameTimeInMs() + TeraMath.floorToInt(health.waitBeforeRegen * 1000);
     entity.saveComponent(health);
     entity.send(new OnDamagedEvent(damageAmount, damagedAmount, damageType, instigator));
     if (health.currentHealth == 0 && health.destroyEntityOnNoHealth) {
       entity.send(new DestroyEvent(instigator, directCause, damageType));
     }
   }
 }
  private void handlePressurePlateEvents() {
    Set<Vector3i> toRemoveSignal = Sets.newHashSet(activatedPressurePlates);

    Iterable<EntityRef> players =
        entityManager.getEntitiesWith(CharacterComponent.class, LocationComponent.class);
    for (EntityRef player : players) {
      Vector3f playerLocation = player.getComponent(LocationComponent.class).getWorldPosition();
      Vector3i locationBeneathPlayer =
          new Vector3i(playerLocation.x + 0.5f, playerLocation.y - 0.5f, playerLocation.z + 0.5f);
      Block blockBeneathPlayer = worldProvider.getBlock(locationBeneathPlayer);
      if (blockBeneathPlayer == signalPressurePlate) {
        EntityRef entityBeneathPlayer = blockEntityRegistry.getBlockEntityAt(locationBeneathPlayer);
        SignalProducerComponent signalProducer =
            entityBeneathPlayer.getComponent(SignalProducerComponent.class);
        if (signalProducer != null) {
          if (signalProducer.signalStrength == 0) {
            startProducingSignal(entityBeneathPlayer, -1);
            activatedPressurePlates.add(locationBeneathPlayer);
          } else {
            toRemoveSignal.remove(locationBeneathPlayer);
          }
        }
      }
    }

    for (Vector3i pressurePlateLocation : toRemoveSignal) {
      EntityRef pressurePlate = blockEntityRegistry.getBlockEntityAt(pressurePlateLocation);
      SignalProducerComponent signalProducer =
          pressurePlate.getComponent(SignalProducerComponent.class);
      if (signalProducer != null) {
        stopProducingSignal(pressurePlate);
        activatedPressurePlates.remove(pressurePlateLocation);
      }
    }
  }
 @ReceiveEvent(components = {SignalConsumerStatusComponent.class})
 public void consumerModified(OnChangedComponent event, EntityRef entity) {
   if (entity.hasComponent(BlockComponent.class)) {
     SignalConsumerStatusComponent consumerStatusComponent =
         entity.getComponent(SignalConsumerStatusComponent.class);
     Vector3i blockLocation =
         new Vector3i(entity.getComponent(BlockComponent.class).getPosition());
     Block block = worldProvider.getBlock(blockLocation);
     BlockFamily blockFamily = block.getBlockFamily();
     if (block == lampTurnedOff && consumerStatusComponent.hasSignal) {
       logger.debug("Lamp turning on");
       worldProvider.setBlock(blockLocation, lampTurnedOn);
     } else if (block == lampTurnedOn && !consumerStatusComponent.hasSignal) {
       logger.debug("Lamp turning off");
       worldProvider.setBlock(blockLocation, lampTurnedOff);
     } else if (blockFamily == signalOrGate
         || blockFamily == signalAndGate
         || blockFamily == signalXorGate) {
       logger.debug("Signal changed for gate");
       signalChangedForNormalGate(entity, consumerStatusComponent);
     } else if (blockFamily == signalNandGate) {
       signalChangedForNotGate(entity, consumerStatusComponent);
     } else if (blockFamily == signalOnDelayGate) {
       signalChangedForDelayOnGate(entity, consumerStatusComponent);
     } else if (blockFamily == signalOffDelayGate) {
       signalChangedForDelayOffGate(entity, consumerStatusComponent);
     }
   }
 }
  public void setToInterpolateState(
      EntityRef entity, CharacterStateEvent a, CharacterStateEvent b, long time) {
    float t = (float) (time - a.getTime()) / (b.getTime() - a.getTime());
    Vector3f newPos = BaseVector3f.lerp(a.getPosition(), b.getPosition(), t);
    Quat4f newRot = BaseQuat4f.interpolate(a.getRotation(), b.getRotation(), t);
    LocationComponent location = entity.getComponent(LocationComponent.class);
    location.setWorldPosition(newPos);
    location.setWorldRotation(newRot);
    entity.saveComponent(location);

    CharacterMovementComponent movementComponent =
        entity.getComponent(CharacterMovementComponent.class);
    movementComponent.mode = a.getMode();
    movementComponent.setVelocity(a.getVelocity());
    movementComponent.grounded = a.isGrounded();
    if (b.getFootstepDelta() < a.getFootstepDelta()) {
      movementComponent.footstepDelta =
          t * (1 + b.getFootstepDelta() - a.getFootstepDelta()) + a.getFootstepDelta();
      if (movementComponent.footstepDelta > 1) {
        movementComponent.footstepDelta -= 1;
      }
    } else {
      movementComponent.footstepDelta =
          t * (b.getFootstepDelta() - a.getFootstepDelta()) + a.getFootstepDelta();
    }
    entity.saveComponent(movementComponent);

    extrapolateCharacterComponent(entity, b);
    setPhysicsLocation(entity, newPos);
  }
  /**
   * Transforms a block entity with the change of block type. This is driven from the delta between
   * the old and new block type prefabs, but takes into account changes made to the block entity.
   *
   * @param blockEntity The entity to update
   * @param oldType The previous type of the block
   * @param type The new type of the block
   */
  private void updateBlockEntityComponents(
      EntityRef blockEntity,
      Block oldType,
      Block type,
      Set<Class<? extends Component>> retainComponents) {
    BlockComponent blockComponent = blockEntity.getComponent(BlockComponent.class);

    Optional<Prefab> oldPrefab = oldType.getPrefab();
    EntityBuilder oldEntityBuilder = entityManager.newBuilder(oldPrefab.orElse(null));
    oldEntityBuilder.addComponent(
        new BlockComponent(oldType, new Vector3i(blockComponent.getPosition())));
    BeforeEntityCreated oldEntityEvent =
        new BeforeEntityCreated(oldPrefab.orElse(null), oldEntityBuilder.iterateComponents());
    blockEntity.send(oldEntityEvent);
    for (Component comp : oldEntityEvent.getResultComponents()) {
      oldEntityBuilder.addComponent(comp);
    }

    Optional<Prefab> newPrefab = type.getPrefab();
    EntityBuilder newEntityBuilder = entityManager.newBuilder(newPrefab.orElse(null));
    newEntityBuilder.addComponent(
        new BlockComponent(type, new Vector3i(blockComponent.getPosition())));
    BeforeEntityCreated newEntityEvent =
        new BeforeEntityCreated(newPrefab.orElse(null), newEntityBuilder.iterateComponents());
    blockEntity.send(newEntityEvent);
    for (Component comp : newEntityEvent.getResultComponents()) {
      newEntityBuilder.addComponent(comp);
    }

    for (Component component : blockEntity.iterateComponents()) {
      if (!COMMON_BLOCK_COMPONENTS.contains(component.getClass())
          && !entityManager
              .getComponentLibrary()
              .getMetadata(component.getClass())
              .isRetainUnalteredOnBlockChange()
          && !newEntityBuilder.hasComponent(component.getClass())
          && !retainComponents.contains(component.getClass())) {
        blockEntity.removeComponent(component.getClass());
      }
    }

    blockComponent.setBlock(type);
    blockEntity.saveComponent(blockComponent);

    HealthComponent health = blockEntity.getComponent(HealthComponent.class);
    if (health == null && type.isDestructible()) {
      blockEntity.addComponent(
          new HealthComponent(type.getHardness(), type.getHardness() / BLOCK_REGEN_SECONDS, 1.0f));
    } else if (health != null && !type.isDestructible()) {
      blockEntity.removeComponent(HealthComponent.class);
    } else if (health != null && type.isDestructible()) {
      health.maxHealth = type.getHardness();
      health.currentHealth = Math.min(health.currentHealth, health.maxHealth);
      blockEntity.saveComponent(health);
    }

    for (Component comp : newEntityBuilder.iterateComponents()) {
      copyIntoPrefab(blockEntity, comp, retainComponents);
    }
  }
 private boolean processOutputForSetResetGate(EntityRef blockEntity) {
   SignalConsumerAdvancedStatusComponent consumerAdvancedStatusComponent =
       blockEntity.getComponent(SignalConsumerAdvancedStatusComponent.class);
   EnumSet<Side> signals = SideBitFlag.getSides(consumerAdvancedStatusComponent.sidesWithSignals);
   SignalProducerComponent producerComponent =
       blockEntity.getComponent(SignalProducerComponent.class);
   int resultSignal = producerComponent.signalStrength;
   if (signals.contains(Side.TOP) || signals.contains(Side.BOTTOM)) {
     resultSignal = 0;
   } else if (signals.size() > 0) {
     resultSignal = -1;
   }
   if (producerComponent.signalStrength != resultSignal) {
     producerComponent.signalStrength = resultSignal;
     blockEntity.saveComponent(producerComponent);
     if (resultSignal != 0) {
       if (!blockEntity.hasComponent(SignalProducerModifiedComponent.class)) {
         blockEntity.addComponent(new SignalProducerModifiedComponent());
       }
     } else if (blockEntity.hasComponent(SignalProducerModifiedComponent.class)) {
       blockEntity.removeComponent(SignalProducerModifiedComponent.class);
     }
     return true;
   }
   return false;
 }
Example #7
0
 private void updateEntity(NetData.UpdateEntityMessage updateEntity) {
   EntityRef currentEntity = networkSystem.getEntity(updateEntity.getNetId());
   if (currentEntity.exists()) {
     NetworkComponent netComp = currentEntity.getComponent(NetworkComponent.class);
     if (netComp == null) {
       logger.error(
           "Updating entity with no network component: {}, expected netId {}",
           currentEntity,
           updateEntity.getNetId());
       return;
     }
     if (netComp.getNetworkId() != updateEntity.getNetId()) {
       logger.error("Network ID wrong before update");
     }
     boolean blockEntityBefore = currentEntity.hasComponent(BlockComponent.class);
     entitySerializer.deserializeOnto(currentEntity, updateEntity.getEntity());
     BlockComponent blockComponent = currentEntity.getComponent(BlockComponent.class);
     if (blockComponent != null && !blockEntityBefore) {
       if (!blockEntityRegistry
           .getExistingBlockEntityAt(blockComponent.getPosition())
           .equals(currentEntity)) {
         logger.error("Failed to associated new block entity");
       }
     }
     if (netComp.getNetworkId() != updateEntity.getNetId()) {
       logger.error(
           "Network ID lost in update: {}, {} -> {}",
           currentEntity,
           updateEntity.getNetId(),
           netComp.getNetworkId());
     }
   } else {
     logger.warn("Received update for non-existent entity {}", updateEntity.getNetId());
   }
 }
 @ReceiveEvent(components = {BlockComponent.class, SignalProducerComponent.class})
 public void producerActivated(ActivateEvent event, EntityRef entity) {
   SignalProducerComponent producerComponent = entity.getComponent(SignalProducerComponent.class);
   Vector3i blockLocation = new Vector3i(entity.getComponent(BlockComponent.class).getPosition());
   Block blockAtLocation = worldProvider.getBlock(blockLocation);
   if (blockAtLocation == signalTransformer) {
     signalTransformerActivated(entity, producerComponent);
   } else if (blockAtLocation == signalSwitch) {
     signalSwitchActivated(entity, producerComponent);
   } else if (blockAtLocation == signalLimitedSwitch) {
     signalLimitedSwitchActivated(entity, producerComponent);
   } else if (blockAtLocation == signalButton) {
     signalButtonActivated(entity, producerComponent);
   }
 }
 private void extrapolateLocationComponent(
     EntityRef entity, CharacterStateEvent state, Vector3f newPos) {
   LocationComponent location = entity.getComponent(LocationComponent.class);
   location.setWorldPosition(newPos);
   location.setWorldRotation(state.getRotation());
   entity.saveComponent(location);
 }
Example #10
0
 @ReceiveEvent(components = ClientComponent.class)
 public void onMessage(MessageEvent event, EntityRef entity) {
   ClientComponent client = entity.getComponent(ClientComponent.class);
   if (client.local) {
     console.addMessage(event.getFormattedMessage());
   }
 }
  private EntityRef createResultItem(String itemResult) {
    String resultText = itemResult;
    int count = 1;
    int starIndex = resultText.indexOf("*");
    if (starIndex > -1) {
      count = Integer.parseInt(resultText.substring(0, starIndex));
      resultText = resultText.substring(starIndex + 1);
    }

    EntityManager entityManager = CoreRegistry.get(EntityManager.class);
    BlockManager blockManager = CoreRegistry.get(BlockManager.class);
    PrefabManager prefabManager = CoreRegistry.get(PrefabManager.class);
    Prefab prefab = prefabManager.getPrefab(resultText);

    EntityRef result;
    if (prefab != null) {
      result = entityManager.create(prefab);
      ItemComponent item = result.getComponent(ItemComponent.class);
      item.stackCount = (byte) count;
      result.saveComponent(item);
    } else {
      BlockItemFactory blockItemFactory = new BlockItemFactory(entityManager);
      BlockFamily blockFamily = blockManager.getBlockFamily(resultText);
      result = blockItemFactory.newInstance(blockFamily, count);
    }
    return result;
  }
  private void cleanUpTemporaryEntity(EntityRef entity) {
    Prefab prefab = entity.getParentPrefab();

    for (Component comp : entity.iterateComponents()) {
      if (!COMMON_BLOCK_COMPONENTS.contains(comp.getClass())
          && (prefab == null || !prefab.hasComponent(comp.getClass()))) {
        entity.removeComponent(comp.getClass());
      }
    }
    entity.removeComponent(NetworkComponent.class);

    if (prefab != null) {
      for (Component comp : prefab.iterateComponents()) {
        Component currentComp = entity.getComponent(comp.getClass());
        if (currentComp == null) {
          entity.addComponent(entityManager.getComponentLibrary().copy(comp));
        } else {
          ComponentMetadata<?> metadata =
              entityManager.getComponentLibrary().getMetadata(comp.getClass());
          boolean changed = false;
          for (FieldMetadata field : metadata.getFields()) {
            Object expected = field.getValue(comp);
            if (!Objects.equal(expected, field.getValue(currentComp))) {
              field.setValue(currentComp, expected);
              changed = true;
            }
          }
          if (changed) {
            entity.saveComponent(currentComp);
          }
        }
      }
    }
    entityManager.destroyEntityWithoutEvents(entity);
  }
  @Override
  public CharacterStateEvent step(
      CharacterStateEvent initial, CharacterMoveInputEvent input, EntityRef entity) {
    CharacterMovementComponent characterMovementComponent =
        entity.getComponent(CharacterMovementComponent.class);
    CharacterStateEvent result = new CharacterStateEvent(initial);
    result.setSequenceNumber(input.getSequenceNumber());
    if (worldProvider.isBlockRelevant(initial.getPosition())) {
      updatePosition(characterMovementComponent, result, input, entity);

      if (input.isFirstRun()) {
        checkBlockEntry(
            entity,
            new Vector3i(initial.getPosition(), 0.5f),
            new Vector3i(result.getPosition(), 0.5f),
            characterMovementComponent.height);
      }

      if (result.getMode() != MovementMode.GHOSTING && result.getMode() != MovementMode.NONE) {
        checkMode(characterMovementComponent, result, initial, entity, input.isFirstRun());
      }
    }
    result.setTime(initial.getTime() + input.getDeltaMs());
    updateRotation(characterMovementComponent, result, input);
    result.setPitch(input.getPitch());
    result.setYaw(input.getYaw());
    input.runComplete();
    return result;
  }
 @Test
 public void componentsAlteredIfBlockInSameFamilyWhenForced() {
   worldProvider.setBlock(Vector3i.zero(), blockInFamilyOne);
   EntityRef entity = worldProvider.getBlockEntityAt(Vector3i.zero());
   entity.addComponent(new IntegerComponent());
   worldProvider.setBlockForceUpdateEntity(Vector3i.zero(), blockInFamilyTwo);
   assertNull(entity.getComponent(IntegerComponent.class));
 }
 @Test
 public void componentUntouchedIfRetainRequested() {
   worldProvider.setBlock(Vector3i.zero(), blockInFamilyOne);
   EntityRef entity = worldProvider.getBlockEntityAt(Vector3i.zero());
   entity.addComponent(new IntegerComponent());
   worldProvider.setBlockRetainComponent(Vector3i.zero(), blockWithString, IntegerComponent.class);
   assertNotNull(entity.getComponent(IntegerComponent.class));
 }
  @Command(shortDescription = "Reduce the player's health by an amount", runOnServer = true)
  public String damage(@Sender EntityRef client, @CommandParam("amount") int amount) {
    ClientComponent clientComp = client.getComponent(ClientComponent.class);
    clientComp.character.send(
        new DoDamageEvent(amount, EngineDamageTypes.DIRECT.get(), clientComp.character));

    return "Inflicted damage of " + amount;
  }
 private boolean processOutputForRevertedGate(EntityRef blockEntity) {
   boolean hasSignal = blockEntity.getComponent(SignalConsumerStatusComponent.class).hasSignal;
   if (!hasSignal) {
     return startProducingSignal(blockEntity, -1);
   } else {
     return stopProducingSignal(blockEntity);
   }
 }
 @ReceiveEvent(components = {BlockComponent.class})
 public void onDeactivateBlock(BeforeDeactivateComponent event, EntityRef entity) {
   BlockComponent block = entity.getComponent(BlockComponent.class);
   Vector3i pos = new Vector3i(block.getPosition());
   if (blockEntityLookup.get(pos) == entity) {
     blockEntityLookup.remove(pos);
   }
 }
 @ReceiveEvent(components = {BlockRegionComponent.class})
 public void onBlockRegionActivated(OnActivatedComponent event, EntityRef entity) {
   BlockRegionComponent regionComp = entity.getComponent(BlockRegionComponent.class);
   blockRegions.put(entity, regionComp.region);
   for (Vector3i pos : regionComp.region) {
     blockRegionLookup.put(pos, entity);
   }
 }
 private void extrapolateCharacterMovementComponent(EntityRef entity, CharacterStateEvent state) {
   CharacterMovementComponent movementComponent =
       entity.getComponent(CharacterMovementComponent.class);
   movementComponent.mode = state.getMode();
   movementComponent.setVelocity(state.getVelocity());
   movementComponent.grounded = state.isGrounded();
   entity.saveComponent(movementComponent);
 }
 @Command(
     shortDescription = "Restores your health by an amount",
     runOnServer = true,
     requiredPermission = PermissionManager.CHEAT_PERMISSION)
 public void health(@Sender EntityRef client, @CommandParam("amount") int amount) {
   ClientComponent clientComp = client.getComponent(ClientComponent.class);
   clientComp.character.send(new DoHealEvent(amount, clientComp.character));
 }
 private void followToParent(final CharacterStateEvent state, EntityRef entity) {
   LocationComponent locationComponent = entity.getComponent(LocationComponent.class);
   if (!locationComponent.getParent().equals(EntityRef.NULL)) {
     Vector3f velocity = new Vector3f(locationComponent.getWorldPosition());
     velocity.sub(state.getPosition());
     state.getVelocity().set(velocity);
     state.getPosition().set(locationComponent.getWorldPosition());
   }
 }
 @ReceiveEvent(components = {BlockComponent.class})
 public void onActivateBlock(OnActivatedComponent event, EntityRef entity) {
   BlockComponent block = entity.getComponent(BlockComponent.class);
   EntityRef oldEntity = blockEntityLookup.put(new Vector3i(block.getPosition()), entity);
   // If this is a client, then an existing block entity may exist. Destroy it.
   if (oldEntity != null && !Objects.equal(oldEntity, entity)) {
     oldEntity.destroy();
   }
 }
Example #24
0
 /**
  * @param event An instance of the ActivateEvent event
  * @param entity An instance of EntityRef Deal with the real activation event (No predicted) and
  *     play a sound.
  */
 @ReceiveEvent(components = {PlaySoundActionComponent.class})
 public void onActivate(ActivateEvent event, EntityRef entity) {
   if (event.getInstigator().equals(localPlayer.getCharacterEntity())) {
     return; // owner has heard sound from prediction
   }
   PlaySoundActionComponent playSound = entity.getComponent(PlaySoundActionComponent.class);
   StaticSound sound = random.nextItem(playSound.sounds);
   verifyAndPlaySound(event, playSound, sound);
 }
 @Command(
     shortDescription = "Restores your health to max",
     runOnServer = true,
     requiredPermission = PermissionManager.CHEAT_PERMISSION)
 public String healthMax(@Sender EntityRef clientEntity) {
   ClientComponent clientComp = clientEntity.getComponent(ClientComponent.class);
   clientComp.character.send(new DoHealEvent(100000, clientComp.character));
   return "Health restored";
 }
 private boolean processOutputForNormalGate(EntityRef blockEntity) {
   boolean hasSignal = blockEntity.getComponent(SignalConsumerStatusComponent.class).hasSignal;
   logger.debug("Processing gate, hasSignal=" + hasSignal);
   if (hasSignal) {
     return startProducingSignal(blockEntity, -1);
   } else {
     return stopProducingSignal(blockEntity);
   }
 }
  @Test
  public void retainedComponentsNotAltered() {
    EntityRef entity = worldProvider.getBlockEntityAt(new Vector3i(0, 0, 0));
    entity.addComponent(new RetainedOnBlockChangeComponent(2));

    worldProvider.setBlock(Vector3i.zero(), blockWithRetainedComponent);

    assertEquals(2, entity.getComponent(RetainedOnBlockChangeComponent.class).value);
  }
  @Override
  public long getDuration(EntityRef instigator, EntityRef workstation, EntityRef processEntity) {
    SpecificInputSlotComponent input = processEntity.getComponent(SpecificInputSlotComponent.class);
    HeatProcessedComponent component =
        InventoryUtils.getItemAt(workstation, input.slot)
            .getComponent(HeatProcessedComponent.class);

    return component.processingTime;
  }
  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();
    }
  }
 private boolean stopProducingSignal(EntityRef entity) {
   SignalProducerComponent producer = entity.getComponent(SignalProducerComponent.class);
   if (producer.signalStrength != 0) {
     producer.signalStrength = 0;
     entity.saveComponent(producer);
     entity.removeComponent(SignalProducerModifiedComponent.class);
     return true;
   }
   return false;
 }