Java Code Examples for net.minecraftforge.fml.common.FMLCommonHandler

The following examples show how to use net.minecraftforge.fml.common.FMLCommonHandler. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: malmo   Source File: ServerStateMachine.java    License: MIT License 6 votes vote down vote up
protected boolean checkWatchList()
{
    String[] connected_users = FMLCommonHandler.instance().getMinecraftServerInstance().getOnlinePlayerNames();
    if (connected_users.length < this.userConnectionWatchList.size())
        return false;

    // More detailed check (since there may be non-mission-required connections - eg a human spectator).
    for (String username : this.userConnectionWatchList)
    {
        boolean bFound = false;
        for (int i = 0; i < connected_users.length && !bFound; i++)
        {
            if (connected_users[i].equals(username))
                bFound = true;
        }
        if (!bFound)
            return false;
    }
    return true;
}
 
Example 2
Source Project: malmo   Source File: ServerStateMachine.java    License: MIT License 6 votes vote down vote up
protected void onReceiveMissionInit(MissionInit missionInit)
{
	MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance();
    System.out.println("Mission received: " + missionInit.getMission().getAbout().getSummary());
    TextComponentString txtMission = new TextComponentString("Received mission: " + TextFormatting.BLUE + missionInit.getMission().getAbout().getSummary());
    TextComponentString txtSource = new TextComponentString("Source: " + TextFormatting.GREEN + missionInit.getClientAgentConnection().getAgentIPAddress());
    server.getPlayerList().sendMessage(txtMission);
    server.getPlayerList().sendMessage(txtSource);

    ServerStateMachine.this.currentMissionInit = missionInit;
    // Create the Mission Handlers
    try
    {
        this.ssmachine.initialiseHandlers(missionInit);
    }
    catch (Exception e)
    {
        // TODO: What?
    }
    // Move on to next state:
    episodeHasCompleted(ServerState.BUILDING_WORLD);
}
 
Example 3
@Override
protected void channelRead0(ChannelHandlerContext ctx, PacketAbstract packet) throws Exception {
	INetHandler netHandler = ctx.channel().attr(NetworkRegistry.NET_HANDLER).get();

	switch (FMLCommonHandler.instance().getEffectiveSide()) {
		case CLIENT:
			FMLClientHandler.instance().getClient().addScheduledTask(() -> packet.handleClientSide(NovaMinecraft.proxy.getClientPlayer()));
			break;
		case SERVER:
			FMLCommonHandler.instance().getMinecraftServerInstance().addScheduledTask(() -> packet.handleServerSide(((NetHandlerPlayServer) netHandler).player));
			break;
		default:
			break;
	}

}
 
Example 4
public void serverAboutToStart(FMLServerAboutToStartEvent event) {
	traverse_world_data = null;
	File rootDir = FMLCommonHandler.instance().getSavesDirectory();
	if (!rootDir.exists()) {
		rootDir.mkdir();
	}
	File worldDir = new File(rootDir, event.getServer().getFolderName());
	if (!worldDir.exists()) {
		worldDir.mkdir();
	}
	traverse_world_data = new TraverseWorldVersion(worldDir);

	for (TraverseWorld.TraverseBiomeEntry traverseBiome : TraverseWorld.biomeList) {
		BiomeProvider.allowedBiomes.remove(traverseBiome.getBiome());
		BiomeManager.removeSpawnBiome(traverseBiome.getBiome());
		BiomeManager.removeBiome(traverseBiome.getType(), traverseBiome.getEntry());

		boolean canRegister;

		if (!TraverseConfig.registerBiomesRegardless) {
			traverse_world_data.reloadVersionFile();
			canRegister = VersionUtils.isVersionLessOrEqual(traverseBiome.getVersionAdded(), traverse_world_data.version);
		} else {
			canRegister = true;
		}
		if (canRegister) {
			BiomeManager.addBiome(traverseBiome.getType(), traverseBiome.getEntry());
			if (traverseBiome.hasVillages()) {
				BiomeManager.addVillageBiome(traverseBiome.getBiome(), traverseBiome.canSpawn());
			}
			if (traverseBiome.canSpawn()) {
				BiomeManager.addSpawnBiome(traverseBiome.getBiome());
			}
			BiomeProvider.allowedBiomes.add(traverseBiome.getBiome());
		}
	}
}
 
