コード例 #1
0
 public void unjail() {
   jailed = false;
   jail = null;
   jailtime = null;
   JsonConfig conf = getPlayerConfig();
   conf.set("jailed", false);
   conf.set("jail", null);
   conf.set("jailtime", null);
   conf.save();
   save();
   if (tpspawn && getOnlinePlayer() != null) {
     if (bammerbom.ultimatecore.spongeapi.api.UC.getPlayer(getPlayer()).getSpawn(false) == null) {
       LocationUtil.teleport(
           getOnlinePlayer(),
           getOnlinePlayer().getWorld().getSpawnLocation(),
           Cause.of("unjail"),
           false,
           false);
     } else {
       LocationUtil.teleport(
           getOnlinePlayer(),
           bammerbom.ultimatecore.spongeapi.api.UC.getPlayer(getPlayer()).getSpawn(false),
           Cause.of("unjail"),
           false,
           false);
     }
   }
 }
コード例 #2
0
 @Override
 public Cause getCause() {
   if (this.explosion.exploder != null) {
     return Cause.of(this.explosion.exploder);
   } else {
     net.minecraft.block.state.IBlockState state =
         this.world.getBlockState(new BlockPos(this.explosion.getPosition()));
     return Cause.of(state.getBlock());
   }
 }
コード例 #3
0
 public static Cause generateCauseFor(DamageSource damageSource) {
   if (damageSource instanceof EntityDamageSourceIndirect) {
     net.minecraft.entity.Entity source = damageSource.getEntity();
     Optional<User> owner =
         ((IMixinEntity) source).getTrackedPlayer(NbtDataUtil.SPONGE_ENTITY_CREATOR);
     if (owner.isPresent()) {
       return Cause.of(
           NamedCause.of(DamageEntityEvent.SOURCE, damageSource),
           NamedCause.of(DamageEntityEvent.CREATOR, owner.get()));
     } else {
       return Cause.of(NamedCause.of(DamageEntityEvent.SOURCE, damageSource));
     }
   } else if (damageSource instanceof EntityDamageSource) {
     net.minecraft.entity.Entity source = damageSource.getEntity();
     Optional<User> owner =
         ((IMixinEntity) source).getTrackedPlayer(NbtDataUtil.SPONGE_ENTITY_CREATOR);
     Optional<User> notifier =
         ((IMixinEntity) source).getTrackedPlayer(NbtDataUtil.SPONGE_ENTITY_NOTIFIER);
     List<Object> causeObjects = new ArrayList<>();
     causeObjects.add(NamedCause.of(DamageEntityEvent.SOURCE, damageSource));
     if (notifier.isPresent()) {
       causeObjects.add(NamedCause.of(DamageEntityEvent.NOTIFIER, notifier.get()));
     }
     if (owner.isPresent()) {
       causeObjects.add(NamedCause.of(DamageEntityEvent.CREATOR, owner.get()));
     }
     return Cause.of(causeObjects.toArray());
   } else if (damageSource instanceof BlockDamageSource) {
     List<Object> causeObjects = new ArrayList<>();
     Location<org.spongepowered.api.world.World> location =
         ((BlockDamageSource) damageSource).getLocation();
     BlockPos blockPos = VecHelper.toBlockPos(location);
     Optional<User> owner =
         ((IMixinChunk)
                 ((net.minecraft.world.World) location.getExtent())
                     .getChunkFromBlockCoords(blockPos))
             .getBlockOwner(blockPos);
     Optional<User> notifier =
         ((IMixinChunk)
                 ((net.minecraft.world.World) location.getExtent())
                     .getChunkFromBlockCoords(blockPos))
             .getBlockNotifier(blockPos);
     causeObjects.add(NamedCause.of(DamageEntityEvent.SOURCE, damageSource));
     if (notifier.isPresent()) {
       causeObjects.add(NamedCause.of(DamageEntityEvent.NOTIFIER, notifier.get()));
     }
     if (owner.isPresent()) {
       causeObjects.add(NamedCause.of(DamageEntityEvent.CREATOR, owner.get()));
     }
     return Cause.of(causeObjects.toArray());
   } else {
     return Cause.of(NamedCause.of(DamageEntityEvent.SOURCE, damageSource));
   }
 }
コード例 #4
0
 @Inject(
     method = "dropItem",
     at =
         @At(
             value = "FIELD",
             opcode = Opcodes.GETFIELD,
             target = "Lnet/minecraft/entity/player/EntityPlayer;posY:D"),
     cancellable = true)
 private void onDropTop(
     ItemStack itemStack,
     boolean a,
     boolean b,
     CallbackInfoReturnable<EntityItem> callbackInfoReturnable) {
   final double height = this.posY - 0.3D + (double) this.getEyeHeight();
   Transform<org.spongepowered.api.world.World> transform =
       new Transform<>(this.getWorld(), new Vector3d(this.posX, height, this.posZ));
   SpawnCause cause =
       EntitySpawnCause.builder().entity(this).type(SpawnTypes.DROPPED_ITEM).build();
   ConstructEntityEvent.Pre event =
       SpongeEventFactory.createConstructEntityEventPre(
           Cause.of(NamedCause.source(cause)), EntityTypes.ITEM, transform);
   SpongeImpl.postEvent(event);
   if (event.isCancelled()) {
     callbackInfoReturnable.setReturnValue(null);
   }
 }
