Search in sources :

Example 21 with EntityType

use of org.spongepowered.api.entity.EntityType in project SpongeCommon by SpongePowered.

the class TimingsExport method reportTimings.

/**
 * 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().add("version", platform.getContainer(IMPLEMENTATION).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", Sponge.getServer().getMotd().toPlain()).add("online-mode", Sponge.getServer().getOnlineMode()).add("icon", SpongeImpl.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;
    }
    // Current snapshot
    history[i] = new TimingHistory();
    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) -> {
        if (entityType == EntityTypes.UNKNOWN) {
            return null;
        }
        return JSONUtil.singleObjectPair(TimingsPls.getEntityId(entityType), 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();
}
Also used : SpongeImpl(org.spongepowered.common.SpongeImpl) HttpURLConnection(java.net.HttpURLConnection) JsonObject(com.google.gson.JsonObject) ConsoleSource(org.spongepowered.api.command.source.ConsoleSource) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HISTORY(co.aikar.timings.TimingsManager.HISTORY) URL(java.net.URL) JsonObjectBuilder(co.aikar.util.JSONUtil.JsonObjectBuilder) IMPLEMENTATION(org.spongepowered.api.Platform.Component.IMPLEMENTATION) Platform(org.spongepowered.api.Platform) JsonElement(com.google.gson.JsonElement) InetAddress(java.net.InetAddress) Block(net.minecraft.block.Block) EntityTypes(org.spongepowered.api.entity.EntityTypes) Text(org.spongepowered.api.text.Text) RconSource(org.spongepowered.api.command.source.RconSource) ConfigurationNode(ninja.leaping.configurate.ConfigurationNode) ManagementFactory(java.lang.management.ManagementFactory) TextColors(org.spongepowered.api.text.format.TextColors) OutputStream(java.io.OutputStream) RuntimeMXBean(java.lang.management.RuntimeMXBean) TextActions(org.spongepowered.api.text.action.TextActions) CommandSource(org.spongepowered.api.command.CommandSource) Sponge(org.spongepowered.api.Sponge) Set(java.util.Set) IOException(java.io.IOException) Sets(com.google.common.collect.Sets) JSONUtil(co.aikar.util.JSONUtil) JsonArray(com.google.gson.JsonArray) BlockType(org.spongepowered.api.block.BlockType) Entry(java.util.Map.Entry) EntityType(org.spongepowered.api.entity.EntityType) GZIPOutputStream(java.util.zip.GZIPOutputStream) Joiner(com.google.common.base.Joiner) InputStream(java.io.InputStream) Platform(org.spongepowered.api.Platform) RuntimeMXBean(java.lang.management.RuntimeMXBean) EntityType(org.spongepowered.api.entity.EntityType) BlockType(org.spongepowered.api.block.BlockType) JsonObjectBuilder(co.aikar.util.JSONUtil.JsonObjectBuilder)

Example 22 with EntityType

use of org.spongepowered.api.entity.EntityType in project SpongeCommon by SpongePowered.

the class SelectorResolver method addTypeFilters.

private void addTypeFilters(List<Predicate<Entity>> filters) {
    Selector sel = this.selector;
    Optional<Argument.Invertible<EntityType>> typeOpt = sel.getArgument(ArgumentTypes.ENTITY_TYPE);
    if (typeOpt.isPresent()) {
        Argument.Invertible<EntityType> typeArg = typeOpt.get();
        final boolean inverted = typeArg.isInverted();
        final EntityType type = typeArg.getValue();
        filters.add(input -> inverted ^ input.getType() == type);
    }
}
Also used : EntityType(org.spongepowered.api.entity.EntityType) Argument(org.spongepowered.api.text.selector.Argument) Invertible(org.spongepowered.api.text.selector.Argument.Invertible) Selector(org.spongepowered.api.text.selector.Selector)

Example 23 with EntityType

use of org.spongepowered.api.entity.EntityType in project SpongeCommon by SpongePowered.

the class MixinAnvilChunkLoader method onReadChunkEntity.

/**
 * @author gabizou - January 30th, 2016
 *
 *         Attempts to redirect EntityList spawning an entity. Forge
 *         rewrites this method to handle it in a different method, so this
 *         will not actually inject in SpongeForge.
 *
 * @param compound
 * @param world
 * @return
 */