Example 5
Source Project: FastAsyncWorldedit   Source File: FaweForge.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public String getName(UUID uuid) {
    try {
        GameProfile profile = FMLCommonHandler.instance().getMinecraftServerInstance().getPlayerProfileCache().getProfileByUUID(uuid);
        return profile.getName();
    } catch (Throwable e) {
        return null;
    }
}
 
Example 6
@Override
public IMessage onMessage(PacketRequestUpdateAltar message, MessageContext ctx) {
	if (ctx.side == Side.SERVER) {
		World world = FMLCommonHandler.instance().getMinecraftServerInstance().getWorld(message.dimension);
		TileEntity tileEntity = world.getTileEntity(message.pos);
		if (tileEntity instanceof TileEntityAltar) {
			return new PacketUpdateAltar((TileEntityAltar) tileEntity);
		}
	} else {
		System.out.println("Bad packet (wrong side: CLIENT)!");
	}
	return null;
}
 
Example 7
/**
 * Disables metrics for the server by setting "opt-out" to true in the
 * config file and canceling the metrics task.
 *
 * @throws java.io.IOException
 */
public void disable() throws IOException {
    // Check if the server owner has already set opt-out, if not, set it.
    if (!isOptOut()) {
        configuration.getCategory(Configuration.CATEGORY_GENERAL).get("opt-out").set("true");
        configuration.save();
    }
    FMLCommonHandler.instance().bus().unregister(this);
}
 
Example 8
/**
 * Start measuring statistics. This will immediately create an async
 * repeating task as the plugin and send the initial data to the metrics
 * backend, and then after that it will post in increments of PING_INTERVAL
 * * 1200 ticks.
 *
 * @return True if statistics measuring is running, otherwise false.
 */
public boolean start() {
    // Did we opt out?
    if (isOptOut()) {
        return false;
    }

    FMLCommonHandler.instance().bus().register(this);

    return true;
}
 
Example 9
@SubscribeEvent
@SuppressWarnings("unchecked")
public void onServerPacket(FMLNetworkEvent.ServerCustomPacketEvent event) {
    Packet packet = proxy2packet(event.getPacket());
    if (serverExecutors.containsKey(packet.getClass())) {
        PacketExecutor<Packet, NetHandlerPlayServer> executor = (PacketExecutor<Packet, NetHandlerPlayServer>) serverExecutors.get(packet.getClass());
        NetHandlerPlayServer handler = (NetHandlerPlayServer) event.getHandler();
        IThreadListener threadListener = FMLCommonHandler.instance().getWorldThread(handler);
        if(threadListener.isCallingFromMinecraftThread()) {
            executor.execute(packet, handler);
        } else {
            threadListener.addScheduledTask(() -> executor.execute(packet, handler));
        }
    }
}
 
Example 10
/**
 * Disables metrics for the server by setting "opt-out" to true in the
 * config file and canceling the metrics task.
 *
 * @throws java.io.IOException
 */
public void disable() throws IOException {
    // Check if the server owner has already set opt-out, if not, set it.
    if (!isOptOut()) {
        configuration.getCategory(Configuration.CATEGORY_GENERAL).get("opt-out").set("true");
        configuration.save();
    }
    FMLCommonHandler.instance().bus().unregister(this);
}
 
Example 11
@Nullable
Class<? extends Content> getContentClass(String typeName)
{
    if (typeSides.containsKey(typeName)
        && FMLCommonHandler.instance().getSide() != typeSides.get(typeName))
        return null;

    return types.get(typeName);
}
 
Example 12
Source Project: customstuff4   Source File: ModLoader.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static ContentHelper createHelper(CS4Mod mod)
{
    ModContainer container = FMLCommonHandler.instance().findContainerFor(mod);
    File modDirectory = container.getSource();

    return new ContentHelperImpl(container.getModId(), modDirectory);
}
 