コード例 #5
0
 @Inject(
     method = "newExplosion",
     at = @At(value = "INVOKE", target = "Lnet/minecraft/world/Explosion;doExplosionA()V"),
     locals = LocalCapture.CAPTURE_FAILHARD,
     cancellable = true)
 public void callWorldOnExplosionEvent(
     Entity entityIn,
     double x,
     double y,
     double z,
     float strength,
     boolean isFlaming,
     boolean isSmoking,
     CallbackInfoReturnable<Explosion> cir,
     Explosion explosion) {
   final ExplosionEvent.Pre event =
       SpongeEventFactory.createExplosionEventPre(
           Sponge.getGame(),
           Cause.of(this),
           (org.spongepowered.api.world.explosion.Explosion) explosion,
           (org.spongepowered.api.world.World) this);
   if (Sponge.getGame().getEventManager().post(event)) {
     cir.setReturnValue(explosion);
   }
 }
コード例 #6
0
 @Redirect(
     method = "interact",
     at =
         @At(
             value = "INVOKE",
             target = "Ljava/util/Random;nextInt(I)I",
             ordinal = 0,
             remap = false))
 public int onTame(Random rand, int bound, EntityPlayer player) {
   int random = rand.nextInt(bound);
   if (random == 0
       && !SpongeImpl.postEvent(
           SpongeEventFactory.createTameEntityEvent(
               Cause.of(
                   NamedCause.source(player),
                   NamedCause.of(
                       TameEntityEvent.USED_ITEM,
                       ((org.spongepowered.api.item.inventory.ItemStack) this.currentItemStack)
                           .createSnapshot())),
               this))) {
     this.currentItemStack = null;
     return random;
   }
   this.currentItemStack = null;
   return 1;
 }
コード例 #7
0
ファイル: MixinWorld.java プロジェクト: phroa/SpongeCommon
 /**
  * @author gabizou - February 7th, 2016
  *     <p>This will short circuit all other patches such that we control the entities being loaded
  *     by chunkloading and can throw our bulk entity event. This will bypass Forge's hook for
  *     individual entity events, but the SpongeModEventManager will still successfully throw the
  *     appropriate event and cancel the entities otherwise contained.
  * @param entities The entities being loaded
  * @param callbackInfo The callback info
  */
 @Final
 @Inject(method = "loadEntities", at = @At("HEAD"), cancellable = true)
 private void spongeLoadEntities(
     Collection<net.minecraft.entity.Entity> entities, CallbackInfo callbackInfo) {
   if (entities.isEmpty()) {
     // just return, no entities to load!
     callbackInfo.cancel();
     return;
   }
   List<Entity> entityList = new ArrayList<>();
   ImmutableList.Builder<EntitySnapshot> snapshotBuilder = ImmutableList.builder();
   for (net.minecraft.entity.Entity entity : entities) {
     entityList.add((Entity) entity);
     snapshotBuilder.add(((Entity) entity).createSnapshot());
   }
   SpawnCause cause = SpawnCause.builder().type(InternalSpawnTypes.CHUNK_LOAD).build();
   List<NamedCause> causes = new ArrayList<>();
   causes.add(NamedCause.source(cause));
   causes.add(NamedCause.of("World", this));
   SpawnEntityEvent.ChunkLoad chunkLoad =
       SpongeEventFactory.createSpawnEntityEventChunkLoad(
           Cause.of(causes), entityList, snapshotBuilder.build(), this);
   SpongeImpl.postEvent(chunkLoad);
   if (!chunkLoad.isCancelled()) {
     for (Entity successful : chunkLoad.getEntities()) {
       this.loadedEntityList.add((net.minecraft.entity.Entity) successful);
       this.onEntityAdded((net.minecraft.entity.Entity) successful);
     }
   }
   callbackInfo.cancel();
 }
コード例 #8
0
  private Optional<Player> validPlayer(Cause cause) {
    Optional<EntityDamageSource> optionalSrc = cause.first(EntityDamageSource.class);

    if (optionalSrc.isPresent()) {
      Entity src = optionalSrc.get().getSource();

      if (src instanceof Player) {
        return Optional.of((Player) src);
      } else if (src instanceof Projectile) {
        Projectile projectile = (Projectile) src;

        Optional<UUID> optionalUUID = projectile.getCreator();

        if (!optionalUUID.isPresent()) {
          return Optional.empty();
        }

        Optional<Player> optionalPlayer = Sponge.getServer().getPlayer(optionalUUID.get());

        if (!optionalPlayer.isPresent()) {
          return Optional.empty();
        }

        return Optional.of(optionalPlayer.get());
      }
    }

    return Optional.empty();
  }
