net.minecraftforge.fml.common.FMLCommonHandler Java Examples

The following examples show how to use net.minecraftforge.fml.common.FMLCommonHandler. 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 check out the related API usage on the sidebar.
Example #1
Source File: ServerStateMachine.java    From malmo with 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 File: ServerStateMachine.java    From malmo with 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
Source File: Mobycraft.java    From mobycraft with Apache License 2.0 6 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 #4
Source File: MCPacketHandler.java    From NOVA-Core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #5
Source File: MCRetentionManager.java    From NOVA-Core with GNU Lesser General Public License v3.0 5 votes vote down vote up
public File getBaseDirectory() {
	if (FMLCommonHandler.instance().getSide().isClient()) {
		FMLClientHandler.instance().getClient();
		return FMLClientHandler.instance().getClient().mcDataDir;
	} else {
		return new File(".");
	}
}
 
Example #6
Source File: ForgeMetrics.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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 #7
Source File: ItemHandUpgrade.java    From Cyberware with 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 #8
Source File: ItemHandUpgrade.java    From Cyberware with 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 #9
Source File: AtmosphereHandler.java    From AdvancedRocketry with MIT License 5 votes vote down vote up
/**
 * Unregisters the Atmosphere handler for the dimension given
 * @param dimId the dimension id to register the dimension for
 */
public static void unregisterWorld(int dimId) {
	AtmosphereHandler handler = dimensionOxygen.remove(dimId);
	if(Configuration.enableOxygen && handler != null) {

		MinecraftForge.EVENT_BUS.unregister(handler);
		FMLCommonHandler.instance().bus().unregister(handler);
	}
}
 
Example #10
Source File: ItemCybereyeUpgrade.java    From Cyberware with 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 #11
Source File: ForgeMetrics.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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 #12
Source File: ItemConverter.java    From NOVA-Core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void registerNOVAItem(ItemFactory itemFactory) {
	if (map.containsKey(itemFactory)) {
		// just a safeguard - don't map stuff twice
		return;
	}

	net.minecraft.item.Item itemWrapper;

	Item dummy = itemFactory.build();
	if (dummy instanceof ItemBlock) {
		BlockFactory blockFactory = ((ItemBlock) dummy).blockFactory;
		net.minecraft.block.Block mcBlock = BlockConverter.instance().toNative(blockFactory);
		itemWrapper = net.minecraft.item.Item.getItemFromBlock(mcBlock);
		if (itemWrapper == null) {
			throw new InitializationException("ItemConverter: Missing block: " + itemFactory.getID());
		}
	} else {
		itemWrapper = new FWItem(itemFactory);
	}

	MinecraftItemMapping minecraftItemMapping = new MinecraftItemMapping(itemWrapper, 0);
	map.forcePut(itemFactory, minecraftItemMapping);

	// Don't register ItemBlocks twice
	if (!(dummy instanceof ItemBlock)) {
		NovaMinecraft.proxy.registerItem((FWItem) itemWrapper);
		String itemId = itemFactory.getID();
		if (!itemId.contains(":"))
			itemId = NovaLauncher.instance().flatMap(NovaLauncher::getCurrentMod).map(Mod::id).orElse("nova") + ':' + itemId;
		GameRegistry.register(itemWrapper, new ResourceLocation(itemId));

		if (dummy.components.has(Category.class) && FMLCommonHandler.instance().getSide().isClient()) {
			//Add into creative tab
			Category category = dummy.components.get(Category.class);
			itemWrapper.setCreativeTab(CategoryConverter.instance().toNative(category, itemWrapper));
		}

		Game.logger().info("Registered item: {}", itemFactory.getID());
	}
}
 
Example #13
Source File: ForgeMetrics.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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 #14
Source File: ForgeMetrics.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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 #15
Source File: CraftingKeys.java    From CraftingKeys with MIT License 5 votes vote down vote up
/**
 * This method will be executed while loading.
 *
 * @param event Input Event from FML
 */