Example 13
Source Project: mobycraft   Source File: Mobycraft.java    License: Apache License 2.0 5 votes vote down vote up
@EventHandler
public void init(FMLInitializationEvent event) {
	injector = Guice.createInjector(new MobycraftModule());

	// Helps render item textures
	mesher = Minecraft.getMinecraft().getRenderItem().getItemModelMesher();

	docker_block = new GenericBlock("docker_block", Material.iron, 5.0F,
			10.0F, "pickaxe", 1, Block.soundTypeMetal);
	registerBlock(docker_block, "docker_block");

	container_wand = new GenericItem("container_wand",
			CreativeTabs.tabTools).setMaxStackSize(1);
	registerItem(container_wand, "container_wand");

	container_essence = new GenericItem("container_essence",
			CreativeTabs.tabMaterials);
	registerItem(container_essence, "container_essence");

	RenderManager render = Minecraft.getMinecraft().getRenderManager();

	registerModEntity(EntityMoby.class, new RenderMoby(), "moby",
			EntityRegistry.findGlobalUniqueEntityId(), 0x24B8EB, 0x008BB8);
	registerModEntity(EntityChaosMonkey.class, new RenderChaosMonkey(),
			"chaos_monkey", EntityRegistry.findGlobalUniqueEntityId(),
			0x8E6400, 0xEAFF00);

	DimensionRegistry.mainRegistry();

	commands = injector.getInstance(MainCommand.class);
	commands.loadConfig();

	MinecraftForge.EVENT_BUS.register(commands);
	FMLCommonHandler.instance().bus().register(commands);

	GameRegistry.addRecipe(new ItemStack(container_wand), " ei", "ese",
			"se ", 'e', container_essence, 'i', Items.iron_ingot, 's',
			Items.stick);
}
 
Example 14
@Override
public void deserialize(NBTTagCompound nbt) {
	if (nbt.hasKey("spell_ring"))
		ring = SpellRing.deserializeRing(nbt.getCompoundTag("spell_ring"));
	if (nbt.hasKey("spell_data"))
		data = SpellData.deserializeData(nbt.getCompoundTag("spell_data"));
	if (nbt.hasKey("world"))
		world = FMLCommonHandler.instance().getMinecraftServerInstance().getWorld(nbt.getInteger("world"));
}
 
Example 15
@Override
public void deserialize(NBTTagCompound nbt) {
	if (nbt.hasKey("spell_ring"))
		ring = SpellRing.deserializeRing(nbt.getCompoundTag("spell_ring"));
	if (nbt.hasKey("spell_data"))
		data = SpellData.deserializeData(nbt.getCompoundTag("spell_data"));
	if (nbt.hasKey("world"))
		world = FMLCommonHandler.instance().getMinecraftServerInstance().getWorld(nbt.getInteger("world"));
}
 
Example 16
@Override
public void handle(@Nonnull MessageContext messageContext) {
	World world = FMLCommonHandler.instance().getMinecraftServerInstance().getWorld(this.world);

	TileEntity entity = world.getTileEntity(pos);
	if (entity instanceof TileMagiciansWorktable) {
		((TileMagiciansWorktable) entity).setCommonModules(commonModules);

		BlockPos sister = ((TileMagiciansWorktable) entity).linkedTable;
		TileEntity sisterTile = world.getTileEntity(sister);
		if (sisterTile instanceof TileMagiciansWorktable) {
			((TileMagiciansWorktable) sisterTile).setCommonModules(commonModules);
		}
	}
}
 
Example 17
/**
 * Disables metrics for the server by setting "opt-out" to true in the
 * config file and canceling the metrics task.
 *
 * @throws java.io.IOException
 */
public void disable() throws IOException {
    // Check if the server owner has already set opt-out, if not, set it.
    if (!isOptOut()) {
        configuration.getCategory(Configuration.CATEGORY_GENERAL).get("opt-out").set("true");
        configuration.save();
    }
    FMLCommonHandler.instance().bus().unregister(this);
}
 
Example 18
/**
 * Start measuring statistics. This will immediately create an async
 * repeating task as the plugin and send the initial data to the metrics
 * backend, and then after that it will post in increments of PING_INTERVAL
 * * 1200 ticks.
 *
 * @return True if statistics measuring is running, otherwise false.
 */