コード例 #9
0
  public void spawnEntity(Location<World> location, Vector3d velocity, CommandSource src) {
    Extent extent = location.getExtent();
    Optional<Entity> optional = extent.createEntity(EntityTypes.FIREBALL, location.getPosition());

    Entity fireball = optional.get();
    fireball.offer(Keys.VELOCITY, velocity);
    extent.spawnEntity(fireball, Cause.of(src));
  }
コード例 #10
0
  public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException {
    if (src instanceof Player) {
      Player player = (Player) src;
      String playerTeamName = ConfigManager.getTeam(player.getUniqueId());

      if (playerTeamName != null
          && !ConfigManager.getMembers(playerTeamName).contains(player.getUniqueId().toString())) {
        BigDecimal money =
            ConfigManager.getClaimCost()
                .multiply(new BigDecimal(ConfigManager.getClaims(playerTeamName)));
        Polis.economyService
            .getOrCreateAccount(playerTeamName)
            .get()
            .deposit(
                Polis.economyService.getDefaultCurrency(),
                money,
                Cause.of(NamedCause.source(player)));
        ConfigManager.depositToTownBank(money, playerTeamName);
        ConfigManager.removeClaims(playerTeamName);
        player.sendMessage(
            Text.of(
                TextColors.GREEN,
                "[Polis]: ",
                TextColors.GOLD,
                "Successfully removed all claims!"));
      } else if (playerTeamName != null) {
        player.sendMessage(
            Text.of(
                TextColors.GREEN,
                "[Polis]: ",
                TextColors.DARK_RED,
                "Error! ",
                TextColors.RED,
                "Ask your leader to remove all claims!"));
      } else {
        player.sendMessage(
            Text.of(
                TextColors.GREEN,
                "[Polis]: ",
                TextColors.DARK_RED,
                "Error! ",
                TextColors.RED,
                "You're not part of a town!"));
      }
    } else {
      src.sendMessage(
          Text.of(
              TextColors.DARK_RED,
              "Error! ",
              TextColors.RED,
              "Must be an in-game player to use /polis unclaimall!"));
    }

    return CommandResult.success();
  }
コード例 #11
0
  @Overwrite
  public static PlayerInteractEvent onPlayerInteract(
      EntityPlayer player,
      Action action,
      net.minecraft.world.World world,
      BlockPos pos,
      EnumFacing face) {
    if (world.isRemote) {
      PlayerInteractEvent event = new PlayerInteractEvent(player, action, pos, face, world);
      MinecraftForge.EVENT_BUS.post(event);
      return event;
    }

    InteractBlockEvent event = null;
    if (action == Action.LEFT_CLICK_BLOCK) {
      event =
          SpongeEventFactory.createInteractBlockEventPrimary(
              SpongeImpl.getGame(),
              Cause.of(player),
              Optional.empty(),
              ((World) world).createSnapshot(VecHelper.toVector(pos)),
              face == null
                  ? Direction.NONE
                  : DirectionFacingProvider.getInstance().getKey(face).get());
    } else {
      event =
          SpongeEventFactory.createInteractBlockEventSecondary(
              SpongeImpl.getGame(),
              Cause.of(player),
              Optional.empty(),
              ((World) world).createSnapshot(VecHelper.toVector(pos)),
              face == null
                  ? Direction.NONE
                  : DirectionFacingProvider.getInstance().getKey(face).get());
    }

    SpongeImpl.postEvent(event);

    return (PlayerInteractEvent) SpongeForgeEventFactory.lastForgeEvent;
  }
コード例 #12
0
  @Override
  public void accept(T t) {
    final Location<World> location = t.getLocation();

    final Explosion.Builder builder = Explosion.builder();
    builder.location(location);
    builder.canCauseFire(this.canCauseFire);
    builder.radius((float) this.radius);
    builder.shouldBreakBlocks(this.shouldBreakBlocks);
    builder.shouldDamageEntities(this.shouldDamageEntities);
    builder.shouldPlaySmoke(this.shouldPlaySmoke);

    location.getExtent().triggerExplosion(builder.build(), Cause.source(t).build());
  }
コード例 #13
0
  /**
   * @author gabizou - January 30th, 2016
   * @author blood - May 12th, 2016
   * @reason If capturing is enabled, captures the item and avoids spawn. If capturing is not
   *     enabled, redirects the dropped item spawning to use our world spawning since we know the
   *     cause.
   */
  @Overwrite
  public void joinEntityItemWithWorld(EntityItem itemIn) {
    if (this.worldObj.isRemote) {
      this.worldObj.spawnEntityInWorld(itemIn);
      return;
    }

    if (this.captureItemDrops) {
      this.capturedItemDrops.add(itemIn);
      return;
    }

    SpawnCause spawnCause =
        EntitySpawnCause.builder().entity(this).type(SpawnTypes.DROPPED_ITEM).build();
    ((org.spongepowered.api.world.World) this.worldObj)
        .spawnEntity((Entity) itemIn, Cause.of(NamedCause.source(spawnCause)));
  }
