private void loadPlugins(Object source, Set<String> loadedPlugins, Iterable<String> plugins) {
    for (String plugin : plugins) {
      if (loadedPlugins.contains(plugin)) {
        SpongeImpl.getLogger().warn("Skipping duplicate plugin class {} from {}", plugin, source);
        continue;
      }

      try {
        Class<?> pluginClass = Class.forName(plugin);
        VanillaPluginContainer container = new VanillaPluginContainer(source, pluginClass);
        registerPlugin(container);
        loadedPlugins.add(plugin);
        SpongeImpl.getGame()
            .getEventManager()
            .registerListeners(container, container.getInstance().get());

        SpongeImpl.getLogger()
            .info(
                "Loaded plugin: {} {} (from {})",
                container.getName(),
                container.getVersion(),
                source);
      } catch (Throwable e) {
        SpongeImpl.getLogger().error("Failed to load plugin: {} (from {})", plugin, source, e);
      }
    }
  }
  public void loadPlugins() throws IOException {
    for (PluginContainer container : SpongeVersion.getComponents()) {
      registerPlugin(container);
    }

    Set<String> plugins;
    Set<String> loadedPlugins = new HashSet<>();

    if (SCAN_CLASSPATH) {
      SpongeImpl.getLogger().info("Scanning classpath for plugins...");

      // Find plugins on the classpath
      plugins = PluginScanner.scanClassPath(Launch.classLoader);
      if (!plugins.isEmpty()) {
        loadPlugins("classpath", loadedPlugins, plugins);
      }
    }

    try (DirectoryStream<Path> dir =
        Files.newDirectoryStream(SpongeImpl.getPluginsDir(), ARCHIVE_FILTER)) {
      for (Path jar : dir) {
        // Search for plugins in the JAR
        plugins = PluginScanner.scanZip(jar);

        if (!plugins.isEmpty()) {
          // Add plugin to the classpath
          Launch.classLoader.addURL(jar.toUri().toURL());

          // Load the plugins
          loadPlugins(jar, loadedPlugins, plugins);
        }
      }
    }
  }
 private static boolean isDefaultProperPhase(RegistryModule module) {
   try {
     Method method = module.getClass().getMethod("registerDefaults");
     DelayedRegistration delay = method.getDeclaredAnnotation(DelayedRegistration.class);
     if (delay == null) {
       return SpongeImpl.getRegistry().getPhase() == RegistrationPhase.PRE_REGISTRY;
     } else {
       return SpongeImpl.getRegistry().getPhase() == delay.value();
     }
   } catch (NoSuchMethodException e) {
     e.printStackTrace();
   }
   return false;
 }
 private static boolean isCustomProperPhase(RegistryModule module) {
   for (Method method : module.getClass().getMethods()) {
     CustomCatalogRegistration registration =
         method.getDeclaredAnnotation(CustomCatalogRegistration.class);
     DelayedRegistration delay = method.getDeclaredAnnotation(DelayedRegistration.class);
     if (registration != null) {
       if (delay == null) {
         return SpongeImpl.getRegistry().getPhase() == RegistrationPhase.PRE_REGISTRY;
       } else {
         return SpongeImpl.getRegistry().getPhase() == delay.value();
       }
     }
   }
   return false;
 }
 @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);
   }
 }