@Redirect(method = "readChunkEntity", at = @At(value = "INVOKE", target = ENTITY_LIST_CREATE_FROM_NBT), require = 0, expect = 0)
private static Entity onReadChunkEntity(NBTTagCompound compound, World world, Chunk chunk) {
    if ("Minecart".equals(compound.getString(NbtDataUtil.ENTITY_TYPE_ID))) {
        compound.setString(NbtDataUtil.ENTITY_TYPE_ID, EntityMinecart.Type.values()[compound.getInteger(NbtDataUtil.MINECART_TYPE)].getName());
        compound.removeTag(NbtDataUtil.MINECART_TYPE);
    }
    Class<? extends Entity> entityClass = SpongeImplHooks.getEntityClass(new ResourceLocation(compound.getString(NbtDataUtil.ENTITY_TYPE_ID)));
    if (entityClass == null) {
        return null;
    }
    EntityType type = EntityTypeRegistryModule.getInstance().getForClass(entityClass);
    if (type == null) {
        return null;
    }
    NBTTagList positionList = compound.getTagList(NbtDataUtil.ENTITY_POSITION, NbtDataUtil.TAG_DOUBLE);
    NBTTagList rotationList = compound.getTagList(NbtDataUtil.ENTITY_ROTATION, NbtDataUtil.TAG_FLOAT);
    Vector3d position = new Vector3d(positionList.getDoubleAt(0), positionList.getDoubleAt(1), positionList.getDoubleAt(2));
    Vector3d rotation = new Vector3d(rotationList.getFloatAt(0), rotationList.getFloatAt(1), 0);
    Transform<org.spongepowered.api.world.World> transform = new Transform<>((org.spongepowered.api.world.World) world, position, rotation);
    try (StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {
        Sponge.getCauseStackManager().addContext(EventContextKeys.SPAWN_TYPE, SpawnTypes.CHUNK_LOAD);
        ConstructEntityEvent.Pre event = SpongeEventFactory.createConstructEntityEventPre(Sponge.getCauseStackManager().getCurrentCause(), type, transform);
        SpongeImpl.postEvent(event);
        if (event.isCancelled()) {
            return null;
        }
        return EntityList.createEntityFromNBT(compound, world);
    }
}
Also used : World(net.minecraft.world.World) EntityType(org.spongepowered.api.entity.EntityType) NBTTagList(net.minecraft.nbt.NBTTagList) ConstructEntityEvent(org.spongepowered.api.event.entity.ConstructEntityEvent) Vector3d(com.flowpowered.math.vector.Vector3d) StackFrame(org.spongepowered.api.event.CauseStackManager.StackFrame) ResourceLocation(net.minecraft.util.ResourceLocation) Transform(org.spongepowered.api.entity.Transform) Redirect(org.spongepowered.asm.mixin.injection.Redirect)

Example 24 with EntityType

use of org.spongepowered.api.entity.EntityType in project SpongeCommon by SpongePowered.

the class EntitySpawnTest method onInitialization.

@Listener
public void onInitialization(final GameInitializationEvent event) {
    Sponge.getCommandManager().register(this, CommandSpec.builder().arguments(GenericArguments.allOf(GenericArguments.catalogedElement(Text.of("type"), EntityType.class))).executor((src, args) -> {
        if (!(src instanceof Player)) {
            throw new CommandException(Text.of(TextColors.RED, "You must be a player to execute this command!"));
        }
        final List<EntityType> types = new ArrayList<>(args.getAll("type"));
        final int size = types.size();
        if (size == 0) {
            throw new CommandException(Text.of(TextColors.RED, "You must specify at least one entity type to spawn any."));
        }
        final Location location = ((Player) src).getLocation();
        if (size == 1) {
            boolean failed = false;
            final EntityType type = types.get(0);
            final Entity entity = location.createEntity(type);
            try {
                if (location.getExtent().spawnEntity(entity)) {
                    src.sendMessage(Text.of(TextColors.GOLD, "You have successfully spawned a ", TextColors.DARK_GREEN, entity.getTranslation()));
                } else {
                    failed = true;
                }
            } catch (Exception e) {
                failed = true;
            }
            if (failed) {
                throw new CommandException(Text.of(TextColors.RED, "You have failed to spawn a " + type.getId()));
            }
        } else {
            src.sendMessage(Text.of(TextColors.GOLD, "You have spawned the following entities:"));
            location.getExtent().spawnEntities(types.stream().map(location::createEntity).collect(Collectors.toList())).forEach(e -> src.sendMessage(Text.of(TextColors.DARK_GREEN, e.getTranslation())));
        }
        return CommandResult.success();
    }).build(), "spawnspongeentity");
}
Also used : EntityType(org.spongepowered.api.entity.EntityType) Entity(org.spongepowered.api.entity.Entity) Player(org.spongepowered.api.entity.living.player.Player) ArrayList(java.util.ArrayList) CommandException(org.spongepowered.api.command.CommandException) CommandException(org.spongepowered.api.command.CommandException) Location(org.spongepowered.api.world.Location) Listener(org.spongepowered.api.event.Listener)

Example 25 with EntityType

use of org.spongepowered.api.entity.EntityType in project SpongeCommon by SpongePowered.

the class EntityActivationRange method initializeEntityActivationState.

/**
 * These entities are excluded from Activation range checks.
 *
 * @param entity Entity to check
 * @return boolean If it should always tick.
 */
public static boolean initializeEntityActivationState(Entity entity) {
    if (((IMixinWorld) entity.world).isFake()) {
        return true;
    }
    // types that should always be active
    if (entity instanceof EntityPlayer && !SpongeImplHooks.isFakePlayer(entity) || entity instanceof EntityThrowable || entity instanceof EntityDragon || entity instanceof MultiPartEntityPart || entity instanceof EntityWither || entity instanceof EntityFireball || entity instanceof EntityWeatherEffect || entity instanceof EntityTNTPrimed || entity instanceof EntityEnderCrystal || entity instanceof EntityFireworkRocket || // Always tick falling blocks
    entity instanceof EntityFallingBlock) {
        return true;
    }
    EntityActivationRangeCategory config = ((IMixinWorldServer) entity.world).getActiveConfig().getConfig().getEntityActivationRange();
    EntityType type = ((org.spongepowered.api.entity.Entity) entity).getType();
    IModData_Activation spongeEntity = (IModData_Activation) entity;
    if (type == EntityTypes.UNKNOWN || !(type instanceof SpongeEntityType)) {
        return false;
    }
    final SpongeEntityType spongeType = (SpongeEntityType) type;
    final byte activationType = spongeEntity.getActivationType();
    if (!spongeType.isActivationRangeInitialized()) {
        addEntityToConfig(entity.world, spongeType, activationType);
        spongeType.setActivationRangeInitialized(true);
    }
    EntityActivationModCategory entityMod = config.getModList().get(spongeType.getModId().toLowerCase());
    int defaultActivationRange = config.getDefaultRanges().get(activationTypeMappings.get(activationType));
    if (entityMod == null) {
        // use default activation range
        spongeEntity.setActivationRange(defaultActivationRange);
        if (defaultActivationRange <= 0) {
            return true;
        }
        return false;
    } else if (!entityMod.isEnabled()) {
        spongeEntity.setActivationRange(defaultActivationRange);
        return true;
    }
    Integer defaultModActivationRange = entityMod.getDefaultRanges().get(activationTypeMappings.get(activationType));
    Integer entityActivationRange = entityMod.getEntityList().get(type.getName().toLowerCase());
    if (defaultModActivationRange != null && entityActivationRange == null) {
        spongeEntity.setActivationRange(defaultModActivationRange);
        if (defaultModActivationRange <= 0) {
            return true;
        }
        return false;
    } else if (entityActivationRange != null) {
        spongeEntity.setActivationRange(entityActivationRange);
        if (entityActivationRange <= 0) {
            return true;
        }
    }
    return false;
}
Also used : EntityThrowable(net.minecraft.entity.projectile.EntityThrowable) EntityDragon(net.minecraft.entity.boss.EntityDragon) IMixinEntity(org.spongepowered.common.interfaces.entity.IMixinEntity) Entity(net.minecraft.entity.Entity) IModData_Activation(org.spongepowered.common.mixin.plugin.entityactivation.interfaces.IModData_Activation) EntityFallingBlock(net.minecraft.entity.item.EntityFallingBlock) EntityTNTPrimed(net.minecraft.entity.item.EntityTNTPrimed) EntityWeatherEffect(net.minecraft.entity.effect.EntityWeatherEffect) EntityEnderCrystal(net.minecraft.entity.item.EntityEnderCrystal) MultiPartEntityPart(net.minecraft.entity.MultiPartEntityPart) IMixinWorldServer(org.spongepowered.common.interfaces.world.IMixinWorldServer) SpongeEntityType(org.spongepowered.common.entity.SpongeEntityType) EntityType(org.spongepowered.api.entity.EntityType) IMixinWorld(org.spongepowered.common.interfaces.world.IMixinWorld) EntityFireworkRocket(net.minecraft.entity.item.EntityFireworkRocket) SpongeEntityType(org.spongepowered.common.entity.SpongeEntityType) EntityPlayer(net.minecraft.entity.player.EntityPlayer) EntityWither(net.minecraft.entity.boss.EntityWither) EntityActivationRangeCategory(org.spongepowered.common.config.category.EntityActivationRangeCategory) EntityActivationModCategory(org.spongepowered.common.config.category.EntityActivationModCategory) EntityFireball(net.minecraft.entity.projectile.EntityFireball)

Aggregations

EntityType (org.spongepowered.api.entity.EntityType)33 Vector3d (com.flowpowered.math.vector.Vector3d)7 World (net.minecraft.world.World)6 Entity (org.spongepowered.api.entity.Entity)6 Transform (org.spongepowered.api.entity.Transform)6 ConstructEntityEvent (org.spongepowered.api.event.entity.ConstructEntityEvent)6 SpongeEntityType (org.spongepowered.common.entity.SpongeEntityType)4 Entity (net.minecraft.entity.Entity)3 NBTTagCompound (net.minecraft.nbt.NBTTagCompound)3 ResourceLocation (net.minecraft.util.ResourceLocation)3 Player (org.spongepowered.api.entity.living.player.Player)3 CauseStackManager (org.spongepowered.api.event.CauseStackManager)3 World (org.spongepowered.api.world.World)3 Redirect (org.spongepowered.asm.mixin.injection.Redirect)3 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 UUID (java.util.UUID)2 EntityPlayer (net.minecraft.entity.player.EntityPlayer)2 NBTTagList (net.minecraft.nbt.NBTTagList)2