コード例 #14
0
 public static Optional<Tuple<DamageModifier, Function<? super Double, Double>>>
     createResistanceModifier(EntityLivingBase entityLivingBase, DamageSource damageSource) {
   if (!damageSource.isDamageAbsolute()
       && entityLivingBase.isPotionActive(Potion.resistance)
       && damageSource != DamageSource.outOfWorld) {
     PotionEffect effect =
         ((PotionEffect) entityLivingBase.getActivePotionEffect(Potion.resistance));
     return Optional.of(
         new Tuple<>(
             DamageModifier.builder()
                 .cause(Cause.of(NamedCause.of(DamageEntityEvent.RESISTANCE, effect)))
                 .type(DamageModifierTypes.DEFENSIVE_POTION_EFFECT)
                 .build(),
             createResistanceFunction(effect.getAmplifier())));
   }
   return Optional.empty();
 }
コード例 #15
0
 public static Optional<Tuple<DamageModifier, Function<? super Double, Double>>>
     createHardHatModifier(EntityLivingBase entityLivingBase, DamageSource damageSource) {
   if ((damageSource instanceof FallingBlockDamageSource)
       && entityLivingBase.getEquipmentInSlot(4) != null) {
     DamageModifier modifier =
         DamageModifier.builder()
             .cause(
                 Cause.of(
                     NamedCause.of(
                         DamageEntityEvent.HARD_HAT_ARMOR,
                         ((ItemStack) entityLivingBase.getEquipmentInSlot(4)).createSnapshot())))
             .type(DamageModifierTypes.HARD_HAT)
             .build();
     return Optional.of(new Tuple<>(modifier, HARD_HAT_FUNCTION));
   }
   return Optional.empty();
 }
コード例 #16
0
ファイル: InventoryGuard.java プロジェクト: CubeEngine/core
 public void submitInventory(Class owner, boolean openInventory) {
   this.owner = owner;
   em.registerListener(owner, this);
   if (openInventory) {
     for (UUID user : users) {
       Optional<Player> player = Sponge.getServer().getPlayer(user);
       if (player.isPresent()) {
         this.container =
             player
                 .get()
                 .openInventory(this.inventory, Cause.of(NamedCause.source(player)))
                 .orElse(null);
         // TODO check if not opened
       }
     }
   }
 }
コード例 #17
0
 public static Optional<Tuple<DamageModifier, Function<? super Double, Double>>>
     createBlockingModifier(EntityLivingBase entityLivingBase, DamageSource damageSource) {
   if (!damageSource.isUnblockable()
       && (entityLivingBase instanceof EntityPlayer
           && ((EntityPlayer) entityLivingBase).isBlocking())) {
     DamageModifier modifier =
         DamageModifier.builder()
             .cause(
                 Cause.of(
                     NamedCause.of(
                         DamageEntityEvent.BLOCKING,
                         ((ItemStack) ((EntityPlayer) entityLivingBase).getCurrentEquippedItem())
                             .createSnapshot())))
             .type(DamageModifierTypes.BLOCKING)
             .build();
     return Optional.of(new Tuple<>(modifier, BLOCKING_FUNCTION));
   }
   return Optional.empty();
 }
コード例 #18
0
  @Listener(order = Order.POST)
  public void onAffectSlotEvent(AffectSlotEvent event, @Root Player player) {
    for (SlotTransaction transaction : event.getTransactions()) {
      ItemStack itemStack = transaction.getFinal().createStack();

      BigDecimal amount = WalletDrop.getValue(itemStack);

      if (amount.compareTo(BigDecimal.ZERO) == 0) {
        continue;
      }

      WorldSettings settings = WorldSettings.get(player.getWorld());

      if (player.gameMode().get().equals(GameModes.CREATIVE) && !settings.isCreativeModeAllowed()) {
        event.setCancelled(true);
        return;
      }

      if (settings.isUsePermissions()) {
        if (!player.hasPermission("walletdrop.enable")) {
          return;
        }
      }

      WalletPickupEvent moneyPickupEvent =
          new WalletPickupEvent(itemStack, amount, Cause.of(NamedCause.source(player)));

      if (!Sponge.getEventManager().post(moneyPickupEvent)) {
        Sponge.getScheduler()
            .createTaskBuilder()
            .delayTicks(2)
            .execute(
                c -> {
                  player.getInventory().query(itemStack).clear();
                })
            .submit(Main.getPlugin());

        WalletDrop.depositOrWithdraw(player, moneyPickupEvent.getAmount());

        WalletDrop.sendPickupMessage(player, amount);
      }
    }
  }
コード例 #19
0
 @Inject(
     method = "randomTick",
     at = @At(value = "HEAD"),
     locals = LocalCapture.CAPTURE_FAILEXCEPTION,
     cancellable = true)
 public void callRandomTickEvent(
     net.minecraft.world.World world,
     BlockPos pos,
     IBlockState state,
     Random rand,
     CallbackInfo ci) {
   BlockSnapshot blockSnapshot = ((World) world).createSnapshot(VecHelper.toVector(pos));
   final TickBlockEvent event =
       SpongeEventFactory.createTickBlockEvent(Cause.of(NamedCause.source(world)), blockSnapshot);
   SpongeImpl.postEvent(event);
   if (event.isCancelled()) {
     ci.cancel();
   }
 }