Пример #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
 /**
  * @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();
 }
 @SuppressWarnings("unchecked")
 protected static boolean post(
     Event event,
     List<RegisteredListener<?>> listeners,
     boolean beforeModifications,
     boolean forced) {
   ModContainer oldContainer =
       ((IMixinLoadController) SpongeMod.instance.getController()).getActiveModContainer();
   for (@SuppressWarnings("rawtypes") RegisteredListener listener : listeners) {
     ((IMixinLoadController) SpongeMod.instance.getController())
         .setActiveModContainer((ModContainer) listener.getPlugin());
     try {
       if (forced
           || (!listener.isBeforeModifications() && !beforeModifications)
           || (listener.isBeforeModifications() && beforeModifications)) {
         listener.handle(event);
       }
     } catch (Throwable e) {
       SpongeImpl.getLogger()
           .error(
               "Could not pass {} to {}",
               event.getClass().getSimpleName(),
               listener.getPlugin(),
               e);
     }
   }
   ((IMixinLoadController) SpongeMod.instance.getController()).setActiveModContainer(oldContainer);
   return event instanceof Cancellable && ((Cancellable) event).isCancelled();
 }
  @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));
    }
  }
Пример #10
0
 PingRecord() {
   final Collection<Player> onlinePlayers = SpongeImpl.getGame().getServer().getOnlinePlayers();
   int totalPing = 0;
   for (Player player : onlinePlayers) {
     totalPing += player.getConnection().getLatency();
   }
   this.avg = onlinePlayers.isEmpty() ? 0 : totalPing / onlinePlayers.size();
 }
  public boolean checkLastInteraction(Claim claim, User user) {
    if (this.lastInteractResult
        && ((SpongeImpl.getServer().getTickCounter() - this.lastTickCounter) <= 2)) {
      if (user != null
          && user.getUniqueId().equals(this.playerID)
          && (claim.getID().equals(this.lastInteractClaim) || claim.isWildernessClaim())) {
        return true;
      }
    }

    return false;
  }
  @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;
  }
Пример #13
0
 private static void invokeCustomRegistration(RegistryModule module, Method method) {
   try {
     if (isCustomProperPhase(module)) {
       method.invoke(module);
     }
   } catch (IllegalAccessException | InvocationTargetException e) {
     SpongeImpl.getLogger()
         .error(
             "Error when calling custom catalog registration for module: "
                 + module.getClass().getCanonicalName(),
             e);
   }
 }
Пример #14
0
 // @formatter:on
 @Inject(method = "<init>", at = @At("RETURN"))
 public void onConstructed(
     ISaveHandler saveHandlerIn,
     WorldInfo info,
     WorldProvider providerIn,
     Profiler profilerIn,
     boolean client,
     CallbackInfo ci) {
   if (info == null) {
     SpongeImpl.getLogger()
         .warn(
             "World constructed without a WorldInfo! This will likely cause problems. Subsituting dummy info.",
             new RuntimeException("Stack trace:"));
     this.worldInfo =
         new WorldInfo(
             new WorldSettings(0, WorldSettings.GameType.NOT_SET, false, false, WorldType.DEFAULT),
             "sponge$dummy_world");
   }
   this.worldContext = new Context(Context.WORLD_KEY, this.worldInfo.getWorldName());
   if (SpongeImpl.getGame().getPlatform().getType() == Platform.Type.SERVER) {
     this.worldBorder.addListener(new PlayerBorderListener(providerIn.getDimensionId()));
   }
   this.activeConfig = SpongeHooks.getActiveConfig((net.minecraft.world.World) (Object) this);
 }
Пример #15
0
  public boolean post(
      Event spongeEvent,
      net.minecraftforge.fml.common.eventhandler.Event forgeEvent,
      IEventListener[] listeners) {
    checkNotNull(forgeEvent, "forgeEvent");

    if (spongeEvent == null) { // Fired by Forge
      spongeEvent = ((IMixinEvent) forgeEvent).createSpongeEvent();
    }
    RegisteredListener.Cache listenerCache = getHandlerCache(spongeEvent);
    // Fire events to plugins before modifications
    for (Order order : Order.values()) {
      post(spongeEvent, listenerCache.getListenersByOrder(order), true, false);
    }

    // If there are no forge listeners for event, skip sync
    if (listeners.length > 0) {
      // sync plugin data for Mods
      ((IMixinEvent) forgeEvent).syncDataToForge(spongeEvent);

      for (IEventListener listener : listeners) {
        try {
          listener.invoke(forgeEvent);
        } catch (Throwable throwable) {
          SpongeImpl.getLogger().catching(throwable);
        }
      }

      // sync Forge data for Plugins
      ((IMixinEvent) spongeEvent).syncDataToSponge(forgeEvent);
    }

    // Fire events to plugins after modifications (default)
    for (Order order : Order.values()) {
      post(spongeEvent, listenerCache.getListenersByOrder(order), false, false);
    }

    // sync plugin data for Forge
    ((IMixinEvent) forgeEvent).syncDataToForge(spongeEvent);

    if (spongeEvent instanceof Cancellable) {
      if (((Cancellable) spongeEvent).isCancelled()) {
        forgeEvent.setCanceled(true);
      }
    }
    return forgeEvent.isCancelable() && forgeEvent.isCanceled();
  }
 @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;
 }
Пример #17
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();
   }
 }
Пример #18
0
 @SuppressWarnings("unchecked")
 private static Map<String, ?> getCatalogMap(RegistryModule module) {
   for (Field field : module.getClass().getDeclaredFields()) {
     RegisterCatalog annotation = field.getAnnotation(RegisterCatalog.class);
     if (annotation != null) {
       try {
         field.setAccessible(true);
         return (Map<String, ?>) field.get(module);
       } catch (Exception e) {
         SpongeImpl.getLogger()
             .error(
                 "Failed to retrieve a registry field from module: "
                     + module.getClass().getCanonicalName());
       }
     }
   }
   throw new IllegalStateException(
       "Registry module does not have a catalog map! Registry: "
           + module.getClass().getCanonicalName());
 }
Пример #19
0
 public static Location<World> findFirstMatchingBlock(
     Entity entity, AxisAlignedBB bb, Predicate<Block> predicate) {
   int i = MathHelper.floor_double(bb.minX);
   int j = MathHelper.floor_double(bb.maxX + 1.0D);
   int k = MathHelper.floor_double(bb.minY);
   int l = MathHelper.floor_double(bb.maxY + 1.0D);
   int i1 = MathHelper.floor_double(bb.minZ);
   int j1 = MathHelper.floor_double(bb.maxZ + 1.0D);
   for (int k1 = i; k1 < j; ++k1) {
     for (int l1 = k; l1 < l; ++l1) {
       for (int i2 = i1; i2 < j1; ++i2) {
         BlockPos blockPos = new BlockPos(k1, l1, i2);
         if (predicate.test(entity.worldObj.getBlockState(blockPos).getBlock())) {
           return new Location<>((World) entity.worldObj, k1, l1, i2);
         }
       }
     }
   }
   SpongeImpl.getLogger().error("Could not find a Source block!");
   return ((org.spongepowered.api.entity.Entity) entity).getLocation();
 }
Пример #20
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;
 }
Пример #21
0
  private String getResponse(HttpURLConnection con) throws IOException {
    InputStream is = null;
    try {
      is = con.getInputStream();
      ByteArrayOutputStream bos = new ByteArrayOutputStream();

      byte[] b = new byte[1024];
      int bytesRead;
      while ((bytesRead = is.read(b)) != -1) {
        bos.write(b, 0, bytesRead);
      }
      return bos.toString();

    } catch (IOException ex) {
      this.sender.sendMessage(
          Text.of(TextColors.RED, "Error uploading timings, check your logs for more information"));
      SpongeImpl.getLogger().warn(con.getResponseMessage(), ex);
      return null;
    } finally {
      if (is != null) {
        is.close();
      }
    }
  }
Пример #22
0
  @Override
  public Optional<Entity> createEntity(EntityType type, Vector3d position) {
    checkNotNull(type, "The entity type cannot be null!");
    checkNotNull(position, "The position cannot be null!");

    Entity entity = null;

    Class<? extends Entity> entityClass = type.getEntityClass();
    double x = position.getX();
    double y = position.getY();
    double z = position.getZ();

    if (entityClass.isAssignableFrom(EntityPlayerMP.class)
        || entityClass.isAssignableFrom(EntityDragonPart.class)) {
      // Unable to construct these
      return Optional.empty();
    }

    net.minecraft.world.World world = (net.minecraft.world.World) (Object) this;

    // Not all entities have a single World parameter as their constructor
    if (entityClass.isAssignableFrom(EntityLightningBolt.class)) {
      entity = (Entity) new EntityLightningBolt(world, x, y, z);
    } else if (entityClass.isAssignableFrom(EntityEnderPearl.class)) {
      EntityArmorStand tempEntity = new EntityArmorStand(world, x, y, z);
      tempEntity.posY -= tempEntity.getEyeHeight();
      entity = (Entity) new EntityEnderPearl(world, tempEntity);
      ((EnderPearl) entity).setShooter(ProjectileSource.UNKNOWN);
    }

    // Some entities need to have non-null fields (and the easiest way to
    // set them is to use the more specialised constructor).
    if (entityClass.isAssignableFrom(EntityFallingBlock.class)) {
      entity = (Entity) new EntityFallingBlock(world, x, y, z, Blocks.sand.getDefaultState());
    } else if (entityClass.isAssignableFrom(EntityItem.class)) {
      entity = (Entity) new EntityItem(world, x, y, z, new ItemStack(Blocks.stone));
    }

    if (entity == null) {
      try {
        entity = ConstructorUtils.invokeConstructor(entityClass, this);
        ((net.minecraft.entity.Entity) entity).setPosition(x, y, z);
      } catch (Exception e) {
        SpongeImpl.getLogger().error(ExceptionUtils.getStackTrace(e));
      }
    }

    // TODO - replace this with an actual check
    /*
    if (entity instanceof EntityHanging) {
        if (((EntityHanging) entity).facingDirection == null) {
            // TODO Some sort of detection of a valid direction?
            // i.e scan immediate blocks for something to attach onto.
            ((EntityHanging) entity).facingDirection = EnumFacing.NORTH;
        }
        if (!((EntityHanging) entity).onValidSurface()) {
            return Optional.empty();
        }
    }*/

    // Last chance to fix null fields
    if (entity instanceof EntityPotion) {
      // make sure EntityPotion.potionDamage is not null
      ((EntityPotion) entity).getPotionDamage();
    } else if (entity instanceof EntityPainting) {
      // This is default when art is null when reading from NBT, could
      // choose a random art instead?
      ((EntityPainting) entity).art = EnumArt.KEBAB;
    }

    return Optional.ofNullable(entity);
  }
  /**
   * @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();
          }
        }
      }
    }
  }
Пример #24
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;
  }
Пример #25
0
  TimingHistory() {
    this.endTime = System.currentTimeMillis() / 1000;
    this.startTime = TimingsManager.historyStart / 1000;
    if (timedTicks % 1200 != 0 || MINUTE_REPORTS.isEmpty()) {
      this.minuteReports = MINUTE_REPORTS.toArray(new MinuteReport[MINUTE_REPORTS.size() + 1]);
      this.minuteReports[this.minuteReports.length - 1] = new MinuteReport();
    } else {
      this.minuteReports = MINUTE_REPORTS.toArray(new MinuteReport[MINUTE_REPORTS.size()]);
    }
    long ticks = 0;
    for (MinuteReport mp : this.minuteReports) {
      ticks += mp.ticksRecord.timed;
    }
    this.totalTicks = ticks;
    this.totalTime = FULL_SERVER_TICK.record.totalTime;
    this.entries = new TimingHistoryEntry[TimingsManager.HANDLERS.size()];

    int i = 0;
    for (TimingHandler handler : TimingsManager.HANDLERS) {
      this.entries[i++] = new TimingHistoryEntry(handler);
    }

    final Map<EntityType, Counter> entityCounts =
        MRUMapCache.of(LoadingMap.of(Maps.newHashMap(), Counter.loader()));
    final Map<BlockType, Counter> tileEntityCounts =
        MRUMapCache.of(LoadingMap.of(Maps.newHashMap(), Counter.loader()));
    // Information about all loaded chunks/entities
    this.worlds =
        JSONUtil.mapArrayToObject(
            SpongeImpl.getGame().getServer().getWorlds(),
            (world) -> {
              return JSONUtil.singleObjectPair(
                  String.valueOf(worldMap.get(world.getName())),
                  JSONUtil.mapArray(
                      world.getLoadedChunks(),
                      (chunk) -> {
                        entityCounts.clear();
                        tileEntityCounts.clear();

                        for (Entity entity : chunk.getEntities()) {
                          if (entity.getType() == null) {
                            SpongeImpl.getLogger().error("Entity is not registered {}", entity);
                            continue;
                          }
                          entityCounts.get(entity.getType()).increment();
                        }

                        for (TileEntity tileEntity : chunk.getTileEntities()) {
                          tileEntityCounts.get(tileEntity.getBlock().getType()).increment();
                        }

                        if (tileEntityCounts.isEmpty() && entityCounts.isEmpty()) {
                          return null;
                        }
                        return JSONUtil.arrayOf(
                            chunk.getPosition().getX(),
                            chunk.getPosition().getZ(),
                            JSONUtil.mapArrayToObject(
                                entityCounts.entrySet(),
                                (entry) -> {
                                  if (entry.getKey() == EntityTypes.UNKNOWN) {
                                    return null;
                                  }
                                  this.entityTypeSet.add(entry.getKey());
                                  return JSONUtil.singleObjectPair(
                                      ((SpongeEntityType) entry.getKey()).entityTypeId,
                                      entry.getValue().count());
                                }),
                            JSONUtil.mapArrayToObject(
                                tileEntityCounts.entrySet(),
                                (entry) -> {
                                  this.blockTypeSet.add(entry.getKey());
                                  return JSONUtil.singleObjectPair(
                                      Block.getIdFromBlock((Block) entry.getKey()),
                                      entry.getValue().count());
                                }));
                      }));
            });
  }
Пример #26
0
  public SpongeCoremod() {
    // This MUST be the first line in the constructor, to prevent
    // JavaVersionCheckUtils from being passed through the transformer
    // chain, and thereby triggering Mixin to switch to PREINIT.
    Launch.classLoader.addTransformerExclusion("org.spongepowered.launch.JavaVersionCheckUtils");

    try {
      JavaVersionCheckUtils.ensureJava8();
    } catch (Exception e) {
      e.printStackTrace();
      this.clearSecurityManager();
      Runtime.getRuntime().exit(1);
    }

    // Let's get this party started
    MixinBootstrap.init();
    MixinEnvironment.setCompatibilityLevel(MixinEnvironment.CompatibilityLevel.JAVA_8);

    // Add pre-init mixins
    MixinEnvironment.getEnvironment(Phase.PREINIT)
        .addConfiguration("mixins.forge.preinit.json")
        .registerTokenProviderClass("org.spongepowered.mod.SpongeCoremod$TokenProvider");

    SpongeLaunch.initialize();
    SpongeImpl.getGlobalConfig(); // Load config

    MixinEnvironment.getEnvironment(Phase.INIT)
        .addConfiguration("mixins.forge.init.json")
        .registerTokenProviderClass("org.spongepowered.mod.SpongeCoremod$TokenProvider");

    // Add default mixins
    MixinEnvironment.getDefaultEnvironment()
        .addConfiguration("mixins.common.api.json")
        .addConfiguration("mixins.common.core.json")
        .addConfiguration("mixins.common.bungeecord.json")
        .addConfiguration("mixins.common.eulashutdown.json")
        .addConfiguration("mixins.common.timings.json")
        .addConfiguration("mixins.forge.core.json")
        .addConfiguration("mixins.forge.entityactivation.json")
        .addConfiguration("mixins.forge.bungeecord.json")
        .registerTokenProviderClass("org.spongepowered.mod.SpongeCoremod$TokenProvider");

    Launch.classLoader.addClassLoaderExclusion("org.spongepowered.api.event.cause.Cause");
    Launch.classLoader.addClassLoaderExclusion("org.spongepowered.api.event.cause.NamedCause");
    Launch.classLoader.addClassLoaderExclusion("org.spongepowered.api.event.Cancellable");
    Launch.classLoader.addClassLoaderExclusion(
        "org.spongepowered.api.eventgencore.annotation.PropertySettings");

    // Transformer exclusions
    Launch.classLoader.addTransformerExclusion("ninja.leaping.configurate.");
    Launch.classLoader.addTransformerExclusion("org.apache.commons.lang3.");
    Launch.classLoader.addTransformerExclusion("org.spongepowered.mod.interfaces.IMixinEvent");
    Launch.classLoader.addTransformerExclusion("org.spongepowered.common.launch.");

    SpongeSuperclassRegistry.registerSuperclassModification(
        "org.spongepowered.api.entity.ai.task.AbstractAITask",
        "org.spongepowered.common.entity.ai.SpongeEntityAICommonSuperclass");
    SpongeSuperclassRegistry.registerSuperclassModification(
        "org.spongepowered.api.event.cause.entity.damage.source.common.AbstractDamageSource",
        "org.spongepowered.common.event.damage.SpongeCommonDamageSource");
    SpongeSuperclassRegistry.registerSuperclassModification(
        "org.spongepowered.api.event.cause.entity.damage.source.common.AbstractEntityDamageSource",
        "org.spongepowered.common.event.damage.SpongeCommonEntityDamageSource");
    SpongeSuperclassRegistry.registerSuperclassModification(
        "org.spongepowered.api.event.cause.entity.damage.source.common.AbstractIndirectEntityDamageSource",
        "org.spongepowered.common.event.damage.SpongeCommonIndirectEntityDamageSource");
  }
 public void setLastInteractData(Claim claim) {
   this.lastInteractResult = true;
   this.lastInteractClaim = claim.getID();
   this.lastTickCounter = SpongeImpl.getServer().getTickCounter();
 }
Пример #28
0
  /**
   * Builds an XML report of the timings to be uploaded for parsing.
   *
   * @param sender Who to report to
   */
  static void reportTimings(CommandSource sender) {
    Platform platform = SpongeImpl.getGame().getPlatform();
    JsonObjectBuilder builder =
        JSONUtil.objectBuilder()
            // Get some basic system details about the server
            .add(
                "version",
                platform
                    .getImplementation()
                    .getVersion()
                    .orElse(platform.getMinecraftVersion().getName() + "-DEV"))
            .add("maxplayers", SpongeImpl.getGame().getServer().getMaxPlayers())
            .add("start", TimingsManager.timingStart / 1000)
            .add("end", System.currentTimeMillis() / 1000)
            .add("sampletime", (System.currentTimeMillis() - TimingsManager.timingStart) / 1000);
    if (!TimingsManager.privacy) {
      builder
          .add("server", getServerName())
          .add("motd", SpongeImpl.getGame().getServer().getMotd().toPlain())
          .add("online-mode", SpongeImpl.getGame().getServer().getOnlineMode())
          .add("icon", MinecraftServer.getServer().getServerStatusResponse().getFavicon());
    }

    final Runtime runtime = Runtime.getRuntime();
    RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
    builder.add(
        "system",
        JSONUtil.objectBuilder()
            .add("timingcost", getCost())
            .add("name", System.getProperty("os.name"))
            .add("version", System.getProperty("os.version"))
            .add("jvmversion", System.getProperty("java.version"))
            .add("arch", System.getProperty("os.arch"))
            .add("maxmem", runtime.maxMemory())
            .add("cpu", runtime.availableProcessors())
            .add("runtime", ManagementFactory.getRuntimeMXBean().getUptime())
            .add("flags", RUNTIME_FLAG_JOINER.join(runtimeBean.getInputArguments()))
            .add(
                "gc",
                JSONUtil.mapArrayToObject(
                    ManagementFactory.getGarbageCollectorMXBeans(),
                    (input) -> {
                      return JSONUtil.singleObjectPair(
                          input.getName(),
                          JSONUtil.arrayOf(input.getCollectionCount(), input.getCollectionTime()));
                    })));

    Set<BlockType> blockTypeSet = Sets.newHashSet();
    Set<EntityType> entityTypeSet = Sets.newHashSet();

    int size = HISTORY.size();
    TimingHistory[] history = new TimingHistory[size + 1];
    int i = 0;
    for (TimingHistory timingHistory : HISTORY) {
      blockTypeSet.addAll(timingHistory.blockTypeSet);
      entityTypeSet.addAll(timingHistory.entityTypeSet);
      history[i++] = timingHistory;
    }

    history[i] = new TimingHistory(); // Current snapshot
    blockTypeSet.addAll(history[i].blockTypeSet);
    entityTypeSet.addAll(history[i].entityTypeSet);

    JsonObjectBuilder handlersBuilder = JSONUtil.objectBuilder();
    for (TimingIdentifier.TimingGroup group : TimingIdentifier.GROUP_MAP.values()) {
      for (TimingHandler id : group.handlers) {
        if (!id.timed && !id.isSpecial()) {
          continue;
        }
        handlersBuilder.add(id.id, JSONUtil.arrayOf(group.id, id.name));
      }
    }

    builder.add(
        "idmap",
        JSONUtil.objectBuilder()
            .add(
                "groups",
                JSONUtil.mapArrayToObject(
                    TimingIdentifier.GROUP_MAP.values(),
                    (group) -> {
                      return JSONUtil.singleObjectPair(group.id, group.name);
                    }))
            .add("handlers", handlersBuilder)
            .add(
                "worlds",
                JSONUtil.mapArrayToObject(
                    TimingHistory.worldMap.entrySet(),
                    (entry) -> {
                      return JSONUtil.singleObjectPair(entry.getValue(), entry.getKey());
                    }))
            .add(
                "tileentity",
                JSONUtil.mapArrayToObject(
                    blockTypeSet,
                    (blockType) -> {
                      return JSONUtil.singleObjectPair(
                          Block.getIdFromBlock((Block) blockType), blockType.getId());
                    }))
            .add(
                "entity",
                JSONUtil.mapArrayToObject(
                    entityTypeSet,
                    (entityType) -> {
                      return JSONUtil.singleObjectPair(
                          ((SpongeEntityType) entityType).entityTypeId, entityType.getId());
                    })));

    // Information about loaded plugins

    builder.add(
        "plugins",
        JSONUtil.mapArrayToObject(
            SpongeImpl.getGame().getPluginManager().getPlugins(),
            (plugin) -> {
              return JSONUtil.objectBuilder()
                  .add(
                      plugin.getId(),
                      JSONUtil.objectBuilder()
                          .add("version", plugin.getVersion().orElse(""))
                          .add("description", plugin.getDescription().orElse(""))
                          .add("website", plugin.getUrl().orElse(""))
                          .add("authors", AUTHOR_LIST_JOINER.join(plugin.getAuthors())))
                  .build();
            }));

    // Information on the users Config

    builder.add(
        "config",
        JSONUtil.objectBuilder()
            .add("sponge", serializeConfigNode(SpongeImpl.getGlobalConfig().getRootNode())));

    new TimingsExport(sender, builder.build(), history).start();
  }