public boolean start() {
    // Did we opt out?
    if (isOptOut()) {
        return false;
    }

    FMLCommonHandler.instance().bus().register(this);

    return true;
}
 
Example 19
Source Project: Cyberware   Source File: ItemCybereyeUpgrade.java    License: MIT License 5 votes vote down vote up
public ItemCybereyeUpgrade(String name, EnumSlot slot, String[] subnames)
{
	super(name, slot, subnames);
	MinecraftForge.EVENT_BUS.register(this);
	FMLCommonHandler.instance().bus().register(this);

}
 
Example 20
Source Project: Cyberware   Source File: ItemHandUpgrade.java    License: MIT License 5 votes vote down vote up
@SubscribeEvent(priority=EventPriority.NORMAL)
public void handleLivingUpdate(CyberwareUpdateEvent event)
{
	EntityLivingBase e = event.getEntityLiving();
	
	ItemStack test = new ItemStack(this, 1, 1);
	if (CyberwareAPI.isCyberwareInstalled(e, test))
	{
		boolean last = getLastClaws(e);
		boolean isEquipped = e.getHeldItemMainhand() == null && 
				(e.getPrimaryHand() == EnumHandSide.RIGHT ? 
						(CyberwareAPI.isCyberwareInstalled(e, new ItemStack(CyberwareContent.cyberlimbs, 1, 1))) : 
						(CyberwareAPI.isCyberwareInstalled(e, new ItemStack(CyberwareContent.cyberlimbs, 1, 0))));
		if (isEquipped && EnableDisableHelper.isEnabled(CyberwareAPI.getCyberware(e, test)))
		{
			this.addUnarmedDamage(e, test);
			lastClaws.put(e.getEntityId(), true);

			if (!last)
			{
				if (FMLCommonHandler.instance().getSide() == Side.CLIENT)
				{
					updateHand(e, true);
				}
			}
		}
		else
		{
			this.removeUnarmedDamage(e, test);
			lastClaws.put(e.getEntityId(), false);
		}
		
	}
	else
	{
		
		lastClaws.put(e.getEntityId(), false);
	}
}
 
Example 21
Source Project: Cyberware   Source File: ItemHandUpgrade.java    License: MIT License 5 votes vote down vote up
@Override
public void use(Entity e, ItemStack stack)
{
	EnableDisableHelper.toggle(stack);
	if (e instanceof EntityLivingBase && FMLCommonHandler.instance().getSide() == Side.CLIENT)
	{
		updateHand((EntityLivingBase) e, false);
	}
}
 
Example 22
/**
 * Start measuring statistics. This will immediately create an async
 * repeating task as the plugin and send the initial data to the metrics
 * backend, and then after that it will post in increments of PING_INTERVAL
 * * 1200 ticks.
 *
 * @return True if statistics measuring is running, otherwise false.
 */
public boolean start() {
    // Did we opt out?
    if (isOptOut()) {
        return false;
    }

    FMLCommonHandler.instance().bus().register(this);

    return true;
}
 
Example 23
Source Project: FastAsyncWorldedit   Source File: ForgeMain.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent event) {
    this.logger = event.getModLog();
    File directory = new File(event.getModConfigurationDirectory() + File.separator + "FastAsyncWorldEdit");
    MinecraftForge.EVENT_BUS.register(this);
    FMLCommonHandler.instance().bus().register(this);
    this.IMP = new FaweForge(this, event.getModLog(), event.getModMetadata(), directory);
    try {
        Class.forName("org.spongepowered.api.Sponge");
        Settings.IMP.QUEUE.PARALLEL_THREADS = 1;
    } catch (Throwable ignore) {}
}
 