コード例 #20
0
 @Redirect(
     method = "onUpdate",
     at =
         @At(
             value = "INVOKE",
             target = "Lnet/minecraft/entity/player/EntityPlayer;isPlayerSleeping()Z"))
 public boolean onIsPlayerSleeping(EntityPlayer self) {
   if (self.isPlayerSleeping()) {
     if (!this.worldObj.isRemote) {
       SpongeImpl.postEvent(
           SpongeEventFactory.createSleepingEventTick(
               Cause.of(NamedCause.source(this)),
               this.getWorld().createSnapshot(VecHelper.toVector(this.playerLocation)),
               this));
     }
     return true;
   }
   return false;
 }
コード例 #21
0
 public static Optional<Tuple<DamageModifier, Function<? super Double, Double>>>
     createAbsorptionModifier(EntityLivingBase entityLivingBase, DamageSource damageSource) {
   if (entityLivingBase.isPotionActive(Potion.absorption)) {
     Function<? super Double, Double> function =
         damage ->
             -(Math.max(
                 damage - Math.max(damage - entityLivingBase.getAbsorptionAmount(), 0.0F), 0.0F));
     DamageModifier modifier =
         DamageModifier.builder()
             .cause(
                 Cause.of(
                     NamedCause.of(
                         DamageEntityEvent.ABSORPTION,
                         entityLivingBase.getActivePotionEffect(Potion.absorption)),
                     NamedCause.of(DamageEntityEvent.CREATOR, entityLivingBase)))
             .type(DamageModifierTypes.ABSORPTION)
             .build();
     return Optional.of(new Tuple<>(modifier, function));
   }
   return Optional.empty();
 }
コード例 #22
0
 @Redirect(
     method = "onUpdate()V",
     at =
         @At(
             value = "INVOKE",
             target =
                 "Lnet/minecraft/entity/Entity;attackEntityFrom(Lnet/minecraft/util/DamageSource;F)Z"))
 public boolean onAttackEntityFrom(
     net.minecraft.entity.Entity entity, DamageSource damageSource, float damage) {
   EntitySnapshot fishHookSnapshot = this.createSnapshot();
   FishingEvent.HookEntity event =
       SpongeEventFactory.createFishingEventHookEntity(
           Cause.of(NamedCause.source(this.angler)), this.createSnapshot(), this, (Entity) entity);
   if (!SpongeImpl.postEvent(event)) {
     if (this.getShooter() instanceof Entity) {
       DamageSource.causeThrownDamage(
           (net.minecraft.entity.Entity) (Object) this,
           (net.minecraft.entity.Entity) this.getShooter());
     }
     return entity.attackEntityFrom(damageSource, (float) this.getDamage());
   }
   return false;
 }