@EventHandler
public void load(FMLInitializationEvent event) {

    // Registering
    FMLCommonHandler.instance().bus().register(this);
    MinecraftForge.EVENT_BUS.register(this);
    NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiConfigHandler());
    KeyBindings.init();
    Logger.info("load(e)", "Registered Mod.");

}
 
Example #16
Source File: FaweForge.java    From FastAsyncWorldedit with 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 #17
Source File: PacketSyncWorktable.java    From Wizardry with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 #18
Source File: ForgeMain.java    From FastAsyncWorldedit with 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 #19
Source File: ServerStateMachine.java    From malmo with 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 #20
Source File: ForgeMetrics.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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 #21
Source File: TickHandler.java    From GokiStats with MIT License 5 votes vote down vote up
@SubscribeEvent
@SideOnly(Side.SERVER)
public void serverTick(TickEvent.ServerTickEvent event) {
    if (event.phase == TickEvent.Phase.END) {
        if (tickTimer.get() == GokiConfig.syncTicks) {
            tickTimer.lazySet(0);
            for (EntityPlayerMP player : FMLCommonHandler.instance().getMinecraftServerInstance().getPlayerList().getPlayers()) {
                GokiPacketHandler.CHANNEL.sendTo(new S2CSyncAll(player), player);
            }
        } else {
            tickTimer.getAndIncrement();
        }
    }
}
 
Example #22
Source File: SpaceObject.java    From AdvancedRocketry with MIT License 5 votes vote down vote up
/**
 * Used the amount of fuel passed
 * @param amt
 * @return amount of fuel consumed
 */
public int useFuel(int amt) {
	if(amt > getFuelAmount())
		return 0;

	fuelAmount -= amt;

	if(FMLCommonHandler.instance().getSide().isServer())
		PacketHandler.sendToAll(new PacketStationUpdate(this, Type.FUEL_UPDATE));
	return amt;
}
 
Example #23
Source File: SpaceObject.java    From AdvancedRocketry with 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 #24
Source File: MalmoMod.java    From malmo with 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 #25
Source File: ForgeMetrics.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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 #26
Source File: FaweForge.java    From FastAsyncWorldedit with 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 #27
Source File: ForgeMain.java    From FastAsyncWorldedit with 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 #28
Source File: NEIInitialization.java    From NotEnoughItems with MIT License 5 votes vote down vote up
private static void loadModSubsets() {
    ProgressBar bar = ProgressManager.push("Mod Subsets", ForgeRegistries.ITEMS.getKeys().size());
    HashMap<String, ItemStackSet> modSubsets = new HashMap<>();

    for (Item item : ForgeRegistries.ITEMS) {
        try {
            ResourceLocation ident = item.getRegistryName();
            bar.step(ident.toString());
            if (ident == null) {
                LogHelper.error("Failed to find identifier for: " + item);
                continue;
            }
            String modId = ident.getResourceDomain();
            ItemInfo.itemOwners.put(item, modId);
            ItemStackSet itemset = modSubsets.computeIfAbsent(modId, k -> new ItemStackSet());
            itemset.with(item);
        } catch (Throwable t) {
            LogHelper.errorError("Failed to process mod subset item %s %s", t, String.valueOf(item), String.valueOf(item.getRegistryName()));
        }
    }
    ProgressManager.pop(bar);

    API.addSubset("Mod.Minecraft", modSubsets.remove("minecraft"));
    for (Entry<String, ItemStackSet> entry : modSubsets.entrySet()) {
        ModContainer mc = FMLCommonHandler.instance().findContainerFor(entry.getKey());
        if (mc == null) {
            LogHelper.error("Missing container for " + entry.getKey());
        } else {
            API.addSubset("Mod." + mc.getName(), entry.getValue());
        }
    }
}
 
Example #29
Source File: FaweForge.java    From FastAsyncWorldedit with 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 #30
Source File: ForgeMetrics.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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);
}