Example 24
Source Project: malmo   Source File: ServerStateMachine.java    License: MIT License 5 votes vote down vote up
@Override
protected void execute()
{
	MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance();
	World world = server.getEntityWorld();
    MissionBehaviour handlers = this.ssmachine.getHandlers();
    // Assume the world has been created correctly - now do the necessary building.
    boolean builtOkay = true;
    if (handlers != null && handlers.worldDecorator != null)
    {
        try
        {
            handlers.worldDecorator.buildOnWorld(this.ssmachine.currentMissionInit(), world);
        }
        catch (DecoratorException e)
        {
            // Error attempting to decorate the world - abandon the mission.
            builtOkay = false;
            if (e.getMessage() != null)
                saveErrorDetails(e.getMessage());
            // Tell all the clients to abort:
            Map<String, String>data = new HashMap<String, String>();
            data.put("message", getErrorDetails());
            MalmoMod.safeSendToAll(MalmoMessageType.SERVER_ABORT, data);
            // And abort ourselves:
            episodeHasCompleted(ServerState.ERROR);
        }
    }
    if (builtOkay)
    {
        // Now set up other attributes of the environment (eg weather)
        EnvironmentHelper.setMissionWeather(currentMissionInit(), server.getEntityWorld().getWorldInfo());
        episodeHasCompleted(ServerState.WAITING_FOR_AGENTS_TO_ASSEMBLE);
    }
}
 
Example 25
Source Project: AdvancedRocketry   Source File: SpaceObject.java    License: MIT License 5 votes vote down vote up
/**
 * Adds the passed amount of fuel to the space station
 * @param amt
 * @return amount of fuel used
 */
public int addFuel(int amt) {
	if(amt < 0)
		return amt;

	int oldFuelAmt = fuelAmount;
	fuelAmount = Math.min(fuelAmount + amt, MAX_FUEL);

	amt = fuelAmount - oldFuelAmt;

	if(FMLCommonHandler.instance().getSide().isServer())
		PacketHandler.sendToAll(new PacketStationUpdate(this, Type.FUEL_UPDATE));
	return amt;
}
 
Example 26
Source Project: malmo   Source File: MalmoMod.java    License: MIT License 5 votes vote down vote up
public static void safeSendToAll(MalmoMessageType malmoMessage)
{
    // network.sendToAll() is buggy - race conditions result in the message getting trashed if there is more than one client.
    MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance();
    for (Object player : server.getPlayerList().getPlayers())
    {
        if (player != null && player instanceof EntityPlayerMP)
        {
            // Must construct a new message for each client:
            network.sendTo(new MalmoMod.MalmoMessage(malmoMessage, ""), (EntityPlayerMP)player);
        }
    }
}
 
Example 27
/**
 * Start measuring statistics. This will immediately create an async
 * repeating task as the plugin and send the initial data to the metrics
 * backend, and then after that it will post in increments of PING_INTERVAL
 * * 1200 ticks.
 *
 * @return True if statistics measuring is running, otherwise false.
 */
public boolean start() {
    // Did we opt out?
    if (isOptOut()) {
        return false;
    }

    FMLCommonHandler.instance().bus().register(this);

    return true;
}
 
Example 28
Source Project: FastAsyncWorldedit   Source File: FaweForge.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public UUID getUUID(String name) {
    try {
        GameProfile profile = FMLCommonHandler.instance().getMinecraftServerInstance().getPlayerProfileCache().getGameProfileForUsername(name);
        return profile.getId();
    } catch (Throwable e) {
        return null;
    }
}
 
Example 29
/**
 * Enables metrics for the server by setting "opt-out" to false in the
 * config file and starting the metrics task.
 *
 * @throws java.io.IOException
 */
public void enable() throws IOException {
    // Check if the server owner has already set opt-out, if not, set it.
    if (isOptOut()) {
        configuration.getCategory(Configuration.CATEGORY_GENERAL).get("opt-out").set("false");
        configuration.save();
    }
    // Enable Task, if it is not running
    FMLCommonHandler.instance().bus().register(this);
}
 
Example 30
Source Project: FastAsyncWorldedit   Source File: FaweForge.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public UUID getUUID(String name) {
    try {
        GameProfile profile = FMLCommonHandler.instance().getMinecraftServerInstance().getPlayerProfileCache().getGameProfileForUsername(name);
        return profile.getId();
    } catch (Throwable e) {
        return null;
    }
}