コード例 #23
0
 @Inject(
     method = "combineItems",
     at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/item/EntityItem;setDead()V"))
 public void onCombineItems(EntityItem other, CallbackInfoReturnable<Boolean> cir) {
   this.destructCause = Cause.of(NamedCause.of("CombinedItem", other));
 }
コード例 #24
0
 @Inject(
     method = "onUpdate()V",
     at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/item/EntityItem;setDead()V"))
 public void onEntityItemUpdate(CallbackInfo ci) {
   this.destructCause = Cause.of(NamedCause.of("ExpiredItem", this));
 }
コード例 #25
0
  /**
   * @author gabizou - April 8th, 2016
   * @reason Rewrites the attackTargetEntityWithCurrentItem to throw an {@link AttackEntityEvent}
   *     prior to the ensuing {@link DamageEntityEvent}. This should cover all cases where players
   *     are attacking entities and those entities override {@link
   *     EntityLivingBase#attackEntityFrom(DamageSource, float)} and effectively bypass our damage
   *     event hooks.
   * @param targetEntity The target entity
   */
  @Overwrite
  public void attackTargetEntityWithCurrentItem(net.minecraft.entity.Entity targetEntity) {
    // Sponge Start - Add SpongeImpl hook to override in forge as necessary
    if (!SpongeImplHooks.checkAttackEntity((EntityPlayer) (Object) this, targetEntity)) {
      return;
    }
    // Sponge End
    if (targetEntity.canAttackWithItem()) {
      if (!targetEntity.hitByEntity((EntityPlayer) (Object) this)) {
        // Sponge Start - Prepare our event values
        // float baseDamage =
        // this.getEntityAttribute(SharedMonsterAttributes.attackDamage).getAttributeValue();
        final double originalBaseDamage =
            this.getEntityAttribute(SharedMonsterAttributes.attackDamage).getAttributeValue();
        float baseDamage = (float) originalBaseDamage;
        // Sponge End
        int knockbackModifier = 0;
        float enchantmentModifierAmount = 0.0F;

        // Sponge Start - gather the attack modifiers
        final List<Tuple<DamageModifier, Function<? super Double, Double>>> originalFunctions =
            new ArrayList<>();

        final EnumCreatureAttribute creatureAttribute =
            targetEntity instanceof EntityLivingBase
                ? ((EntityLivingBase) targetEntity).getCreatureAttribute()
                : EnumCreatureAttribute.UNDEFINED;
        final List<Tuple<DamageModifier, Function<? super Double, Double>>>
            enchantmentModifierFunctions =
                DamageEventHandler.createAttackEnchamntmentFunction(
                    this.getHeldItem(), creatureAttribute);
        // if (targetEntity instanceof EntityLivingBase) {
        //     enchantmentModifierAmount =
        // EnchantmentHelper.getModifierForCreature(this.getHeldItem(), creatureAttribute);
        // } else {
        //     enchantmentModifierAmount =
        // EnchantmentHelper.getModifierForCreature(this.getHeldItem(),
        // EnumCreatureAttribute.UNDEFINED);
        // }
        enchantmentModifierAmount =
            (float)
                enchantmentModifierFunctions
                    .stream()
                    .map(Tuple::getSecond)
                    .mapToDouble(function -> function.apply(originalBaseDamage))
                    .sum();
        originalFunctions.addAll(enchantmentModifierFunctions);
        // Sponge End

        knockbackModifier =
            knockbackModifier
                + EnchantmentHelper.getKnockbackModifier((EntityPlayer) (Object) this);

        if (this.isSprinting()) {
          ++knockbackModifier;
        }

        if (baseDamage > 0.0F || enchantmentModifierAmount > 0.0F) {
          boolean fallingCriticalHit =
              this.fallDistance > 0.0F
                  && !this.onGround
                  && !this.isOnLadder()
                  && !this.isInWater()
                  && !this.isPotionActive(Potion.blindness)
                  && this.ridingEntity == null
                  && targetEntity instanceof EntityLivingBase;

          if (fallingCriticalHit && baseDamage > 0.0F) {
            // Sponge - Add the function for critical attacking
            originalFunctions.add(
                DamageEventHandler.provideCriticalAttackTuple((EntityPlayer) (Object) this));
            // baseDamage *= 1.5F; Sponge - remove since it's handled in the event
          }

          // baseDamage = baseDamage + enchantmentModifierAmount; // Sponge - remove since it is
          // delegated through the event.
          boolean targetLitOnFire = false;
          int fireAspectLevel =
              EnchantmentHelper.getFireAspectModifier((EntityPlayer) (Object) this);

          if (targetEntity instanceof EntityLivingBase
              && fireAspectLevel > 0
              && !targetEntity.isBurning()) {
            targetLitOnFire = true;
            targetEntity.setFire(1);
          }

          double targetMotionX = targetEntity.motionX;
          double targetMotionY = targetEntity.motionY;
          double targetMotionZ = targetEntity.motionZ;

          // Sponge Start - Create the event and throw it
          final DamageSource damageSource =
              DamageSource.causePlayerDamage((EntityPlayer) (Object) this);
          final AttackEntityEvent event =
              SpongeEventFactory.createAttackEntityEvent(
                  Cause.source(damageSource).build(),
                  originalFunctions,
                  EntityUtil.fromNative(targetEntity),
                  knockbackModifier,
                  originalBaseDamage);
          SpongeImpl.postEvent(event);
          if (event.isCancelled()) {
            if (targetLitOnFire) {
              targetEntity.extinguish();
            }
            return;
          }
          baseDamage = (float) event.getFinalOutputDamage();
          knockbackModifier = event.getKnockbackModifier();
          boolean attackSucceded =
              targetEntity.attackEntityFrom(damageSource, (float) event.getFinalOutputDamage());
          // Sponge End
          if (attackSucceded) {
            if (knockbackModifier > 0) {
              targetEntity.addVelocity(
                  (double)
                      (-MathHelper.sin(this.rotationYaw * (float) Math.PI / 180.0F)
                          * (float) knockbackModifier
                          * 0.5F),
                  0.1D,
                  (double)
                      (MathHelper.cos(this.rotationYaw * (float) Math.PI / 180.0F)
                          * (float) knockbackModifier
                          * 0.5F));
              this.motionX *= 0.6D;
              this.motionZ *= 0.6D;
              this.setSprinting(false);
            }

            if (targetEntity instanceof EntityPlayerMP && targetEntity.velocityChanged) {
              ((EntityPlayerMP) targetEntity)
                  .playerNetServerHandler.sendPacket(new S12PacketEntityVelocity(targetEntity));
              targetEntity.velocityChanged = false;
              targetEntity.motionX = targetMotionX;
              targetEntity.motionY = targetMotionY;
              targetEntity.motionZ = targetMotionZ;
            }

            if (fallingCriticalHit) {
              this.onCriticalHit(targetEntity);
            }

            if (enchantmentModifierAmount > 0.0F) {
              this.onEnchantmentCritical(targetEntity);
            }

            if (baseDamage >= 18.0F) {
              this.triggerAchievement(AchievementList.overkill);
            }

            this.setLastAttacker(targetEntity);

            if (targetEntity instanceof EntityLivingBase) {
              EnchantmentHelper.applyThornEnchantments(
                  (EntityLivingBase) targetEntity, (EntityPlayer) (Object) this);
            }

            EnchantmentHelper.applyArthropodEnchantments(
                (EntityPlayer) (Object) this, targetEntity);
            ItemStack itemstack = this.getCurrentEquippedItem();
            net.minecraft.entity.Entity entity = targetEntity;

            if (targetEntity instanceof EntityDragonPart) {
              IEntityMultiPart ientitymultipart = ((EntityDragonPart) targetEntity).entityDragonObj;

              if (ientitymultipart instanceof EntityLivingBase) {
                entity = (EntityLivingBase) ientitymultipart;
              }
            }

            if (itemstack != null && entity instanceof EntityLivingBase) {
              itemstack.hitEntity((EntityLivingBase) entity, (EntityPlayer) (Object) this);

              if (itemstack.stackSize <= 0) {
                this.destroyCurrentEquippedItem();
              }
            }

            if (targetEntity instanceof EntityLivingBase) {
              this.addStat(StatList.damageDealtStat, Math.round(baseDamage * 10.0F));

              if (fireAspectLevel > 0) {
                targetEntity.setFire(fireAspectLevel * 4);
              }
            }

            this.addExhaustion(0.3F);
          } else if (targetLitOnFire) {
            targetEntity.extinguish();
          }
        }
      }
    }
  }
コード例 #26
0
 @Override
 public Cause getCause() {
   return Cause.of(this.player);
 }
コード例 #27
0
  /**
   * @author Aaron1011 - February 6th, 2015
   * @reason This needs to handle for both cases where a fish and/or an entity is being caught.
   *     There's no real good way to do this with an injection.
   */
  @Overwrite
  public int handleHookRetraction() {
    if (this.worldObj.isRemote) {
      return 0;
    }

    // Sponge start
    byte b0 = 0;

    net.minecraft.item.ItemStack itemStack = null;
    int exp = 0;
    if (this.ticksCatchable > 0) {
      itemStack = this.getFishingResult();
      exp = this.rand.nextInt(6) + 1;
    }

    EntitySnapshot fishHookSnapshot = this.createSnapshot();

    Transaction<ItemStackSnapshot> transaction = null;
    if (itemStack != null) {
      ItemStackSnapshot original = ((ItemStack) itemStack).createSnapshot();
      ItemStackSnapshot replacement = ((ItemStack) itemStack).createSnapshot();
      transaction = new Transaction<>(original, replacement);
    } else {
      transaction = new Transaction<>(ItemStackSnapshot.NONE, ItemStackSnapshot.NONE);
    }

    FishingEvent.Stop event =
        SpongeEventFactory.createFishingEventStop(
            Cause.of(NamedCause.source(this.angler)),
            exp,
            exp,
            fishHookSnapshot,
            this,
            transaction,
            (Player) this.angler);
    if (!SpongeImpl.postEvent(event)) {
      // Sponge end
      if (this.caughtEntity != null) {
        double d0 = this.angler.posX - this.posX;
        double d2 = this.angler.posY - this.posY;
        double d4 = this.angler.posZ - this.posZ;
        double d6 = (double) MathHelper.sqrt_double(d0 * d0 + d2 * d2 + d4 * d4);
        double d8 = 0.1D;
        this.caughtEntity.motionX += d0 * d8;
        this.caughtEntity.motionY += d2 * d8 + (double) MathHelper.sqrt_double(d6) * 0.08D;
        this.caughtEntity.motionZ += d4 * d8;
        b0 = 3;
      }

      // Sponge Start
      if (!event.getItemStackTransaction().getFinal().getType().equals(ItemTypes.NONE)) {
        ItemStackSnapshot itemSnapshot = event.getItemStackTransaction().getFinal();
        EntityItem entityitem1 =
            new EntityItem(
                this.worldObj,
                this.posX,
                this.posY,
                this.posZ,
                (net.minecraft.item.ItemStack) itemSnapshot.createStack());
        double d1 = this.angler.posX - this.posX;
        double d3 = this.angler.posY - this.posY;
        double d5 = this.angler.posZ - this.posZ;
        double d7 = MathHelper.sqrt_double(d1 * d1 + d3 * d3 + d5 * d5);
        double d9 = 0.1D;
        entityitem1.motionX = d1 * d9;
        entityitem1.motionY = d3 * d9 + MathHelper.sqrt_double(d7) * 0.08D;
        entityitem1.motionZ = d5 * d9;
        this.worldObj.spawnEntityInWorld(entityitem1);
        this.angler.worldObj.spawnEntityInWorld(
            new EntityXPOrb(
                this.angler.worldObj,
                this.angler.posX,
                this.angler.posY + 0.5D,
                this.angler.posZ + 0.5D,
                event.getExperience()));
        // Sponge End
        b0 = 1;
      }

      if (this.inGround) {
        b0 = 2;
      }

      this.setDead();
      this.angler.fishEntity = null;

      // Sponge Start
      if (this.fishingRod != null) {
        this.fishingRod.damageItem(b0, this.angler);
        this.angler.swingItem();
        this.fishingRod = null;
      }
      // Sponge End
    }
    return b0;
  }
コード例 #28
0
@Mixin(EntityLightningBolt.class)
public abstract class MixinEntityLightningBolt extends MixinEntityWeatherEffect
    implements Lightning, IMixinEntityLightningBolt {

  public Cause cause = Cause.source(this).build();

  private final List<Entity> struckEntities = Lists.newArrayList();
  private final List<EntitySnapshot> struckEntitySnapshots = Lists.newArrayList();
  private final List<Transaction<BlockSnapshot>> struckBlocks = Lists.newArrayList();
  private boolean effect = false;

  @Override
  public boolean isEffect() {
    return this.effect;
  }

  @Override
  public void setEffect(boolean effect) {
    this.effect = effect;
  }

  @Override
  public ExpirableData getExpiringData() {
    return get(ExpirableData.class).get();
  }

  @Redirect(
      method = "<init>",
      at =
          @At(
              value = "INVOKE",
              target =
                  "Lnet/minecraft/world/World;setBlockState(Lnet/minecraft/util/BlockPos;Lnet/minecraft/block/state/IBlockState;)Z"))
  public boolean onStrikeBlockInit(
      net.minecraft.world.World world, BlockPos pos, IBlockState blockState) {
    return onStrikeBlock(world, pos, blockState);
  }

  @Redirect(
      method = "onUpdate()V",
      at =
          @At(
              value = "INVOKE",
              target =
                  "Lnet/minecraft/world/World;setBlockState(Lnet/minecraft/util/BlockPos;Lnet/minecraft/block/state/IBlockState;)Z"))
  public boolean onStrikeBlockUpdate(
      net.minecraft.world.World world, BlockPos pos, IBlockState blockState) {
    return onStrikeBlock(world, pos, blockState);
  }

  private boolean onStrikeBlock(
      net.minecraft.world.World world, BlockPos pos, IBlockState blockState) {
    if (!this.effect) {
      Vector3i pos3i = VecHelper.toVector(pos);
      Transaction<BlockSnapshot> transaction =
          new Transaction<BlockSnapshot>(
              new SpongeBlockSnapshotBuilder()
                  .blockState((BlockState) world.getBlockState(pos))
                  .world(((World) world).getProperties())
                  .position(pos3i)
                  .build(),
              new SpongeBlockSnapshotBuilder()
                  .blockState((BlockState) blockState)
                  .world(((World) world).getProperties())
                  .position(pos3i)
                  .build());
      if (!this.struckBlocks.contains(transaction)) {
        this.struckBlocks.add(transaction);
      }
    }
    return false;
  }

  @Redirect(
      method = "onUpdate()V",
      at =
          @At(
              value = "INVOKE",
              target =
                  "Lnet/minecraft/entity/Entity;onStruckByLightning(Lnet/minecraft/entity/effect/EntityLightningBolt;)V"))
  public void onStrikeEntity(
      net.minecraft.entity.Entity mcEntity, EntityLightningBolt lightningBolt) {
    if (!this.effect) {
      Entity entity = (Entity) mcEntity;
      if (!this.struckEntities.contains(entity)) {
        this.struckEntities.add(entity);
        this.struckEntitySnapshots.add(new SpongeEntitySnapshotBuilder().from(mcEntity).build());
      }
    }
  }

  @Inject(
      method = "onUpdate",
      at =
          @At(
              value = "INVOKE",
              target = "Lnet/minecraft/entity/effect/EntityLightningBolt;setDead()V"))
  public void onSetDead(CallbackInfo ci) {
    if (this.isDead) {
      return;
    }
    World world = (World) this.worldObj;
    LightningEvent.Strike strike =
        SpongeEventFactory.createLightningEventStrike(
            this.cause, this.struckEntities, this.struckEntitySnapshots, world, this.struckBlocks);
    Sponge.getEventManager().post(strike);

    if (!strike.isCancelled()) {
      for (Transaction<BlockSnapshot> bt : strike.getTransactions()) {
        if (bt.isValid()) {
          BlockSnapshot bs = bt.getFinal();
          world.setBlock(bs.getPosition(), bs.getState());
        }
      }
      for (Entity e : strike.getEntities()) {
        ((net.minecraft.entity.Entity) e).onStruckByLightning((EntityLightningBolt) (Object) this);
      }
      SpongeImpl.postEvent(SpongeEventFactory.createLightningEventPost(this.cause));
    }
  }

  @Override
  public void readFromNbt(NBTTagCompound compound) {
    super.readFromNbt(compound);
    if (compound.hasKey("effect")) {
      this.effect = compound.getBoolean("effect");
    }
  }

  @Override
  public void writeToNbt(NBTTagCompound compound) {
    super.writeToNbt(compound);
    compound.setBoolean("effect", this.effect);
  }

  @Override
  public Cause getCause() {
    return this.cause;
  }

  @Override
  public void setCause(Cause cause) {
    this.cause = cause;
  }
}
コード例 #29
0
 @Override
 public Cause getCause() {
   return Cause.of(this.entity);
 }
コード例 #30
0
ファイル: MixinEvent.java プロジェクト: XakepSDK/Sponge
 @Override
 public Cause getCause() {
   return Cause.empty();
 }