Пример #29
0
 private static String getServerName() {
   return SpongeImpl.getPlugin().getName() + " " + SpongeImpl.getPlugin().getVersion().orElse("");
 }
Пример #30
0
  @Override
  public void run() {
    this.sender.sendMessage(Text.of(TextColors.GREEN, "Preparing Timings Report..."));

    this.out.add("data", JSONUtil.mapArray(this.history, TimingHistory::export));

    String response = null;
    try {
      HttpURLConnection con =
          (HttpURLConnection) new URL("http://timings.aikar.co/post").openConnection();
      con.setDoOutput(true);
      con.setRequestProperty(
          "User-Agent",
          "Sponge/" + getServerName() + "/" + InetAddress.getLocalHost().getHostName());
      con.setRequestMethod("POST");
      con.setInstanceFollowRedirects(false);

      OutputStream request =
          new GZIPOutputStream(con.getOutputStream()) {

            {
              this.def.setLevel(7);
            }
          };

      request.write(JSONUtil.toString(this.out).getBytes("UTF-8"));
      request.close();

      response = getResponse(con);

      if (con.getResponseCode() != 302) {
        this.sender.sendMessage(
            Text.of(
                TextColors.RED,
                "Upload Error: " + con.getResponseCode() + ": " + con.getResponseMessage()));
        this.sender.sendMessage(Text.of(TextColors.RED, "Check your logs for more information"));
        if (response != null) {
          SpongeImpl.getLogger().fatal(response);
        }
        return;
      }

      String location = con.getHeaderField("Location");
      this.sender.sendMessage(
          Text.of(
              TextColors.GREEN,
              "View Timings Report: ",
              TextActions.openUrl(new URL(location)),
              location));
      if (!(this.sender instanceof ConsoleSource)) {
        SpongeImpl.getLogger().info("View Timings Report: " + location);
      }

      if (response != null && !response.isEmpty()) {
        SpongeImpl.getLogger().info("Timing Response: " + response);
      }
    } catch (IOException ex) {
      this.sender.sendMessage(
          Text.of(TextColors.RED, "Error uploading timings, check your logs for more information"));
      if (response != null) {
        SpongeImpl.getLogger().fatal(response);
      }
      SpongeImpl.getLogger().fatal("Could not paste timings", ex);
    }
  }