From 95c6fa1b8540d947417aed678e839ea63de30fa7 Mon Sep 17 00:00:00 2001 From: DarkGuardsman Date: Sat, 12 Oct 2013 06:12:59 -0400 Subject: [PATCH] API update --- APIs/basiccomponents/api/BasicRegistry.java | 57 ++ APIs/buildcraft/api/core/IAreaProvider.java | 36 + APIs/buildcraft/api/core/IBox.java | 31 + APIs/buildcraft/api/core/IIconProvider.java | 27 + APIs/buildcraft/api/core/LaserKind.java | 15 + APIs/buildcraft/api/core/SafeTimeTracker.java | 24 +- APIs/buildcraft/api/core/StackWrapper.java | 54 ++ APIs/buildcraft/api/power/PowerHandler.java | 16 +- APIs/dan200/computer/api/IComputerAccess.java | 106 ++- APIs/dan200/computer/api/ILuaContext.java | 53 +- APIs/dan200/computer/api/IMount.java | 41 +- APIs/dan200/computer/api/IPeripheral.java | 172 ++-- APIs/dan200/computer/api/IWritableMount.java | 38 +- .../ic2/api/energy/event/EnergyTileEvent.java | 11 +- .../api/energy/event/EnergyTileLoadEvent.java | 27 +- .../energy/event/EnergyTileUnloadEvent.java | 29 +- APIs/ic2/api/energy/tile/IEnergyAcceptor.java | 11 +- .../ic2/api/energy/tile/IEnergyConductor.java | 14 +- APIs/ic2/api/energy/tile/IEnergyEmitter.java | 7 +- APIs/ic2/api/energy/tile/IEnergySink.java | 26 +- APIs/ic2/api/energy/tile/IEnergySource.java | 10 +- APIs/ic2/api/energy/tile/IEnergyTile.java | 6 +- APIs/ic2/api/energy/tile/IMetaDelegate.java | 19 +- APIs/ic2/api/item/ElectricItem.java | 51 +- APIs/ic2/api/item/IBoxable.java | 4 +- APIs/ic2/api/item/ICustomElectricItem.java | 35 +- APIs/ic2/api/item/IDebuggable.java | 37 +- APIs/ic2/api/item/IElectricItem.java | 22 +- APIs/ic2/api/item/IElectricItemManager.java | 44 +- APIs/ic2/api/item/IItemHudInfo.java | 31 +- APIs/ic2/api/item/IMetalArmor.java | 3 +- APIs/ic2/api/item/ISpecialElectricItem.java | 3 +- APIs/ic2/api/item/ITerraformingBP.java | 7 +- APIs/ic2/api/item/ItemWrapper.java | 49 +- APIs/ic2/api/item/Items.java | 875 +++++++++++------- .../recipe/ICannerBottleRecipeManager.java | 51 + .../recipe/ICannerEnrichRecipeManager.java | 54 ++ .../api/recipe/ICraftingRecipeManager.java | 26 + APIs/ic2/api/recipe/ILiquidAcceptManager.java | 10 + APIs/ic2/api/recipe/IListRecipeManager.java | 36 + .../ic2/api/recipe/IMachineRecipeManager.java | 40 + APIs/ic2/api/recipe/IPatternStorage.java | 15 + APIs/ic2/api/recipe/IRecipeInput.java | 31 + APIs/ic2/api/recipe/IScrapboxManager.java | 13 + .../ic2/api/recipe/ISemiFluidFuelManager.java | 32 + APIs/ic2/api/recipe/RecipeInputItemStack.java | 38 + APIs/ic2/api/recipe/RecipeInputOreDict.java | 45 + APIs/ic2/api/recipe/RecipeOutput.java | 21 + APIs/ic2/api/recipe/Recipes.java | 55 ++ APIs/ic2/api/tile/ExplosionWhitelist.java | 46 + APIs/ic2/api/tile/IEnergyStorage.java | 61 ++ APIs/ic2/api/tile/IWrenchable.java | 59 ++ APIs/org/modstats/IModstatsReporter.java | 5 +- APIs/org/modstats/ModVersionData.java | 157 ++-- APIs/org/modstats/ModsUpdateEvent.java | 48 +- APIs/org/modstats/ModstatInfo.java | 37 +- APIs/org/modstats/Modstats.java | 110 +-- APIs/org/modstats/reporter/v1/Config.java | 66 +- APIs/org/modstats/reporter/v1/DataSender.java | 450 ++++----- APIs/org/modstats/reporter/v1/Reporter.java | 183 ++-- .../compatibility/Compatibility.java | 112 ++- .../TileEntityUniversalConductor.java | 67 +- .../TileEntityUniversalElectrical.java | 314 +++++++ .../compatibility/UniversalNetwork.java | 35 +- .../core/UniversalElectricity.java | 9 +- .../core/electricity/ElectricityDisplay.java | 342 ++++--- .../core/item/ItemElectric.java | 230 ++--- .../prefab/RecipeHelper.java | 192 ++++ .../prefab/network/PacketManager.java | 336 +++++++ .../prefab/tile/IRotatable.java | 21 +- .../prefab/tile/TileEntityElectrical.java | 224 +++++ src/com/builtbroken/common/Vector.java | 42 + src/com/builtbroken/common/Vector2.java | 31 + src/com/builtbroken/common/Vector3.java | 31 + src/com/builtbroken/common/Vector4.java | 26 + .../builtbroken/common/animation/Joint.java | 63 ++ .../common/animation/Skeleton.java | 14 + .../common/debug/TileEntityInfSupply.java | 2 +- 78 files changed, 4147 insertions(+), 1624 deletions(-) create mode 100644 APIs/basiccomponents/api/BasicRegistry.java create mode 100644 APIs/buildcraft/api/core/IAreaProvider.java create mode 100644 APIs/buildcraft/api/core/IBox.java create mode 100644 APIs/buildcraft/api/core/IIconProvider.java create mode 100644 APIs/buildcraft/api/core/LaserKind.java create mode 100644 APIs/buildcraft/api/core/StackWrapper.java create mode 100644 APIs/ic2/api/recipe/ICannerBottleRecipeManager.java create mode 100644 APIs/ic2/api/recipe/ICannerEnrichRecipeManager.java create mode 100644 APIs/ic2/api/recipe/ICraftingRecipeManager.java create mode 100644 APIs/ic2/api/recipe/ILiquidAcceptManager.java create mode 100644 APIs/ic2/api/recipe/IListRecipeManager.java create mode 100644 APIs/ic2/api/recipe/IMachineRecipeManager.java create mode 100644 APIs/ic2/api/recipe/IPatternStorage.java create mode 100644 APIs/ic2/api/recipe/IRecipeInput.java create mode 100644 APIs/ic2/api/recipe/IScrapboxManager.java create mode 100644 APIs/ic2/api/recipe/ISemiFluidFuelManager.java create mode 100644 APIs/ic2/api/recipe/RecipeInputItemStack.java create mode 100644 APIs/ic2/api/recipe/RecipeInputOreDict.java create mode 100644 APIs/ic2/api/recipe/RecipeOutput.java create mode 100644 APIs/ic2/api/recipe/Recipes.java create mode 100644 APIs/ic2/api/tile/ExplosionWhitelist.java create mode 100644 APIs/ic2/api/tile/IEnergyStorage.java create mode 100644 APIs/ic2/api/tile/IWrenchable.java create mode 100644 APIs/universalelectricity/compatibility/TileEntityUniversalElectrical.java create mode 100644 APIs/universalelectricity/prefab/RecipeHelper.java create mode 100644 APIs/universalelectricity/prefab/network/PacketManager.java create mode 100644 APIs/universalelectricity/prefab/tile/TileEntityElectrical.java create mode 100644 src/com/builtbroken/common/Vector.java create mode 100644 src/com/builtbroken/common/Vector2.java create mode 100644 src/com/builtbroken/common/Vector3.java create mode 100644 src/com/builtbroken/common/Vector4.java create mode 100644 src/com/builtbroken/common/animation/Joint.java create mode 100644 src/com/builtbroken/common/animation/Skeleton.java diff --git a/APIs/basiccomponents/api/BasicRegistry.java b/APIs/basiccomponents/api/BasicRegistry.java new file mode 100644 index 000000000..0ea72ed3b --- /dev/null +++ b/APIs/basiccomponents/api/BasicRegistry.java @@ -0,0 +1,57 @@ +package basiccomponents.api; + +import java.util.HashSet; +import java.util.Set; + +/** + * This should be the only class you include in your mod. If your mod is a coremod, feel free to + * download Basic Components Core directly during run-time. + * + * @author Calclavia + */ + +public class BasicRegistry +{ + public static final Set requests = new HashSet(); + + /** + * @param request - Name of the item/block to register. Use the EXACT FIELD NAME of the + * BasicComponents.java field. + */ + public static void register(String request) + { + requests.add(request); + } + + /** + * Requests all items in Basic Components. + */ + public static void requestAll() + { + register("ingotCopper"); + register("ingotTin"); + + register("oreCopper"); + register("oreTin"); + + register("ingotSteel"); + register("dustSteel"); + register("plateSteel"); + + register("ingotBronze"); + register("dustBronze"); + register("plateBronze"); + + register("plateCopper"); + register("plateTin"); + register("plateIron"); + register("plateGold"); + + register("circuitBasic"); + register("circuitAdvanced"); + register("circuitElite"); + + register("motor"); + register("wrench"); + } +} diff --git a/APIs/buildcraft/api/core/IAreaProvider.java b/APIs/buildcraft/api/core/IAreaProvider.java new file mode 100644 index 000000000..cad9e2111 --- /dev/null +++ b/APIs/buildcraft/api/core/IAreaProvider.java @@ -0,0 +1,36 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.core; + +/** + * To be implemented by TileEntities able to provide a square area on the world, typically + * BuildCraft markers. + */ +public interface IAreaProvider +{ + + public int xMin(); + + public int yMin(); + + public int zMin(); + + public int xMax(); + + public int yMax(); + + public int zMax(); + + /** + * Remove from the world all objects used to define the area. + */ + public void removeFromWorld(); + +} diff --git a/APIs/buildcraft/api/core/IBox.java b/APIs/buildcraft/api/core/IBox.java new file mode 100644 index 000000000..a6f95cae7 --- /dev/null +++ b/APIs/buildcraft/api/core/IBox.java @@ -0,0 +1,31 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.core; + +import net.minecraft.world.World; + +public interface IBox +{ + + public void expand(int amount); + + public void contract(int amount); + + public boolean contains(int x, int y, int z); + + public Position pMin(); + + public Position pMax(); + + public void createLasers(World world, LaserKind kind); + + public void deleteLasers(); + +} diff --git a/APIs/buildcraft/api/core/IIconProvider.java b/APIs/buildcraft/api/core/IIconProvider.java new file mode 100644 index 000000000..3a249e041 --- /dev/null +++ b/APIs/buildcraft/api/core/IIconProvider.java @@ -0,0 +1,27 @@ +package buildcraft.api.core; + +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.util.Icon; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +public interface IIconProvider +{ + + /** + * @param iconIndex + * @return + */ + @SideOnly(Side.CLIENT) + public Icon getIcon(int iconIndex); + + /** + * A call for the provider to register its Icons. This may be called multiple times but should + * only be executed once per provider + * + * @param iconRegister + */ + @SideOnly(Side.CLIENT) + public void registerIcons(IconRegister iconRegister); + +} diff --git a/APIs/buildcraft/api/core/LaserKind.java b/APIs/buildcraft/api/core/LaserKind.java new file mode 100644 index 000000000..520d6511c --- /dev/null +++ b/APIs/buildcraft/api/core/LaserKind.java @@ -0,0 +1,15 @@ +/** + * Copyright (c) SpaceToad, 2011 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ + +package buildcraft.api.core; + +public enum LaserKind +{ + Red, Blue, Stripes +} diff --git a/APIs/buildcraft/api/core/SafeTimeTracker.java b/APIs/buildcraft/api/core/SafeTimeTracker.java index 628f4df76..cee37abe9 100644 --- a/APIs/buildcraft/api/core/SafeTimeTracker.java +++ b/APIs/buildcraft/api/core/SafeTimeTracker.java @@ -1,12 +1,10 @@ -/** - * Copyright (c) SpaceToad, 2011 - * http://www.mod-buildcraft.com - * - * BuildCraft is distributed under the terms of the Minecraft Mod Public - * License 1.0, or MMPL. Please check the contents of the license located in +/** + * Copyright (c) SpaceToad, 2011 http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public License + * 1.0, or MMPL. Please check the contents of the license located in * http://www.mod-buildcraft.com/MMPL-1.0.txt */ - package buildcraft.api.core; import net.minecraft.world.World; @@ -15,8 +13,7 @@ public class SafeTimeTracker { private long lastMark = Long.MIN_VALUE; - private long duration = 0; - private boolean marked; + private long duration = -1; /** * Return true if a given delay has passed since last time marked was called successfully. @@ -26,7 +23,7 @@ public class SafeTimeTracker if (world == null) return false; - long currentTime = world.getWorldTime(); + long currentTime = world.getTotalWorldTime(); if (currentTime < lastMark) { @@ -36,8 +33,7 @@ public class SafeTimeTracker else if (lastMark + delay <= currentTime) { duration = currentTime - lastMark; - lastMark = world.getWorldTime(); - marked = true; + lastMark = currentTime; return true; } else @@ -47,11 +43,11 @@ public class SafeTimeTracker public long durationOfLastDelay() { - return marked ? duration : 0; + return duration > 0 ? duration : 0; } public void markTime(World world) { - lastMark = world.getWorldTime(); + lastMark = world.getTotalWorldTime(); } } diff --git a/APIs/buildcraft/api/core/StackWrapper.java b/APIs/buildcraft/api/core/StackWrapper.java new file mode 100644 index 000000000..2f354719a --- /dev/null +++ b/APIs/buildcraft/api/core/StackWrapper.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) SpaceToad, 2011-2012 + * http://www.mod-buildcraft.com + * + * BuildCraft is distributed under the terms of the Minecraft Mod Public + * License 1.0, or MMPL. Please check the contents of the license located in + * http://www.mod-buildcraft.com/MMPL-1.0.txt + */ +package buildcraft.api.core; + +import net.minecraft.item.ItemStack; + +/** + * + * @author CovertJaguar + */ +public class StackWrapper +{ + + public final ItemStack stack; + + public StackWrapper(ItemStack stack) + { + this.stack = stack; + } + + @Override + public int hashCode() + { + int hash = 5; + hash = 67 * hash + stack.itemID; + hash = 67 * hash + stack.getItemDamage(); + if (stack.stackTagCompound != null) + hash = 67 * hash + stack.stackTagCompound.hashCode(); + return hash; + } + + @Override + public boolean equals(Object obj) + { + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final StackWrapper other = (StackWrapper) obj; + if (stack.itemID != other.stack.itemID) + return false; + if (stack.getHasSubtypes() && stack.getItemDamage() != other.stack.getItemDamage()) + return false; + if (stack.stackTagCompound != null && !stack.stackTagCompound.equals(other.stack.stackTagCompound)) + return false; + return true; + } +} diff --git a/APIs/buildcraft/api/power/PowerHandler.java b/APIs/buildcraft/api/power/PowerHandler.java index 6a247d879..2969dd628 100644 --- a/APIs/buildcraft/api/power/PowerHandler.java +++ b/APIs/buildcraft/api/power/PowerHandler.java @@ -86,7 +86,7 @@ public final class PowerHandler } } - public static final PerditionCalculator DEFUALT_PERDITION = new PerditionCalculator(); + public static final PerditionCalculator DEFAULT_PERDITION = new PerditionCalculator(); private float minEnergyReceived; private float maxEnergyReceived; private float maxEnergyStored; @@ -106,6 +106,7 @@ public final class PowerHandler this.receptor = receptor; this.type = type; this.receiver = new PowerReceiver(); + this.perdition = DEFAULT_PERDITION; } public PowerReceiver getPowerReceiver() @@ -179,19 +180,21 @@ public final class PowerHandler /** * Allows you to define a new PerditionCalculator class to handler perdition calculations. * - * For example if you want exponentially increasing loss bases on amount stored. + * For example if you want exponentially increasing loss based on amount stored. * * @param perdition */ public void setPerdition(PerditionCalculator perdition) { + if (perdition == null) + perdition = DEFAULT_PERDITION; this.perdition = perdition; } public PerditionCalculator getPerdition() { if (perdition == null) - return DEFUALT_PERDITION; + return DEFAULT_PERDITION; return perdition; } @@ -215,13 +218,9 @@ public final class PowerHandler { float newEnergy = getPerdition().applyPerdition(this, energyStored, perditionTracker.durationOfLastDelay()); if (newEnergy == 0 || newEnergy < energyStored) - { energyStored = newEnergy; - } else - { - energyStored = DEFUALT_PERDITION.applyPerdition(this, energyStored, perditionTracker.durationOfLastDelay()); - } + energyStored = DEFAULT_PERDITION.applyPerdition(this, energyStored, perditionTracker.durationOfLastDelay()); validateEnergy(); } } @@ -366,6 +365,7 @@ public final class PowerHandler */ public float powerRequest() { + update(); return Math.min(maxEnergyReceived, maxEnergyStored - energyStored); } diff --git a/APIs/dan200/computer/api/IComputerAccess.java b/APIs/dan200/computer/api/IComputerAccess.java index ff086a344..d49643b84 100644 --- a/APIs/dan200/computer/api/IComputerAccess.java +++ b/APIs/dan200/computer/api/IComputerAccess.java @@ -6,83 +6,103 @@ package dan200.computer.api; +import net.minecraft.world.World; + /** - * The interface passed to peripherals by computers or turtles, providing methods - * that they can call. This should not be implemented by your classes. Do not interact - * with computers except via this interface. + * The interface passed to peripherals by computers or turtles, providing methods that they can + * call. This should not be implemented by your classes. Do not interact with computers except via + * this interface. */ public interface IComputerAccess { /** * Mount a mount onto the computers' file system in a read only mode.
- * @param desiredLoction The location on the computer's file system where you would like the mount to be mounted. - * @param mount The mount object to mount on the computer. These can be obtained by calling ComputerCraftAPI.createSaveDirMount(), ComputerCraftAPI.createResourceMount() or by creating your own objects that implement the IMount interface. - * @return The location on the computer's file system where you the mount was actually mounted, this may be different from desiredLocation if there was already a file in the desired location. Store this value if you wish to unmount the mount later. + * + * @param desiredLoction The location on the computer's file system where you would like the + * mount to be mounted. + * @param mount The mount object to mount on the computer. These can be obtained by calling + * ComputerCraftAPI.createSaveDirMount(), ComputerCraftAPI.createResourceMount() or by creating + * your own objects that implement the IMount interface. + * @return The location on the computer's file system where you the mount was actually mounted, + * this may be different from desiredLocation if there was already a file in the desired + * location. Store this value if you wish to unmount the mount later. * @see ComputerCraftAPI#createSaveDirMount(World, String) * @see ComputerCraftAPI#createResourceMount(Class, String, String) * @see #mountWritable(String, IWritableMount) * @see #unmount(String) * @see IMount */ - public String mount( String desiredLocation, IMount mount ); - + public String mount(String desiredLocation, IMount mount); + /** * Mount a mount onto the computers' file system in a writable mode.
- * @param desiredLoction The location on the computer's file system where you would like the mount to be mounted. - * @param mount The mount object to mount on the computer. These can be obtained by calling ComputerCraftAPI.createSaveDirMount() or by creating your own objects that implement the IWritableMount interface. - * @return The location on the computer's file system where you the mount was actually mounted, this may be different from desiredLocation if there was already a file in the desired location. Store this value if you wish to unmount the mount later. + * + * @param desiredLoction The location on the computer's file system where you would like the + * mount to be mounted. + * @param mount The mount object to mount on the computer. These can be obtained by calling + * ComputerCraftAPI.createSaveDirMount() or by creating your own objects that implement the + * IWritableMount interface. + * @return The location on the computer's file system where you the mount was actually mounted, + * this may be different from desiredLocation if there was already a file in the desired + * location. Store this value if you wish to unmount the mount later. * @see ComputerCraftAPI#createSaveDirMount(World, String) * @see ComputerCraftAPI#createResourceMount(Class, String, String) * @see #mount(String, IMount) * @see #unmount(String) * @see IMount */ - public String mountWritable( String desiredLocation, IWritableMount mount ); - + public String mountWritable(String desiredLocation, IWritableMount mount); + /** - * Unmounts a directory previously mounted onto the computers file system by mount() or mountWritable().
- * When a directory is unmounted, it will disappear from the computers file system, and the user will no longer be able to - * access it. All directories mounted by a mount or mountWritable are automatically unmounted when the peripheral - * is attached if they have not been explicitly unmounted. - * @param location The desired location in the computers file system of the directory to unmount. - * This must be the location of a directory previously mounted by mount() or mountWritable(), as - * indicated by their return value. - * @see #mount(String, IMount) - * @see #mountWritable(String, IWritableMount) + * Unmounts a directory previously mounted onto the computers file system by mount() or + * mountWritable().
+ * When a directory is unmounted, it will disappear from the computers file system, and the user + * will no longer be able to access it. All directories mounted by a mount or mountWritable are + * automatically unmounted when the peripheral is attached if they have not been explicitly + * unmounted. + * + * @param location The desired location in the computers file system of the directory to + * unmount. This must be the location of a directory previously mounted by mount() or + * mountWritable(), as indicated by their return value. + * @see #mount(String, IMount) + * @see #mountWritable(String, IWritableMount) */ - public void unmount( String location ); - + public void unmount(String location); + /** * Returns the numerical ID of this computer.
- * This is the same number obtained by calling os.getComputerID() or running the "id" program from lua, - * and is guarunteed unique. This number will be positive. - * @return The identifier. + * This is the same number obtained by calling os.getComputerID() or running the "id" program + * from lua, and is guarunteed unique. This number will be positive. + * + * @return The identifier. */ - public int getID(); + public int getID(); /** * Causes an event to be raised on this computer, which the computer can respond to by calling * os.pullEvent(). This can be used to notify the computer when things happen in the world or to * this peripheral. - * @param event A string identifying the type of event that has occurred, this will be - * returned as the first value from os.pullEvent(). It is recommended that you - * you choose a name that is unique, and recognisable as originating from your - * peripheral. eg: If your peripheral type is "button", a suitable event would be - * "button_pressed". - * @param arguments In addition to a name, you may pass an array of extra arguments to the event, that will - * be supplied as extra return values to os.pullEvent(). Objects in the array will be converted - * to lua data types in the same fashion as the return values of IPeripheral.callMethod().
- * You may supply null to indicate that no arguments are to be supplied. + * + * @param event A string identifying the type of event that has occurred, this will be returned + * as the first value from os.pullEvent(). It is recommended that you you choose a name that is + * unique, and recognisable as originating from your peripheral. eg: If your peripheral type is + * "button", a suitable event would be "button_pressed". + * @param arguments In addition to a name, you may pass an array of extra arguments to the + * event, that will be supplied as extra return values to os.pullEvent(). Objects in the array + * will be converted to lua data types in the same fashion as the return values of + * IPeripheral.callMethod().
+ * You may supply null to indicate that no arguments are to be supplied. * @see IPeripheral#callMethod */ - public void queueEvent( String event, Object[] arguments ); + public void queueEvent(String event, Object[] arguments); /** - * Get a string, unique to the computer, by which the computer refers to this peripheral. - * For directly attached peripherals this will be "left","right","front","back",etc, but - * for peripherals attached remotely it will be different. It is good practice to supply - * this string when raising events to the computer, so that the computer knows from - * which peripheral the event came. + * Get a string, unique to the computer, by which the computer refers to this peripheral. For + * directly attached peripherals this will be "left","right","front","back",etc, but for + * peripherals attached remotely it will be different. It is good practice to supply this string + * when raising events to the computer, so that the computer knows from which peripheral the + * event came. + * * @return A string unique to the computer, but not globally. */ public String getAttachmentName(); diff --git a/APIs/dan200/computer/api/ILuaContext.java b/APIs/dan200/computer/api/ILuaContext.java index eb3193905..b057f7799 100644 --- a/APIs/dan200/computer/api/ILuaContext.java +++ b/APIs/dan200/computer/api/ILuaContext.java @@ -8,38 +8,55 @@ package dan200.computer.api; /** * An interface passed to peripherals and ILuaObjects' by computers or turtles, providing methods - * that allow the peripheral call to wait for events before returning, just like in lua. - * This is very useful if you need to signal work to be performed on the main thread, and don't want to return - * until the work has been completed. + * that allow the peripheral call to wait for events before returning, just like in lua. This is + * very useful if you need to signal work to be performed on the main thread, and don't want to + * return until the work has been completed. */ public interface ILuaContext { /** - * Wait for an event to occur on the computer, suspending the thread until it arises. This method is exactly equivalent to os.pullEvent() in lua. + * Wait for an event to occur on the computer, suspending the thread until it arises. This + * method is exactly equivalent to os.pullEvent() in lua. + * * @param filter A specific event to wait for, or null to wait for any event - * @return An object array containing the name of the event that occurred, and any event parameters - * @throws Exception If the user presses CTRL+T to terminate the current program while pullEvent() is waiting for an event, a "Terminated" exception will be thrown here. - * Do not attempt to block this exception, unless you wish to prevent termination, which is not recommended. - * @throws InterruptedException If the user shuts down or reboots the computer while pullEvent() is waiting for an event, InterruptedException will be thrown. This exception must not be caught or intercepted, or the computer will leak memory and end up in a broken state. + * @return An object array containing the name of the event that occurred, and any event + * parameters + * @throws Exception If the user presses CTRL+T to terminate the current program while + * pullEvent() is waiting for an event, a "Terminated" exception will be thrown here. Do not + * attempt to block this exception, unless you wish to prevent termination, which is not + * recommended. + * @throws InterruptedException If the user shuts down or reboots the computer while pullEvent() + * is waiting for an event, InterruptedException will be thrown. This exception must not be + * caught or intercepted, or the computer will leak memory and end up in a broken state. */ - public Object[] pullEvent( String filter ) throws Exception, InterruptedException; - + public Object[] pullEvent(String filter) throws Exception, InterruptedException; + /** - * The same as pullEvent(), except "terminated" events are ignored. Only use this if you want to prevent program termination, which is not recommended. This method is exactly equivalent to os.pullEventRaw() in lua. + * The same as pullEvent(), except "terminated" events are ignored. Only use this if you want to + * prevent program termination, which is not recommended. This method is exactly equivalent to + * os.pullEventRaw() in lua. + * * @param filter A specific event to wait for, or null to wait for any event - * @return An object array containing the name of the event that occurred, and any event parameters - * @throws InterruptedException If the user shuts down or reboots the computer while pullEventRaw() is waiting for an event, InterruptedException will be thrown. This exception must not be caught or intercepted, or the computer will leak memory and end up in a broken state. + * @return An object array containing the name of the event that occurred, and any event + * parameters + * @throws InterruptedException If the user shuts down or reboots the computer while + * pullEventRaw() is waiting for an event, InterruptedException will be thrown. This exception + * must not be caught or intercepted, or the computer will leak memory and end up in a broken + * state. * @see #pullEvent(String) */ - public Object[] pullEventRaw( String filter ) throws InterruptedException; + public Object[] pullEventRaw(String filter) throws InterruptedException; - /** - * Yield the current coroutine with some arguments until it is resumed. This method is exactly equivalent to coroutine.yield() in lua. Use pullEvent() if you wish to wait for events. + * Yield the current coroutine with some arguments until it is resumed. This method is exactly + * equivalent to coroutine.yield() in lua. Use pullEvent() if you wish to wait for events. + * * @param arguments An object array containing the arguments to pass to coroutine.yield() * @return An object array containing the return values from coroutine.yield() - * @throws InterruptedException If the user shuts down or reboots the computer the coroutine is suspended, InterruptedException will be thrown. This exception must not be caught or intercepted, or the computer will leak memory and end up in a broken state. + * @throws InterruptedException If the user shuts down or reboots the computer the coroutine is + * suspended, InterruptedException will be thrown. This exception must not be caught or + * intercepted, or the computer will leak memory and end up in a broken state. * @see #pullEvent(String) */ - public Object[] yield( Object[] arguments ) throws InterruptedException; + public Object[] yield(Object[] arguments) throws InterruptedException; } diff --git a/APIs/dan200/computer/api/IMount.java b/APIs/dan200/computer/api/IMount.java index 69ff32314..ccf28dfbb 100644 --- a/APIs/dan200/computer/api/IMount.java +++ b/APIs/dan200/computer/api/IMount.java @@ -10,9 +10,14 @@ import java.io.IOException; import java.io.InputStream; import java.util.List; +import net.minecraft.world.World; + /** - * Represents a read only part of a virtual filesystem that can be mounted onto a computer using IComputerAccess.mount(). - * Ready made implementations of this interface can be created using ComputerCraftAPI.createSaveDirMount() or ComputerCraftAPI.createResourceMount(), or you're free to implement it yourselves! + * Represents a read only part of a virtual filesystem that can be mounted onto a computer using + * IComputerAccess.mount(). Ready made implementations of this interface can be created using + * ComputerCraftAPI.createSaveDirMount() or ComputerCraftAPI.createResourceMount(), or you're free + * to implement it yourselves! + * * @see ComputerCraftAPI#createSaveDirMount(World, String) * @see ComputerCraftAPI#createResourceMount(Class, String, String) * @see IComputerAccess#mount(String, IMount) @@ -22,36 +27,46 @@ public interface IMount { /** * Returns whether a file with a given path exists or not. - * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram" + * + * @param path A file path in normalised format, relative to the mount location. ie: + * "programs/myprogram" * @return true if the file exists, false otherwise */ - public boolean exists( String path ) throws IOException; + public boolean exists(String path) throws IOException; /** * Returns whether a file with a given path is a directory or not. - * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprograms" + * + * @param path A file path in normalised format, relative to the mount location. ie: + * "programs/myprograms" * @return true if the file exists and is a directory, false otherwise */ - public boolean isDirectory( String path ) throws IOException; + public boolean isDirectory(String path) throws IOException; /** * Returns the file names of all the files in a directory. - * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprograms" + * + * @param path A file path in normalised format, relative to the mount location. ie: + * "programs/myprograms" * @param contents A list of strings. Add all the file names to this list */ - public void list( String path, List contents ) throws IOException; + public void list(String path, List contents) throws IOException; /** * Returns the size of a file with a given path, in bytes - * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram" + * + * @param path A file path in normalised format, relative to the mount location. ie: + * "programs/myprogram" * @return the size of the file, in bytes */ - public long getSize( String path ) throws IOException; - + public long getSize(String path) throws IOException; + /** * Opens a file with a given path, and returns an inputstream representing it's contents. - * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram" + * + * @param path A file path in normalised format, relative to the mount location. ie: + * "programs/myprogram" * @return a stream representing the contents of the file */ - public InputStream openForRead( String path ) throws IOException; + public InputStream openForRead(String path) throws IOException; } diff --git a/APIs/dan200/computer/api/IPeripheral.java b/APIs/dan200/computer/api/IPeripheral.java index 672431809..18e97b6fc 100644 --- a/APIs/dan200/computer/api/IPeripheral.java +++ b/APIs/dan200/computer/api/IPeripheral.java @@ -7,100 +7,108 @@ package dan200.computer.api; /** - * The interface that defines a peripheral. This should be implemented by the - * TileEntity of any block that you wish to be interacted with by - * computer or turtle. + * The interface that defines a peripheral. This should be implemented by the TileEntity of any + * block that you wish to be interacted with by computer or turtle. */ public interface IPeripheral { /** - * Should return a string that uniquely identifies this type of peripheral. - * This can be queried from lua by calling peripheral.getType() - * @return A string identifying the type of peripheral. + * Should return a string that uniquely identifies this type of peripheral. This can be queried + * from lua by calling peripheral.getType() + * + * @return A string identifying the type of peripheral. */ - public String getType(); - - /** - * Should return an array of strings that identify the methods that this - * peripheral exposes to Lua. This will be called once before each attachment, - * and should not change when called multiple times. - * @return An array of strings representing method names. - * @see #callMethod - */ - public String[] getMethodNames(); - - /** - * This is called when a lua program on an attached computer calls peripheral.call() with - * one of the methods exposed by getMethodNames().
- *
- * Be aware that this will be called from the ComputerCraft Lua thread, and must be thread-safe - * when interacting with minecraft objects. - * @param computer The interface to the computer that is making the call. Remember that multiple - * computers can be attached to a peripheral at once. - * @param context The context of the currently running lua thread. This can be used to wait for events - * or otherwise yield. - * @param method An integer identifying which of the methods from getMethodNames() the computer - * wishes to call. The integer indicates the index into the getMethodNames() table - * that corresponds to the string passed into peripheral.call() - * @param arguments An array of objects, representing the arguments passed into peripheral.call().
- * Lua values of type "string" will be represented by Object type String.
- * Lua values of type "number" will be represented by Object type Double.
- * Lua values of type "boolean" will be represented by Object type Boolean.
- * Lua values of any other type will be represented by a null object.
- * This array will be empty if no arguments are passed. - * @return An array of objects, representing values you wish to return to the lua program.
- * Integers, Doubles, Floats, Strings, Booleans and null be converted to their corresponding lua type.
- * All other types will be converted to nil.
- * You may return null to indicate no values should be returned. - * @throws Exception If you throw any exception from this function, a lua error will be raised with the - * same message as your exception. Use this to throw appropriate errors if the wrong - * arguments are supplied to your method. - * @see #getMethodNames - */ - public Object[] callMethod( IComputerAccess computer, ILuaContext context, int method, Object[] arguments ) throws Exception; - - /** - * Is called before the computer attempts to attach to the peripheral, and should return whether to allow - * the attachment. Use this to restrict the number of computers that can attach, or to limit attachments to - * certain world directions.
- * If true is returned, attach() will be called shortly afterwards, and the computer will be able to make method calls. - * If false is returned, attach() will not be called, and the peripheral will be invisible to the computer. - * @param side The world direction (0=bottom, 1=top, etc) that the computer lies relative to the peripheral. - * @return Whether to allow the attachment, as a boolean. - * @see #attach - */ - public boolean canAttachToSide( int side ); + public String getType(); /** - * Is called when canAttachToSide has returned true, and a computer is attaching to the peripheral. - * This will occur when a peripheral is placed next to an active computer, when a computer is turned on next to a peripheral, - * or when a turtle travels into a square next to a peripheral. - * Between calls to attach() and detach(), the attached computer can make method calls on the peripheral using peripheral.call(). - * This method can be used to keep track of which computers are attached to the peripheral, or to take action when attachment - * occurs.
- *
- * Be aware that this will be called from the ComputerCraft Lua thread, and must be thread-safe - * when interacting with minecraft objects. - * @param computer The interface to the computer that is being attached. Remember that multiple - * computers can be attached to a peripheral at once. - * @see #canAttachToSide - * @see #detach + * Should return an array of strings that identify the methods that this peripheral exposes to + * Lua. This will be called once before each attachment, and should not change when called + * multiple times. + * + * @return An array of strings representing method names. + * @see #callMethod */ - public void attach( IComputerAccess computer ); + public String[] getMethodNames(); /** - * Is called when a computer is detaching from the peripheral. - * This will occur when a computer shuts down, when the peripheral is removed while attached to computers, - * or when a turtle moves away from a square attached to a peripheral. - * This method can be used to keep track of which computers are attached to the peripheral, or to take action when detachment - * occurs.
+ * This is called when a lua program on an attached computer calls peripheral.call() with one of + * the methods exposed by getMethodNames().
*
* Be aware that this will be called from the ComputerCraft Lua thread, and must be thread-safe * when interacting with minecraft objects. - * @param computer The interface to the computer that is being detached. Remember that multiple - * computers can be attached to a peripheral at once. - * @see #canAttachToSide - * @see #detach + * + * @param computer The interface to the computer that is making the call. Remember that multiple + * computers can be attached to a peripheral at once. + * @param context The context of the currently running lua thread. This can be used to wait for + * events or otherwise yield. + * @param method An integer identifying which of the methods from getMethodNames() the computer + * wishes to call. The integer indicates the index into the getMethodNames() table that + * corresponds to the string passed into peripheral.call() + * @param arguments An array of objects, representing the arguments passed into + * peripheral.call().
+ * Lua values of type "string" will be represented by Object type String.
+ * Lua values of type "number" will be represented by Object type Double.
+ * Lua values of type "boolean" will be represented by Object type Boolean.
+ * Lua values of any other type will be represented by a null object.
+ * This array will be empty if no arguments are passed. + * @return An array of objects, representing values you wish to return to the lua program.
+ * Integers, Doubles, Floats, Strings, Booleans and null be converted to their corresponding lua + * type.
+ * All other types will be converted to nil.
+ * You may return null to indicate no values should be returned. + * @throws Exception If you throw any exception from this function, a lua error will be raised + * with the same message as your exception. Use this to throw appropriate errors if the wrong + * arguments are supplied to your method. + * @see #getMethodNames */ - public void detach( IComputerAccess computer ); + public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws Exception; + + /** + * Is called before the computer attempts to attach to the peripheral, and should return whether + * to allow the attachment. Use this to restrict the number of computers that can attach, or to + * limit attachments to certain world directions.
+ * If true is returned, attach() will be called shortly afterwards, and the computer will be + * able to make method calls. If false is returned, attach() will not be called, and the + * peripheral will be invisible to the computer. + * + * @param side The world direction (0=bottom, 1=top, etc) that the computer lies relative to the + * peripheral. + * @return Whether to allow the attachment, as a boolean. + * @see #attach + */ + public boolean canAttachToSide(int side); + + /** + * Is called when canAttachToSide has returned true, and a computer is attaching to the + * peripheral. This will occur when a peripheral is placed next to an active computer, when a + * computer is turned on next to a peripheral, or when a turtle travels into a square next to a + * peripheral. Between calls to attach() and detach(), the attached computer can make method + * calls on the peripheral using peripheral.call(). This method can be used to keep track of + * which computers are attached to the peripheral, or to take action when attachment occurs.
+ *
+ * Be aware that this will be called from the ComputerCraft Lua thread, and must be thread-safe + * when interacting with minecraft objects. + * + * @param computer The interface to the computer that is being attached. Remember that multiple + * computers can be attached to a peripheral at once. + * @see #canAttachToSide + * @see #detach + */ + public void attach(IComputerAccess computer); + + /** + * Is called when a computer is detaching from the peripheral. This will occur when a computer + * shuts down, when the peripheral is removed while attached to computers, or when a turtle + * moves away from a square attached to a peripheral. This method can be used to keep track of + * which computers are attached to the peripheral, or to take action when detachment occurs.
+ *
+ * Be aware that this will be called from the ComputerCraft Lua thread, and must be thread-safe + * when interacting with minecraft objects. + * + * @param computer The interface to the computer that is being detached. Remember that multiple + * computers can be attached to a peripheral at once. + * @see #canAttachToSide + * @see #detach + */ + public void detach(IComputerAccess computer); } diff --git a/APIs/dan200/computer/api/IWritableMount.java b/APIs/dan200/computer/api/IWritableMount.java index 7fa8db3f1..aefc12039 100644 --- a/APIs/dan200/computer/api/IWritableMount.java +++ b/APIs/dan200/computer/api/IWritableMount.java @@ -8,11 +8,15 @@ package dan200.computer.api; import java.io.IOException; import java.io.OutputStream; -import java.util.List; + +import net.minecraft.world.World; /** - * Represents a part of a virtual filesystem that can be mounted onto a computer using IComputerAccess.mount() or IComputerAccess.mountWritable(), that can also be written to. - * Ready made implementations of this interface can be created using ComputerCraftAPI.createSaveDirMount(), or you're free to implement it yourselves! + * Represents a part of a virtual filesystem that can be mounted onto a computer using + * IComputerAccess.mount() or IComputerAccess.mountWritable(), that can also be written to. Ready + * made implementations of this interface can be created using + * ComputerCraftAPI.createSaveDirMount(), or you're free to implement it yourselves! + * * @see ComputerCraftAPI#createSaveDirMount(World, String) * @see IComputerAccess#mountWritable(String, IMount) * @see IMount @@ -21,32 +25,42 @@ public interface IWritableMount extends IMount { /** * Creates a directory at a given path inside the virtual file system. - * @param path A file path in normalised format, relative to the mount location. ie: "programs/mynewprograms" + * + * @param path A file path in normalised format, relative to the mount location. ie: + * "programs/mynewprograms" */ - public void makeDirectory( String path ) throws IOException; + public void makeDirectory(String path) throws IOException; /** * Deletes a directory at a given path inside the virtual file system. - * @param path A file path in normalised format, relative to the mount location. ie: "programs/myoldprograms" + * + * @param path A file path in normalised format, relative to the mount location. ie: + * "programs/myoldprograms" */ - public void delete( String path ) throws IOException; + public void delete(String path) throws IOException; /** * Opens a file with a given path, and returns an outputstream for writing to it. - * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram" + * + * @param path A file path in normalised format, relative to the mount location. ie: + * "programs/myprogram" * @return a stream for writing to */ - public OutputStream openForWrite( String path ) throws IOException; + public OutputStream openForWrite(String path) throws IOException; /** * Opens a file with a given path, and returns an outputstream for appending to it. - * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram" + * + * @param path A file path in normalised format, relative to the mount location. ie: + * "programs/myprogram" * @return a stream for writing to */ - public OutputStream openForAppend( String path ) throws IOException; + public OutputStream openForAppend(String path) throws IOException; /** - * Get the ammount of free space on the mount, in bytes. You should decrease this value as the user writes to the mount, and write operations should fail once it reaches zero. + * Get the ammount of free space on the mount, in bytes. You should decrease this value as the + * user writes to the mount, and write operations should fail once it reaches zero. + * * @return The ammount of free space, in bytes. */ public long getRemainingSpace() throws IOException; diff --git a/APIs/ic2/api/energy/event/EnergyTileEvent.java b/APIs/ic2/api/energy/event/EnergyTileEvent.java index b39d24c9f..eb245d3b5 100644 --- a/APIs/ic2/api/energy/event/EnergyTileEvent.java +++ b/APIs/ic2/api/energy/event/EnergyTileEvent.java @@ -1,22 +1,23 @@ package ic2.api.energy.event; -import ic2.api.energy.tile.IEnergyTile; import net.minecraft.tileentity.TileEntity; + import net.minecraftforge.event.world.WorldEvent; +import ic2.api.energy.tile.IEnergyTile; + /** * Base class for energy net events, don't use it directly. * * See ic2/api/energy/usage.txt for an overall description of the energy net api. */ -public class EnergyTileEvent extends WorldEvent -{ +public class EnergyTileEvent extends WorldEvent { public final IEnergyTile energyTile; - public EnergyTileEvent(IEnergyTile energyTile) - { + public EnergyTileEvent(IEnergyTile energyTile) { super(((TileEntity) energyTile).worldObj); this.energyTile = energyTile; } } + diff --git a/APIs/ic2/api/energy/event/EnergyTileLoadEvent.java b/APIs/ic2/api/energy/event/EnergyTileLoadEvent.java index 771b0c2eb..6b342d32e 100644 --- a/APIs/ic2/api/energy/event/EnergyTileLoadEvent.java +++ b/APIs/ic2/api/energy/event/EnergyTileLoadEvent.java @@ -4,22 +4,23 @@ import ic2.api.energy.tile.IEnergyTile; /** * Event announcing new energy tiles. - * - * This event notifies subscribers of loaded energy tiles, e.g. after getting loaded through the - * chunk they are in or after being placed down by the player or another deployer mechanism. - * - * Every energy tile which wants to get connected to the IC2 Energy Network has to either post this - * event or alternatively call EnergyNet.addTileEntity(). - * - * You may use this event to build a static representation of energy tiles for your own energy grid - * implementation if you need to. It's not required if you always lookup energy paths on demand. + * + * This event notifies subscribers of loaded energy tiles, e.g. after getting + * loaded through the chunk they are in or after being placed down by the + * player or another deployer mechanism. + * + * Every energy tile which wants to get connected to the IC2 Energy Network has + * to either post this event or alternatively call EnergyNet.addTileEntity(). + * + * You may use this event to build a static representation of energy tiles for + * your own energy grid implementation if you need to. It's not required if you + * always lookup energy paths on demand. * * See ic2/api/energy/usage.txt for an overall description of the energy net api. */ -public class EnergyTileLoadEvent extends EnergyTileEvent -{ - public EnergyTileLoadEvent(IEnergyTile energyTile) - { +public class EnergyTileLoadEvent extends EnergyTileEvent { + public EnergyTileLoadEvent(IEnergyTile energyTile) { super(energyTile); } } + diff --git a/APIs/ic2/api/energy/event/EnergyTileUnloadEvent.java b/APIs/ic2/api/energy/event/EnergyTileUnloadEvent.java index 3a93aac47..58a4a0643 100644 --- a/APIs/ic2/api/energy/event/EnergyTileUnloadEvent.java +++ b/APIs/ic2/api/energy/event/EnergyTileUnloadEvent.java @@ -4,23 +4,24 @@ import ic2.api.energy.tile.IEnergyTile; /** * Event announcing terminated energy tiles. - * - * This event notifies subscribers of unloaded energy tiles, e.g. after getting unloaded through the - * chunk they are in or after being destroyed by the player or another block pick/destruction - * mechanism. - * - * Every energy tile which wants to get disconnected from the IC2 Energy Network has to either post - * this event or alternatively call EnergyNet.removeTileEntity(). - * - * You may use this event to build a static representation of energy tiles for your own energy grid - * implementation if you need to. It's not required if you always lookup energy paths on demand. + * + * This event notifies subscribers of unloaded energy tiles, e.g. after getting + * unloaded through the chunk they are in or after being destroyed by the + * player or another block pick/destruction mechanism. + * + * Every energy tile which wants to get disconnected from the IC2 Energy + * Network has to either post this event or alternatively call + * EnergyNet.removeTileEntity(). + * + * You may use this event to build a static representation of energy tiles for + * your own energy grid implementation if you need to. It's not required if you + * always lookup energy paths on demand. * * See ic2/api/energy/usage.txt for an overall description of the energy net api. */ -public class EnergyTileUnloadEvent extends EnergyTileEvent -{ - public EnergyTileUnloadEvent(IEnergyTile energyTile) - { +public class EnergyTileUnloadEvent extends EnergyTileEvent { + public EnergyTileUnloadEvent(IEnergyTile energyTile) { super(energyTile); } } + diff --git a/APIs/ic2/api/energy/tile/IEnergyAcceptor.java b/APIs/ic2/api/energy/tile/IEnergyAcceptor.java index 9bfce97f1..8b1d75e19 100644 --- a/APIs/ic2/api/energy/tile/IEnergyAcceptor.java +++ b/APIs/ic2/api/energy/tile/IEnergyAcceptor.java @@ -1,26 +1,27 @@ package ic2.api.energy.tile; import net.minecraft.tileentity.TileEntity; + import net.minecraftforge.common.ForgeDirection; /** * For internal/multi-block usage only. - * + * * @see IEnergySink * @see IEnergyConductor * * See ic2/api/energy/usage.txt for an overall description of the energy net api. */ -public interface IEnergyAcceptor extends IEnergyTile -{ +public interface IEnergyAcceptor extends IEnergyTile { /** * Determine if this acceptor can accept current from an adjacent emitter in a direction. * - * The TileEntity in the emitter parameter is what was originally added to the energy net, which - * may be normal in-world TileEntity, a delegate or an IMetaDelegate. + * The TileEntity in the emitter parameter is what was originally added to the energy net, + * which may be normal in-world TileEntity, a delegate or an IMetaDelegate. * * @param emitter energy emitter * @param direction direction the energy is being received from */ boolean acceptsEnergyFrom(TileEntity emitter, ForgeDirection direction); } + diff --git a/APIs/ic2/api/energy/tile/IEnergyConductor.java b/APIs/ic2/api/energy/tile/IEnergyConductor.java index 3e3dc3ea0..16965afe1 100644 --- a/APIs/ic2/api/energy/tile/IEnergyConductor.java +++ b/APIs/ic2/api/energy/tile/IEnergyConductor.java @@ -1,13 +1,12 @@ package ic2.api.energy.tile; /** - * Tile entities which conduct energy pulses without buffering (mostly cables) have to implement - * this interface. + * Tile entities which conduct energy pulses without buffering (mostly cables) have to implement this + * interface. * * See ic2/api/energy/usage.txt for an overall description of the energy net api. */ -public interface IEnergyConductor extends IEnergyAcceptor, IEnergyEmitter -{ +public interface IEnergyConductor extends IEnergyAcceptor, IEnergyEmitter { /** * Energy loss for the conductor in EU per block. * @@ -23,9 +22,9 @@ public interface IEnergyConductor extends IEnergyAcceptor, IEnergyEmitter int getInsulationEnergyAbsorption(); /** - * Amount of energy the insulation will handle before it is destroyed. Ensure that this value is - * greater than the insulation energy absorption + 64. - * + * Amount of energy the insulation will handle before it is destroyed. + * Ensure that this value is greater than the insulation energy absorption + 64. + * * @return Insulation-destroying energy in EU */ int getInsulationBreakdownEnergy(); @@ -51,3 +50,4 @@ public interface IEnergyConductor extends IEnergyAcceptor, IEnergyEmitter */ void removeConductor(); } + diff --git a/APIs/ic2/api/energy/tile/IEnergyEmitter.java b/APIs/ic2/api/energy/tile/IEnergyEmitter.java index b0cbb4c7d..2379252c1 100644 --- a/APIs/ic2/api/energy/tile/IEnergyEmitter.java +++ b/APIs/ic2/api/energy/tile/IEnergyEmitter.java @@ -1,18 +1,18 @@ package ic2.api.energy.tile; import net.minecraft.tileentity.TileEntity; + import net.minecraftforge.common.ForgeDirection; /** * For internal/multi-block usage only. - * + * * @see IEnergySource * @see IEnergyConductor * * See ic2/api/energy/usage.txt for an overall description of the energy net api. */ -public interface IEnergyEmitter extends IEnergyTile -{ +public interface IEnergyEmitter extends IEnergyTile { /** * Determine if this emitter can emit energy to an adjacent receiver. * @@ -25,3 +25,4 @@ public interface IEnergyEmitter extends IEnergyTile */ boolean emitsEnergyTo(TileEntity receiver, ForgeDirection direction); } + diff --git a/APIs/ic2/api/energy/tile/IEnergySink.java b/APIs/ic2/api/energy/tile/IEnergySink.java index faf36d1c1..9826d54e0 100644 --- a/APIs/ic2/api/energy/tile/IEnergySink.java +++ b/APIs/ic2/api/energy/tile/IEnergySink.java @@ -7,15 +7,14 @@ import net.minecraftforge.common.ForgeDirection; * * See ic2/api/energy/usage.txt for an overall description of the energy net api. */ -public interface IEnergySink extends IEnergyAcceptor -{ +public interface IEnergySink extends IEnergyAcceptor { /** * Determine how much energy the sink accepts. - * + * * This value is unrelated to getMaxSafeInput(). - * + * * Make sure that injectEnergy() does accepts energy if demandsEnergy() returns anything > 0. - * + * * @return max accepted input in eu */ double demandedEnergyUnits(); @@ -23,6 +22,9 @@ public interface IEnergySink extends IEnergyAcceptor /** * Transfer energy to the sink. * + * It's highly recommended to accept all energy by letting the internal buffer overflow to + * increase the performance and accuracy of the distribution simulation. + * * @param directionFrom direction from which the energy comes from * @param amount energy to be transferred * @return Energy not consumed (leftover) @@ -30,15 +32,15 @@ public interface IEnergySink extends IEnergyAcceptor double injectEnergyUnits(ForgeDirection directionFrom, double amount); /** - * Determine the amount of eu which can be safely injected into the specific energy sink without - * exploding. - * - * Typical values are 32 for LV, 128 for MV, 512 for HV and 2048 for EV. A value of - * Integer.MAX_VALUE indicates no limit. - * + * Determine the amount of eu which can be safely injected into the specific energy sink without exploding. + * + * Typical values are 32 for LV, 128 for MV, 512 for HV and 2048 for EV. A value of Integer.MAX_VALUE indicates no + * limit. + * * This value is unrelated to demandsEnergy(). - * + * * @return max safe input in eu */ int getMaxSafeInput(); } + diff --git a/APIs/ic2/api/energy/tile/IEnergySource.java b/APIs/ic2/api/energy/tile/IEnergySource.java index bb2bc5e42..1a8bc0a5f 100644 --- a/APIs/ic2/api/energy/tile/IEnergySource.java +++ b/APIs/ic2/api/energy/tile/IEnergySource.java @@ -5,11 +5,10 @@ package ic2.api.energy.tile; * * See ic2/api/energy/usage.txt for an overall description of the energy net api. */ -public interface IEnergySource extends IEnergyEmitter -{ +public interface IEnergySource extends IEnergyEmitter { /** - * Energy output provided by the source this tick. This is typically Math.min(stored energy, max - * output/tick). + * Energy output provided by the source this tick. + * This is typically Math.min(stored energy, max output/tick). * * @return Energy offered this tick */ @@ -20,7 +19,8 @@ public interface IEnergySource extends IEnergyEmitter * * If the source doesn't have a buffer, this is a no-op. * - * @param amount amount of EU to draw + * @param amount amount of EU to draw, may be negative */ void drawEnergy(double amount); } + diff --git a/APIs/ic2/api/energy/tile/IEnergyTile.java b/APIs/ic2/api/energy/tile/IEnergyTile.java index 0b3262b47..932847f85 100644 --- a/APIs/ic2/api/energy/tile/IEnergyTile.java +++ b/APIs/ic2/api/energy/tile/IEnergyTile.java @@ -2,13 +2,13 @@ package ic2.api.energy.tile; /** * For internal usage only, base class for all energy tiles. - * + * * @see IEnergySink * @see IEnergySource * @see IEnergyConductor * * See ic2/api/energy/usage.txt for an overall description of the energy net api. */ -public interface IEnergyTile -{ +public interface IEnergyTile { } + diff --git a/APIs/ic2/api/energy/tile/IMetaDelegate.java b/APIs/ic2/api/energy/tile/IMetaDelegate.java index b1618a26b..8f4e830c8 100644 --- a/APIs/ic2/api/energy/tile/IMetaDelegate.java +++ b/APIs/ic2/api/energy/tile/IMetaDelegate.java @@ -9,24 +9,25 @@ import net.minecraft.tileentity.TileEntity; * * The energy net uses TileEntity to refer to a specific xyz+world position. If multiple of those * positions should belong to the same functional structure, i.e. they consume or produce energy - * only once for the whole multi-block instead of once per every single block, this interface allows - * to do so. + * only once for the whole multi-block instead of once per every single block, this interface + * allows to do so. * - * The tile entity implementing IMetaDelegate has to be added/removed to/from the energy net instead - * of every single sub-TileEntity. The energy net interaction will be handled by the IMetaDelegate - * TileEntity as well. + * The tile entity implementing IMetaDelegate has to be added/removed to/from the energy net + * instead of every single sub-TileEntity. The energy net interaction will be handled by the + * IMetaDelegate TileEntity as well. * * The sub tile array TileEntity[] just provides optional connectivity (IEnergyAcceptor, - * IEnergyEmitter) and mandatory position (x, y, z, World) data. If the connectivity data on the sub - * tile is missing, the meta delegate is queried instead. + * IEnergyEmitter) and mandatory position (x, y, z, World) data. + * If the connectivity data on the sub tile is missing, the meta delegate is queried instead. * * See ic2/api/energy/usage.txt for an overall description of the energy net api. */ -public interface IMetaDelegate extends IEnergyTile -{ +public interface IMetaDelegate extends IEnergyTile { /** * Get the sub-TileEntities belonging to this Meta TileEntity. * + * @note the list has to be consistent between the EnergyNet Load and Unload events. + * * @return sub-TileEntity array */ List getSubTiles(); diff --git a/APIs/ic2/api/item/ElectricItem.java b/APIs/ic2/api/item/ElectricItem.java index 360c2f830..511220fd8 100644 --- a/APIs/ic2/api/item/ElectricItem.java +++ b/APIs/ic2/api/item/ElectricItem.java @@ -5,12 +5,11 @@ import net.minecraft.item.ItemStack; /** * Allows for charging, discharging and using electric items (IElectricItem). - * + * * The charge or remaining capacity of an item can be determined by calling charge/discharge with * ignoreTransferLimit and simulate set to true. */ -public final class ElectricItem -{ +public final class ElectricItem { /** * IElectricItemManager to use for interacting with IElectricItem ItemStacks. * @@ -27,7 +26,7 @@ public final class ElectricItem /** * Charge an item with a specified amount of energy - * + * * @param itemStack electric item's stack * @param amount amount of energy to charge in EU * @param tier tier of the charging device, has to be at least as high as the item to charge @@ -38,18 +37,16 @@ public final class ElectricItem * @deprecated use manager.charge() instead */ @Deprecated - public static int charge(ItemStack itemStack, int amount, int tier, boolean ignoreTransferLimit, boolean simulate) - { + public static int charge(ItemStack itemStack, int amount, int tier, boolean ignoreTransferLimit, boolean simulate) { return manager.charge(itemStack, amount, tier, ignoreTransferLimit, simulate); } /** * Discharge an item by a specified amount of energy - * + * * @param itemStack electric item's stack * @param amount amount of energy to charge in EU - * @param tier tier of the discharging device, has to be at least as high as the item to - * discharge + * @param tier tier of the discharging device, has to be at least as high as the item to discharge * @param ignoreTransferLimit ignore the transfer limit specified by getTransferLimit() * @param simulate don't actually discharge the item, just determine the return value * @return Energy retrieved from the electric item @@ -57,16 +54,15 @@ public final class ElectricItem * @deprecated use manager.discharge() instead */ @Deprecated - public static int discharge(ItemStack itemStack, int amount, int tier, boolean ignoreTransferLimit, boolean simulate) - { + public static int discharge(ItemStack itemStack, int amount, int tier, boolean ignoreTransferLimit, boolean simulate) { return manager.discharge(itemStack, amount, tier, ignoreTransferLimit, simulate); } /** - * Determine if the specified electric item has at least a specific amount of EU. This is - * supposed to be used in the item code during operation, for example if you want to implement - * your own electric item. BatPacks are not taken into account. - * + * Determine if the specified electric item has at least a specific amount of EU. + * This is supposed to be used in the item code during operation, for example if you want to implement your own electric item. + * BatPacks are not taken into account. + * * @param itemStack electric item's stack * @param amount minimum amount of energy required * @return true if there's enough energy @@ -74,16 +70,14 @@ public final class ElectricItem * @deprecated use manager.canUse() instead */ @Deprecated - public static boolean canUse(ItemStack itemStack, int amount) - { + public static boolean canUse(ItemStack itemStack, int amount) { return manager.canUse(itemStack, amount); } /** - * Try to retrieve a specific amount of energy from an Item, and if applicable, a BatPack. This - * is supposed to be used in the item code during operation, for example if you want to - * implement your own electric item. - * + * Try to retrieve a specific amount of energy from an Item, and if applicable, a BatPack. + * This is supposed to be used in the item code during operation, for example if you want to implement your own electric item. + * * @param itemStack electric item's stack * @param amount amount of energy to discharge in EU * @param player player holding the item @@ -92,24 +86,23 @@ public final class ElectricItem * @deprecated use manager.use() instead */ @Deprecated - public static boolean use(ItemStack itemStack, int amount, EntityPlayer player) - { + public static boolean use(ItemStack itemStack, int amount, EntityPlayer player) { return manager.use(itemStack, amount, player); } /** - * Charge an item from the BatPack a player is wearing. This is supposed to be used in the item - * code during operation, for example if you want to implement your own electric item. use() - * already contains this functionality. - * + * Charge an item from the BatPack a player is wearing. + * This is supposed to be used in the item code during operation, for example if you want to implement your own electric item. + * use() already contains this functionality. + * * @param itemStack electric item's stack * @param player player holding the item * * @deprecated use manager.chargeFromArmor() instead */ @Deprecated - public static void chargeFromArmor(ItemStack itemStack, EntityPlayer player) - { + public static void chargeFromArmor(ItemStack itemStack, EntityPlayer player) { manager.chargeFromArmor(itemStack, player); } } + diff --git a/APIs/ic2/api/item/IBoxable.java b/APIs/ic2/api/item/IBoxable.java index 1d86e2c05..bca2cc0dc 100644 --- a/APIs/ic2/api/item/IBoxable.java +++ b/APIs/ic2/api/item/IBoxable.java @@ -2,8 +2,8 @@ package ic2.api.item; import net.minecraft.item.ItemStack; -public interface IBoxable -{ + +public interface IBoxable { /** * Determine whether an item can be stored in a toolbox or not. * diff --git a/APIs/ic2/api/item/ICustomElectricItem.java b/APIs/ic2/api/item/ICustomElectricItem.java index 2b72dc366..9f4b1a684 100644 --- a/APIs/ic2/api/item/ICustomElectricItem.java +++ b/APIs/ic2/api/item/ICustomElectricItem.java @@ -4,25 +4,25 @@ import net.minecraft.item.ItemStack; /** * Provides the ability to store energy on the implementing item. - * + * * This interface is a special version of IElectricItem which delegates the implementation of * charge(), discharge() and canUse() to the implementing Item. - * - * The default implementation (when not using ICustomElectricItem) does the following: - store and - * retrieve the charge - handle charging, taking amount, tier, transfer limit, canProvideEnergy and - * simulate into account - replace item IDs if appropriate (getChargedItemId() and getEmptyItemId()) + * + * The default implementation (when not using ICustomElectricItem) does the following: + * - store and retrieve the charge + * - handle charging, taking amount, tier, transfer limit, canProvideEnergy and simulate into account + * - replace item IDs if appropriate (getChargedItemId() and getEmptyItemId()) * - update and manage the damage value for the visual charge indicator - * + * * @note ICustomElectricItem must not call the ElectricItem methods charge, discharge or canUse * * @deprecated Use ISpecialElectricItem instead. */ @Deprecated -public interface ICustomElectricItem extends IElectricItem -{ +public interface ICustomElectricItem extends IElectricItem { /** * Charge an item with a specified amount of energy - * + * * @param itemStack electric item's stack * @param amount amount of energy to charge in EU * @param tier tier of the charging device, has to be at least as high as the item to charge @@ -34,11 +34,10 @@ public interface ICustomElectricItem extends IElectricItem /** * Discharge an item by a specified amount of energy - * + * * @param itemStack electric item's stack * @param amount amount of energy to charge in EU - * @param tier tier of the discharging device, has to be at least as high as the item to - * discharge + * @param tier tier of the discharging device, has to be at least as high as the item to discharge * @param ignoreTransferLimit ignore the transfer limit specified by getTransferLimit() * @param simulate don't actually discharge the item, just determine the return value * @return Energy retrieved from the electric item @@ -46,10 +45,10 @@ public interface ICustomElectricItem extends IElectricItem public int discharge(ItemStack itemStack, int amount, int tier, boolean ignoreTransferLimit, boolean simulate); /** - * Determine if the specified electric item has at least a specific amount of EU. This is - * supposed to be used in the item code during operation, for example if you want to implement - * your own electric item. BatPacks are not taken into account. - * + * Determine if the specified electric item has at least a specific amount of EU. + * This is supposed to be used in the item code during operation, for example if you want to implement your own electric item. + * BatPacks are not taken into account. + * * @param itemStack electric item's stack * @param amount minimum amount of energy required * @return true if there's enough energy @@ -58,10 +57,10 @@ public interface ICustomElectricItem extends IElectricItem /** * Determine whether to show the charge tool tip with NEI or other means. - * + * * Return false if IC2's handler is incompatible, you want to implement your own or you don't * want to display the charge at all. - * + * * @return true to show the tool tip (x/y EU) */ public boolean canShowChargeToolTip(ItemStack itemStack); diff --git a/APIs/ic2/api/item/IDebuggable.java b/APIs/ic2/api/item/IDebuggable.java index 2ecff67e7..b1fa66bc3 100644 --- a/APIs/ic2/api/item/IDebuggable.java +++ b/APIs/ic2/api/item/IDebuggable.java @@ -1,22 +1,23 @@ package ic2.api.item; -/** - * Allows a tile entity to output a debug message when the debugItem is used on it. Suggestions by - * Myrathi - */ -public abstract interface IDebuggable -{ - /** - * Checks if the tile entity is in a state that can be debugged. - * - * @return True if the tile entity can be debugged - */ - public abstract boolean isDebuggable(); - /** - * Gets the debug text for the tile entity. - * - * @return The text that the debugItem should show - */ - public abstract String getDebugText(); + +/** + * Allows a tile entity to output a debug message when the debugItem is used on it. + * Suggestions by Myrathi + */ +public abstract interface IDebuggable { + /** + * Checks if the tile entity is in a state that can be debugged. + * + * @return True if the tile entity can be debugged + */ + public abstract boolean isDebuggable(); + + /** + * Gets the debug text for the tile entity. + * + * @return The text that the debugItem should show + */ + public abstract String getDebugText(); } diff --git a/APIs/ic2/api/item/IElectricItem.java b/APIs/ic2/api/item/IElectricItem.java index 91bc1e0d8..adaf3b76d 100644 --- a/APIs/ic2/api/item/IElectricItem.java +++ b/APIs/ic2/api/item/IElectricItem.java @@ -4,51 +4,51 @@ import net.minecraft.item.ItemStack; /** * Provides the ability to store energy on the implementing item. - * + * * The item should have a maximum damage of 13. */ -public interface IElectricItem -{ +public interface IElectricItem { /** * Determine if the item can be used in a machine or as an armor part to supply energy. - * + * * @return Whether the item can supply energy */ boolean canProvideEnergy(ItemStack itemStack); /** * Get the item ID to use for a charge energy greater than 0. - * + * * @return Item ID to use */ int getChargedItemId(ItemStack itemStack); /** * Get the item ID to use for a charge energy of 0. - * + * * @return Item ID to use */ int getEmptyItemId(ItemStack itemStack); /** * Get the item's maximum charge energy in EU. - * + * * @return Maximum charge energy */ int getMaxCharge(ItemStack itemStack); /** - * Get the item's tier, lower tiers can't send energy to higher ones. Batteries are Tier 1, - * Energy Crystals are Tier 2, Lapotron Crystals are Tier 3. - * + * Get the item's tier, lower tiers can't send energy to higher ones. + * Batteries are Tier 1, Energy Crystals are Tier 2, Lapotron Crystals are Tier 3. + * * @return Item's tier */ int getTier(ItemStack itemStack); /** * Get the item's transfer limit in EU per transfer operation. - * + * * @return Transfer limit */ int getTransferLimit(ItemStack itemStack); } + diff --git a/APIs/ic2/api/item/IElectricItemManager.java b/APIs/ic2/api/item/IElectricItemManager.java index d8a481fbc..88eab750b 100644 --- a/APIs/ic2/api/item/IElectricItemManager.java +++ b/APIs/ic2/api/item/IElectricItemManager.java @@ -5,22 +5,22 @@ import net.minecraft.item.ItemStack; /** * This interface specifies a manager to handle the various tasks for electric items. - * - * The default implementation does the following: - store and retrieve the charge - handle charging, - * taking amount, tier, transfer limit, canProvideEnergy and simulate into account - replace item - * IDs if appropriate (getChargedItemId() and getEmptyItemId()) - update and manage the damage value - * for the visual charge indicator + * + * The default implementation does the following: + * - store and retrieve the charge + * - handle charging, taking amount, tier, transfer limit, canProvideEnergy and simulate into account + * - replace item IDs if appropriate (getChargedItemId() and getEmptyItemId()) + * - update and manage the damage value for the visual charge indicator * * @note If you're implementing your own variant (ISpecialElectricItem), you can delegate to the * default implementations through ElectricItem.rawManager. The default implementation is designed * to minimize its dependency on its own constraints/structure and delegates most work back to the * more atomic features in the gateway manager. */ -public interface IElectricItemManager -{ +public interface IElectricItemManager { /** * Charge an item with a specified amount of energy - * + * * @param itemStack electric item's stack * @param amount amount of energy to charge in EU * @param tier tier of the charging device, has to be at least as high as the item to charge @@ -32,11 +32,10 @@ public interface IElectricItemManager /** * Discharge an item by a specified amount of energy - * + * * @param itemStack electric item's stack * @param amount amount of energy to charge in EU - * @param tier tier of the discharging device, has to be at least as high as the item to - * discharge + * @param tier tier of the discharging device, has to be at least as high as the item to discharge * @param ignoreTransferLimit ignore the transfer limit specified by getTransferLimit() * @param simulate don't actually discharge the item, just determine the return value * @return Energy retrieved from the electric item @@ -52,10 +51,10 @@ public interface IElectricItemManager int getCharge(ItemStack itemStack); /** - * Determine if the specified electric item has at least a specific amount of EU. This is - * supposed to be used in the item code during operation, for example if you want to implement - * your own electric item. BatPacks are not taken into account. - * + * Determine if the specified electric item has at least a specific amount of EU. + * This is supposed to be used in the item code during operation, for example if you want to implement your own electric item. + * BatPacks are not taken into account. + * * @param itemStack electric item's stack * @param amount minimum amount of energy required * @return true if there's enough energy @@ -63,10 +62,9 @@ public interface IElectricItemManager boolean canUse(ItemStack itemStack, int amount); /** - * Try to retrieve a specific amount of energy from an Item, and if applicable, a BatPack. This - * is supposed to be used in the item code during operation, for example if you want to - * implement your own electric item. - * + * Try to retrieve a specific amount of energy from an Item, and if applicable, a BatPack. + * This is supposed to be used in the item code during operation, for example if you want to implement your own electric item. + * * @param itemStack electric item's stack * @param amount amount of energy to discharge in EU * @param entity entity holding the item @@ -75,10 +73,10 @@ public interface IElectricItemManager boolean use(ItemStack itemStack, int amount, EntityLivingBase entity); /** - * Charge an item from the BatPack a player is wearing. This is supposed to be used in the item - * code during operation, for example if you want to implement your own electric item. use() - * already contains this functionality. - * + * Charge an item from the BatPack a player is wearing. + * This is supposed to be used in the item code during operation, for example if you want to implement your own electric item. + * use() already contains this functionality. + * * @param itemStack electric item's stack * @param entity entity holding the item */ diff --git a/APIs/ic2/api/item/IItemHudInfo.java b/APIs/ic2/api/item/IItemHudInfo.java index a5065ee39..e2b8610da 100644 --- a/APIs/ic2/api/item/IItemHudInfo.java +++ b/APIs/ic2/api/item/IItemHudInfo.java @@ -1,20 +1,27 @@ package ic2.api.item; +import java.util.LinkedList; import java.util.List; import net.minecraft.item.ItemStack; -public interface IItemHudInfo -{ - - /* - * Add Info to Nano- and Quantum-Suit Helm Hud for itemStack - * - * @Override public List getHudInfo(ItemStack itemStack) { List info = new - * LinkedList(); info.add("i am a Cool Item"); info.add("and have Cool info"); return - * info; } - */ - - public List getHudInfo(ItemStack itemStack); +public interface IItemHudInfo { +/* + Add Info to Nano- and Quantum-Suit Helm Hud + for itemStack + + @Override + public List getHudInfo(ItemStack itemStack) { + List info = new LinkedList(); + info.add("i am a Cool Item"); + info.add("and have Cool info"); + return info; + } + + + */ + + public List getHudInfo(ItemStack itemStack); + } diff --git a/APIs/ic2/api/item/IMetalArmor.java b/APIs/ic2/api/item/IMetalArmor.java index c06781475..16ffd24e5 100644 --- a/APIs/ic2/api/item/IMetalArmor.java +++ b/APIs/ic2/api/item/IMetalArmor.java @@ -8,8 +8,7 @@ import net.minecraft.item.ItemStack; * * Currently used for determining which boots can be used to slide up a magnetic pole. */ -public interface IMetalArmor -{ +public interface IMetalArmor { /** * Determine if the given armor piece is metal armor. * diff --git a/APIs/ic2/api/item/ISpecialElectricItem.java b/APIs/ic2/api/item/ISpecialElectricItem.java index b73cf1ddc..a7302f530 100644 --- a/APIs/ic2/api/item/ISpecialElectricItem.java +++ b/APIs/ic2/api/item/ISpecialElectricItem.java @@ -2,8 +2,7 @@ package ic2.api.item; import net.minecraft.item.ItemStack; -public interface ISpecialElectricItem extends IElectricItem -{ +public interface ISpecialElectricItem extends IElectricItem { /** * Supply a custom IElectricItemManager. * diff --git a/APIs/ic2/api/item/ITerraformingBP.java b/APIs/ic2/api/item/ITerraformingBP.java index 2bbf2d340..58f7e2fe7 100644 --- a/APIs/ic2/api/item/ITerraformingBP.java +++ b/APIs/ic2/api/item/ITerraformingBP.java @@ -13,14 +13,15 @@ public interface ITerraformingBP * @return Energy consumption in EU */ public abstract int getConsume(); - + /** - * Get the maximum range of the blueprint. Should be a divisor of 5. + * Get the maximum range of the blueprint. + * Should be a divisor of 5. * * @return Maximum range in blocks */ public abstract int getRange(); - + /** * Perform the terraforming operation. * diff --git a/APIs/ic2/api/item/ItemWrapper.java b/APIs/ic2/api/item/ItemWrapper.java index b04d084c4..58f807340 100644 --- a/APIs/ic2/api/item/ItemWrapper.java +++ b/APIs/ic2/api/item/ItemWrapper.java @@ -12,50 +12,39 @@ import com.google.common.collect.Multimap; * * @author Richard */ -public class ItemWrapper -{ +public class ItemWrapper { private static final Multimap boxableItems = ArrayListMultimap.create(); private static final Multimap metalArmorItems = ArrayListMultimap.create(); - - public static void registerBoxable(Item item, IBoxable boxable) - { + + public static void registerBoxable(Item item, IBoxable boxable) { boxableItems.put(item, boxable); } - - public static boolean canBeStoredInToolbox(ItemStack stack) - { + + public static boolean canBeStoredInToolbox(ItemStack stack) { Item item = stack.getItem(); // use customs first to allow for overriding behavior - for (IBoxable boxable : boxableItems.get(item)) - { - if (boxable.canBeStoredInToolbox(stack)) - return true; + for (IBoxable boxable : boxableItems.get(item)) { + if (boxable.canBeStoredInToolbox(stack)) return true; } - - if (item instanceof IBoxable && ((IBoxable) item).canBeStoredInToolbox(stack)) - return true; - + + if (item instanceof IBoxable && ((IBoxable) item).canBeStoredInToolbox(stack)) return true; + return false; } - - public static void registerMetalArmor(Item item, IMetalArmor armor) - { + + public static void registerMetalArmor(Item item, IMetalArmor armor) { metalArmorItems.put(item, armor); } - - public static boolean isMetalArmor(ItemStack stack, EntityPlayer player) - { + + public static boolean isMetalArmor(ItemStack stack, EntityPlayer player) { Item item = stack.getItem(); // use customs first to allow for overriding behavior - for (IMetalArmor metalArmor : metalArmorItems.get(item)) - { - if (metalArmor.isMetalArmor(stack, player)) - return true; + for (IMetalArmor metalArmor : metalArmorItems.get(item)) { + if (metalArmor.isMetalArmor(stack, player)) return true; } - - if (item instanceof IMetalArmor && ((IMetalArmor) item).isMetalArmor(stack, player)) - return true; - + + if (item instanceof IMetalArmor && ((IMetalArmor) item).isMetalArmor(stack, player)) return true; + return false; } } diff --git a/APIs/ic2/api/item/Items.java b/APIs/ic2/api/item/Items.java index bd3535615..5e6951602 100644 --- a/APIs/ic2/api/item/Items.java +++ b/APIs/ic2/api/item/Items.java @@ -5,338 +5,576 @@ import net.minecraft.item.ItemStack; /** * Provides access to IC2 blocks and items. * - * Some items can be acquired through the ore dictionary which is the recommended way. The items are - * initialized while IC2 is being loaded - try to use ModsLoaded() or load your mod after IC2. Some - * blocks/items can be disabled by a config setting, so it's recommended to check if they're null - * first. + * Some items can be acquired through the ore dictionary which is the recommended way. + * The items are initialized while IC2 is being loaded - try to use ModsLoaded() or load your mod after IC2. + * Some blocks/items can be disabled by a config setting, so it's recommended to check if they're null first. * - * Getting the associated Block/Item for an ItemStack x: Blocks: Block.blocksList[x.itemID] Items: - * x.getItem() + * Getting the associated Block/Item for an ItemStack x: + * Blocks: Block.blocksList[x.itemID] + * Items: x.getItem() */ -public final class Items -{ +public final class Items { /** - * Get an ItemStack for a specific item name, example: Items.getItem("resin") See the list below - * for item names. Make sure to copy() the ItemStack if you want to modify it. - * + * Get an ItemStack for a specific item name, example: Items.getItem("resin") + * See the list below for item names. + * Make sure to copy() the ItemStack if you want to modify it. + * * @param name item name * @return The item or null if the item does not exist or an error occurred */ - public static ItemStack getItem(String name) - { - try - { - if (Ic2Items == null) - Ic2Items = Class.forName(getPackage() + ".core.Ic2Items"); + public static ItemStack getItem(String name) { + try { + if (Ic2Items == null) Ic2Items = Class.forName(getPackage() + ".core.Ic2Items"); Object ret = Ic2Items.getField(name).get(null); - if (ret instanceof ItemStack) - { + if (ret instanceof ItemStack) { return (ItemStack) ret; - } - else - { + } else { return null; } - } - catch (Exception e) - { - System.out.println("IC2 API: Call getItem failed for " + name); + } catch (Exception e) { + System.out.println("IC2 API: Call getItem failed for "+name); return null; } } - /* - * Possible values: - * - * ----- blocks ----- - * - * ores copperOre Copper Ore block, currently not meta sensitive, meta in ItemStack set to 0, - * ore dictionary: oreCopper, null with enableWorldGenOreCopper=false tinOre Tin Ore block, - * currently not meta sensitive, meta in ItemStack set to 0, ore dictionary: oreTin, null with - * enableWorldGenOreTin=false uraniumOre Tin Ore block, currently not meta sensitive, meta in - * ItemStack set to 0, ore dictionary: oreUranium, null with enableWorldGenOreUranium=false - * - * rubber related Rubber wood block, meta reflects the state, meta in ItemStack set to 0, ore - * dictionary: woodRubber (with meta 0), null with enableWorldGenTreeRubber=false dropped (as an - * item) -> metadata 0 block, no resin spot -> metadata 0 or 1 block, wet resin spot -> metadata - * 2-5 (according to the side) block, dry resin spot -> metadata 8-11 (wet state + 6) - * - * rubberWood rubberLeaves Rubber Leaves block, currently not meta sensitive, meta in ItemStack - * set to 0, null with enableWorldGenTreeRubber=false rubberSapling Rubber Sapling block, - * currently not meta sensitive, meta in ItemStack set to 0, null with - * enableWorldGenTreeRubber=false resinSheet Resin Sheet block, currently not meta sensitive - * rubberTrampoline Rubber Trampoline block, meta reflects internal state, meta in ItemStack set - * to 0 - * - * building/storage ironFence Iron Fence block, currently not meta sensitive - * - * reinforcedStone Reinforced Stone block, currently not meta sensitive reinforcedGlass - * Reinforced Glass block, currently not meta sensitive reinforcedDoorBlock Reinforced Door - * block, meta reflects the state (see vanilla doors), meta in ItemStack set to 0 - * - * constructionFoam Construction Foam block, currently not meta sensitive constructionFoamWall - * Construction Foam Wall block, meta = color, implements IPaintableBlock scaffold Scaffold - * block, meta reflects internal physical model data - * - * bronzeBlock Bronze block, meta sensitive copperBlock Copper block, meta sensitive tinBlock - * Tin block, meta sensitive uraniumBlock Uranium block, meta sensitive - * - * cables (when placed as a block, inventory items are different TE implements IEnergyConductor) - * copperCableBlock Copper Cable block, meta sensitive insulatedCopperCableBlock Insulated - * Copper Cable block, meta sensitive - * - * goldCableBlock Gold Cable block, meta sensitive insulatedGoldCableBlock Insulated Gold Cable - * block, meta sensitive doubleInsulatedGoldCableBlock Double Insulated Gold Cable block, meta - * sensitive - * - * ironCableBlock Iron Cable block, meta sensitive insulatedIronCableBlock Insulated Iron Cable - * block, meta sensitive doubleInsulatedIronCableBlock Double Insulated Iron Cable block, meta - * sensitive trippleInsulatedIronCableBlock Tripple Insulated Iron Cable block, meta sensitive - * - * glassFiberCableBlock Glass Fiber Cable block, meta sensitive - * - * tinCableBlock Tin Cable block, meta sensitive - * - * detectorCableBlock Detector Cable block, meta sensitive splitterCableBlock Splitter Cable - * block, meta sensitive - * - * generators + related (TE implements IEnergySource ex. reactorChamber) generator Generator - * block, meta sensitive geothermalGenerator Geothermal Generator block, meta sensitive - * waterMill Water Mill block, meta sensitive solarPanel Solar Panel block, meta sensitive - * windMill Wind Mill block, meta sensitive nuclearReactor Nuclear Reactor block, meta sensitive - * reactorChamber Reactor Chamber block, currently not meta sensitive - * - * energy storages (TE implements IEnergySource and IEnergyConductor) batBox BatBox block, meta - * sensitive mfeUnit MFE Unit block, meta sensitive mfsUnit MFS Unit block, meta sensitive - * - * transformers (TE implements IEnergySource and IEnergyConductor) lvTransformer LV Transformer - * block, meta sensitive mvTransformer MV Transformer block, meta sensitive hvTransformer HV - * Transformer block, meta sensitive - * - * machines + related (TE implements IEnergySink ex. machine, miningPipe, miningPipeTip) machine - * Machine block, meta sensitive advancedMachine Advanced Machine block, meta sensitive - * - * ironFurnace Iron Furnace block, meta sensitive electroFurnace Electro Furnace block, meta - * sensitive macerator Macerator block, meta sensitive extractor Extractor block, meta sensitive - * compressor Compressor block, meta sensitive canner Canner block, meta sensitive miner Miner - * block, meta sensitive pump Pump block, meta sensitive magnetizer Magnetizer block, meta - * sensitive electrolyzer Electrolyzer block, meta sensitive recycler Recycler block, meta - * sensitive inductionFurnace Induction Furnace block, meta sensitive massFabricator Mass - * Fabricator block, meta sensitive terraformer Terraformer block, meta sensitive teleporter - * Teleporter block, meta sensitive teslaCoil Tesla Coil block, meta sensitive luminator Passive - * (dark) Luminator block, meta = facing activeLuminator Active (bright) Luminator block, meta = - * facing - * - * miningPipe Mining Pipe block, currently not meta sensitive, meta in ItemStack set to 0 - * miningPipeTip Mining Pipe Tip block, currently not meta sensitive, meta in ItemStack set to 0 - * - * personal blocks personalSafe Personal Safe block, meta sensitive tradeOMat Trade-O-Mat block, - * meta sensitive energyOMat Energy-O-Mat block, meta sensitive - * - * explosives industrialTnt Industrial TNT block, currently not meta sensitive nuke Nuke block, - * currently not meta sensitive dynamiteStick Dynamite Stick block, meta = placement, meta in - * ItemStack set to 0 dynamiteStickWithRemote Dynamite Stick with Remote block, meta = - * placement, meta in ItemStack set to 0 - * - * Agriculture Stuff crop Crop Block, empty, not meta sensitive - * - * - * ----- items ----- - * - * rubber + related resin Resin item, currently not meta sensitive rubber Rubber item, currently - * not meta sensitive, ore dictionary: itemRubber - * - * ore drops uraniumDrop Uranium Drop item, currently not meta sensitive, ore dictionary: - * itemDropUranium - * - * dusts bronzeDust Bronze Dust item, currently not meta sensitive clayDust Clay Dust item, - * currently not meta sensitive coalDust Coal Dust item, currently not meta sensitive copperDust - * Copper Dust item, currently not meta sensitive goldDust Gold Dust item, currently not meta - * sensitive ironDust Iron Dust item, currently not meta sensitive silverDust Silver Dust item, - * currently not meta sensitive smallIronDust Small Iron Dust item, currently not meta sensitive - * tinDust Tin Dust item, currently not meta sensitive hydratedCoalDust Hydrated Coal Dust item, - * currently not meta sensitive - * - * ingots refinedIronIngot Refined Iron Ingot item, currently not meta sensitive, ore - * dictionary: ingotRefinedIron copperIngot Copper Ingot item, currently not meta sensitive, ore - * dictionary: ingotCopper tinIngot Tin Ingot item, currently not meta sensitive, ore - * dictionary: ingotTin bronzeIngot Bronze Ingot item, currently not meta sensitive, ore - * dictionary: ingotBronze mixedMetalIngot Mixed Metal Ingot item, currently not meta sensitive - * uraniumIngot Uranium Ingot item, currently not meta sensitive, ore dictionary: ingotUranium - * - * tools/weapons (without electric tools) treetap Treetap item, meta = damage value wrench - * Wrench item, meta = damage value cutter Insulation Cutter item, meta = damage value - * constructionFoamSprayer Construction Foam Sprayer item, meta = charges (as of v1.45) - * - * bronzePickaxe Bronze Pickaxe item, meta = damage value bronzeAxe Bronze Axe item, meta = - * damage value bronzeSword Bronze Sword item, meta = damage value bronzeShovel Bronze Shovel - * item, meta = damage value bronzeHoe Bronze Hoe item, meta = damage value - * - * el. tools/devices/weapons miningDrill Mining Drill item, meta = visual charge indicator, - * implements IElectricItem diamondDrill Diamond Tipped Mining Drill item, meta = visual charge - * indicator, implements IElectricItem chainsaw Chainsaw item, meta = visual charge indicator, - * implements IElectricItem electricWrench Electric Wrench item, meta = visual charge indicator, - * implements IElectricItem electricTreetap Electric Treetap item, meta = visual charge - * indicator, implements IElectricItem miningLaser Mining Laser item, meta = visual charge - * indicator, implements IElectricItem - * - * ecMeter EC-Mater item, currently not meta sensitive odScanner Ore Density Scanner item, meta - * = damage value for charge level, implements IElectricItem ovScanner Ore Value Scanner item, - * meta = visual charge indicator, implements IElectricItem - * - * frequencyTransmitter Frequency Transmitter item, currently not meta sensitive - * - * nanoSaber Idle Nano Saber item, meta = visual charge indicator, implements IElectricItem - * enabledNanoSaber Enabled Nano Saber item, meta = visual charge indicator, implements - * IElectricItem - * - * armor/wearable rubberBoots Rubber Boots item, meta = damage value - * - * bronzeHelmet Bronze Helmet Armor item, meta = damage value bronzeChestplate Bronze Chestplate - * Armor item, meta = damage value bronzeLeggings Bronze Leggings Armor item, meta = damage - * value bronzeBoots Bronze Boots Armor item, meta = damage value - * - * compositeArmor Composite Armor item, meta = damage value for charge level - * - * nanoHelmet Nano Helmet Armor item, meta = visual charge indicator, implements IElectricItem - * nanoBodyarmor Nano Bodyarmor item, meta = visual charge indicator, implements IElectricItem - * nanoLeggings Nano Leggings Armor item, meta = visual charge indicator, implements - * IElectricItem nanoBoots Nano Boots Armor item, meta = visual charge indicator, implements - * IElectricItem - * - * quantumHelmet Quantum Helmet Armor item, meta = visual charge indicator, implements - * IElectricItem quantumBodyarmor Quantum Bodyarmor item, meta = visual charge indicator, - * implements IElectricItem quantumLeggings Quantum Leggings Armor item, meta = visual charge - * indicator, implements IElectricItem quantumBoots Quantum Boots Armor item, meta = visual - * charge indicator, implements IElectricItem - * - * jetpack Jetpack item, meta = damage value for fuel level electricJetpack Electric Jetpack - * item, meta = visual charge indicator, implements IElectricItem - * - * batPack BatPack item, meta = visual charge indicator, implements IElectricItem, can provide - * energy lapPack LapPack item, meta = visual charge indicator, implements IElectricItem, can - * provide energy - * - * cfPack CF Pack item, meta = charges (as of v1.45) - * - * solarHelmet Solar Helmet item, currently not meta sensitive staticBoots Static Boots item, - * currently not meta sensitive - * - * batteries reBattery Empty RE Battery item, currently not meta sensitive, implements - * IElectricItem chargedReBattery RE Battery item, meta = visual charge indicator, implements - * IElectricItem, can provide energy energyCrystal Energy Crystal item, meta = visual charge - * indicator, implements IElectricItem, can provide energy lapotronCrystal Lapotron Crystal - * item, meta = visual charge indicator, implements IElectricItem, can provide energy suBattery - * SU Battery item, currently not meta sensitive - * - * cables copperCableItem Copper Cable item, meta sensitive insulatedCopperCableItem Insulated - * Copper Cable item, meta sensitive - * - * goldCableItem Gold Cable item, meta sensitive insulatedGoldCableItem Insulated Gold Cable - * item, meta sensitive doubleInsulatedGoldCableItem Double Insulated Gold Cable item, meta - * sensitive - * - * ironCableItem Iron Cable item, meta sensitive insulatedIronCableItem Insulated Iron Cable - * item, meta sensitive doubleInsulatedIronCableItem Double Insulated Iron Cable item, meta - * sensitive trippleInsulatedIronCableItem Tripple Insulated Iron Cable item, meta sensitive - * - * glassFiberCableItem Glass Fiber Cable item, meta sensitive - * - * tinCableItem Tin Cable item, meta sensitive - * - * detectorCableItem Detector Cable item, meta sensitive splitterCableItem Splitter Cable item, - * meta sensitive - * - * cells/containers (without reactor components) cell Empty Cell item, currently not meta - * sensitive lavaCell Lava Cell item, currently not meta sensitive hydratedCoalCell Hydrated - * Coal Cell item, currently not meta sensitive bioCell Bio Cell item, currently not meta - * sensitive coalfuelCell Coalfuel Cell item, currently not meta sensitive biofuelCell Biofuel - * Cell item, currently not meta sensitive waterCell Water Cell item, currently not meta - * sensitive electrolyzedWaterCell Electrolyzed Water Cell item, currently not meta sensitive - * - * fuelCan Empty Fuel Can item, currently not meta sensitive filledFuelCan Fuel Can item, meta = - * fuel value (as of v1.45) - * - * tinCan Empty Tin Can item, currently not meta sensitive filledTinCan Filled Tin Can item, - * currently not meta sensitive - * - * reactor components uraniumCell Uranium Cell item, meta = damage value coolingCell Cooling - * Cell item, meta = damage value - * - * depletedIsotopeCell Depleted Isotope Cell item, meta = damage value reEnrichedUraniumCell - * Re-Enriched Uranium Cell item, currently not meta sensitive nearDepletedUraniumCell - * Near-Depleted Uranium Cell item, currently not meta sensitive - * - * integratedReactorPlating Integrated Reactor Plating item, meta = damage value - * integratedHeatDisperser Integrated Heat Disperser item, meta = damage value - * - * terraformer blueprints terraformerBlueprint Empty Terraformer Blueprint item, currently not - * meta sensitive cultivationTerraformerBlueprint Cultivation Terraformer Blueprint item, - * currently not meta sensitive irrigationTerraformerBlueprint Irrigation Terraformer Blueprint - * item, currently not meta sensitive chillingTerraformerBlueprint Chilling Terraformer - * Blueprint item, currently not meta sensitive desertificationTerraformerBlueprint - * Desertification Terraformer Blueprint item, currently not meta sensitive - * flatificatorTerraformerBlueprint Flatificator Terraformer Blueprint item, currently not meta - * sensitive mushroomTerraformerBlueprint Mushroom Terraformer Blueprint item, currently not - * meta sensitive - * - * diamond chain coalBall Coal Ball item, currently not meta sensitive compressedCoalBall - * Compressed Coal Ball item, currently not meta sensitive coalChunk Coal Chunk item, currently - * not meta sensitive industrialDiamond Industrial Diamond item, currently not meta sensitive, - * DEPRECATED - * - * recycler chain scrap Scrap item, currently not meta sensitive scrapBox Scrap Box item, - * currently not meta sensitive - * - * fuel production chain hydratedCoalClump Hydrated Coal Clump item, currently not meta - * sensitive plantBall Plant Ball item, currently not meta sensitive compressedPlantBall - * Compressed Plant Ball item, currently not meta sensitive - * - * painting painter Painter item, currently not meta sensitive - * - * blackPainter Black Painter item, meta = damage value redPainter Red Painter item, meta = - * damage value greenPainter Green Painter item, meta = damage value brownPainter Brown Painter - * item, meta = damage value bluePainter Blue Painter item, meta = damage value purplePainter - * Purple Painter item, meta = damage value cyanPainter Cyan Painter item, meta = damage value - * lightGreyPainter Light Grey Painter item, meta = damage value darkGreyPainter Dark Grey - * Painter item, meta = damage value pinkPainter Pink Painter item, meta = damage value - * limePainter Lime Painter item, meta = damage value yellowPainter Yellow Painter item, meta = - * damage value cloudPainter Cloud Painter item, meta = damage value magentaPainter Magenta - * Painter item, meta = damage value orangePainter Orange Painter item, meta = damage value - * whitePainter White Painter item, meta = damage value - * - * explosives + related dynamite Throwable Dynamite item, currently not meta sensitive - * stickyDynamite Throwable Sticky Dynamite item, currently not meta sensitive - * - * remote Dynamite Remote item, currently not meta sensitive - * - * misc intermediate recipe ingredients electronicCircuit Electronic Circuit item, currently not - * meta sensitive advancedCircuit Advanced Circuit item, currently not meta sensitive - * - * advancedAlloy Advanced Alloy item, currently not meta sensitive - * - * carbonFiber Raw Carbon Fiber item, currently not meta sensitive carbonMesh Raw Carbon Mesh - * item, currently not meta sensitive carbonPlate Carbon Plate item, currently not meta - * sensitive - * - * matter UU-Matter item, currently not meta sensitive iridiumOre Iridium Ore item, currently - * not meta sensitive iridiumPlate Iridium Plate item, currently not meta sensitive - * - * upgrade modules overclockerUpgrade overclocker upgrade item, meta sensitive - * transformerUpgrade transformer upgrade item, meta sensitive energyStorageUpgrade energy - * storage upgrade item, meta sensitive - * - * misc coin Coin item, currently not meta sensitive reinforcedDoor Reinforced Door item, - * currently not meta sensitive constructionFoamPellet Construction Foam Pellet item, currently - * not meta sensitive cropSeed Crop seeds, stuff stored in NBT, don't use for crafting recipes! - * cropnalyzer Cropnalyzer handheld device fertilizer Basic IC2Item, used to provide nutrients - * toCropBlocks hydratingCell Cell used to hydrate Crops, meta = Content, 0 = Full, 9999 = Near - * empty electricHoe Electric Hoe, meta = charge level solarHelmet Solar Helmet item, currently - * not meta sensitive terraWart Terra Wart item, cures potion effects weedEx Weed-EX can, meta = - * uses left + /* Possible values: + + // ores + copperOre; // Copper Ore block, currently not meta sensitive, meta in ItemStack set to 0, ore dictionary: oreCopper, null with enableWorldGenOreCopper=false + tinOre; // Tin Ore block, currently not meta sensitive, meta in ItemStack set to 0, ore dictionary: oreTin, null with enableWorldGenOreTin=false + uraniumOre; // Tin Ore block, currently not meta sensitive, meta in ItemStack set to 0, ore dictionary: oreUranium, null with enableWorldGenOreUranium=false + leadOre; // Lead Ore Block, currently not meta sensitive, meta in ItemStack set to 0, ore dictionary: oreLead, null with enableWorldGenOreLead=false + + // rubber related + + Rubber wood block, meta reflects the state, meta in ItemStack set to 0, ore dictionary: woodRubber (with meta 0), null with enableWorldGenTreeRubber=false + dropped (as an item) -> metadata 0 + block, no resin spot -> metadata 0 or 1 + block, wet resin spot -> metadata 2-5 (according to the side) + block, dry resin spot -> metadata 8-11 (wet state + 6) + + rubberWood; + rubberLeaves; // Rubber Leaves block, currently not meta sensitive, meta in ItemStack set to 0, null with enableWorldGenTreeRubber=false + rubberSapling; // Rubber Sapling block, currently not meta sensitive, meta in ItemStack set to 0, null with enableWorldGenTreeRubber=false + resinSheet; // Resin Sheet block, currently not meta sensitive + rubberTrampoline; // Rubber Trampoline block, meta reflects internal state, meta in ItemStack set to 0 + + // building/storage + ironFence; // Iron Fence block, currently not meta sensitive + + reinforcedStone; // Reinforced Stone block, currently not meta sensitive + reinforcedGlass; // Reinforced Glass block, currently not meta sensitive + reinforcedDoorBlock; // Reinforced Door block, meta reflects the state (see vanilla doors), meta in ItemStack set to 0 + + constructionreinforcedFoam; // Construction Reinforced Foam block, currently not meta sensitive + constructionFoam; // Construction Foam block, currently not meta sensitive + constructionFoamWall; // Construction Foam Wall block, meta = color, implements IPaintableBlock + scaffold; // Scaffold block, meta reflects internal physical model data + ironScaffold; // Scaffold block, meta reflects internal physical model data + + bronzeBlock; // Bronze block, meta sensitive + copperBlock; // Copper block, meta sensitive + tinBlock; // Tin block, meta sensitive + uraniumBlock; // Uranium block, meta sensitive + leadBlock; // Uranium block, meta sensitive + + // cables (when placed as a block, inventory items are different; TE implements IEnergyConductor) + + copperCableBlock; // Copper Cable block, meta sensitive + insulatedCopperCableBlock; // Insulated Copper Cable block, meta sensitive + + goldCableBlock; // Gold Cable block, meta sensitive + insulatedGoldCableBlock; // Insulated Gold Cable block, meta sensitive + doubleInsulatedGoldCableBlock; // Double Insulated Gold Cable block, meta sensitive + + ironCableBlock; // Iron Cable block, meta sensitive + insulatedIronCableBlock; // Insulated Iron Cable block, meta sensitive + doubleInsulatedIronCableBlock; // Double Insulated Iron Cable block, meta sensitive + trippleInsulatedIronCableBlock; // Tripple Insulated Iron Cable block, meta sensitive + + glassFiberCableBlock; // Glass Fiber Cable block, meta sensitive + + tinCableBlock; // Tin Cable block, meta sensitive + insulatedtinCableBlock; // Insulated Tin Cable item, meta sensitive + detectorCableBlock; // Detector Cable block, meta sensitive + splitterCableBlock; // Splitter Cable block, meta sensitive + + // generators + related (TE implements IEnergySource ex. reactorChamber) + + generator; // Generator block, meta sensitive + geothermalGenerator; // Geothermal Generator block, meta sensitive + waterMill; // Water Mill block, meta sensitive + solarPanel; // Solar Panel block, meta sensitive + windMill; // Wind Mill block, meta sensitive + nuclearReactor; // Nuclear Reactor block, meta sensitive + reactorChamber; // Reactor Chamber block, currently not meta sensitive + RTGenerator; // Radioisotope Thermoelectric Generator block, meta sensitive + semifluidGenerator; // Semifluid Generator block, meta sensitive + + + // energy storages (TE implements IEnergySource and IEnergyConductor) + + batBox; // BatBox block, meta sensitive + cesuUnit; // CESU Unit block, meta sensitive + mfeUnit; // MFE Unit block, meta sensitive + mfsUnit; // MFS Unit block, meta sensitive + + // transformers (TE implements IEnergySource and IEnergyConductor) + + lvTransformer; // LV Transformer block, meta sensitive + mvTransformer; // MV Transformer block, meta sensitive + hvTransformer; // HV Transformer block, meta sensitive + evTransformer; // EV Transformer block, meta sensitive + + // machines + related (TE implements IEnergySink ex. machine, miningPipe, miningPipeTip) + + machine; // Machine block, meta sensitive + advancedMachine; // Advanced Machine block, meta sensitive + + ironFurnace; // Iron Furnace block, meta sensitive + electroFurnace; // Electro Furnace block, meta sensitive + macerator; // Macerator block, meta sensitive + extractor; // Extractor block, meta sensitive + compressor; // Compressor block, meta sensitive + canner; // Canner block, meta sensitive + miner; // Miner block, meta sensitive + pump; // Pump block, meta sensitive + magnetizer; // Magnetizer block, meta sensitive + electrolyzer; // Electrolyzer block, meta sensitive + recycler; // Recycler block, meta sensitive + inductionFurnace; // Induction Furnace block, meta sensitive + massFabricator; // Mass Fabricator block, meta sensitive + terraformer; // Terraformer block, meta sensitive + teleporter; // Teleporter block, meta sensitive + teslaCoil; // Tesla Coil block, meta sensitive + luminator; // Passive (dark) Luminator block, meta = facing + activeLuminator; // Active (bright) Luminator block, meta = facing + centrifuge; // Centrifuge block, meta sensitive + metalformer; // MetalFormer block ,meta sensitive + orewashingplant; // Ore Wasching Plant,Meta sensitive + patternstorage; // Pattern Storage,Meta sensitive + scanner; // Scanner,Meta sensitive + replicator; // Replicator,Meta sensitive + + miningPipe; // Mining Pipe block, currently not meta sensitive, meta in ItemStack set to 0 + miningPipeTip; // Mining Pipe Tip block, currently not meta sensitive, meta in ItemStack set to 0 + + + // personal blocks + + personalSafe; // Personal Safe block, meta sensitive + tradeOMat; // Trade-O-Mat block, meta sensitive + energyOMat; // Energy-O-Mat block, meta sensitive + + // explosives + + industrialTnt; // Industrial TNT block, currently not meta sensitive + nuke; // Nuke block, currently not meta sensitive + dynamiteStick; // Dynamite Stick block, meta = placement, meta in ItemStack set to 0 + dynamiteStickWithRemote; // Dynamite Stick with Remote block, meta = placement, meta in ItemStack set to 0 + + // Agriculture Stuff + + crop; // Crop Block, empty, not meta sensitive + cropmatron; // Cropmatron machien block, meta sensititve + + // ----- items ----- + + // rubber + related + resin; // Resin item, currently not meta sensitive + rubber; // Rubber item, currently not meta sensitive, ore dictionary: itemRubber + + FluidCell; + + // Lithium -> Tritium + + reactorLithiumCell; // LithiumCell use in Reaktor, , meta = damage value + TritiumCell; // Tritium, currently not meta sensitive + + // Nuclear Fuel + + UranFuel; // , currently not meta sensitive + MOXFuel; // , currently not meta sensitive + Plutonium; // , currently not meta sensitive + smallPlutonium; // , currently not meta sensitive + Uran235; // , currently not meta sensitive + smallUran235; // , currently not meta sensitive + Uran238; // , currently not meta sensitive + + reactorDepletedUraniumSimple; // Depleted Uranium Cell items, currently not meta sensitive + reactorDepletedUraniumDual; + reactorDepletedUraniumQuad; + reactorDepletedMOXSimple; // Depleted MOX Cell items, currently not meta sensitive + reactorDepletedMOXDual; + reactorDepletedMOXQuad; + reactorMOXSimple; // Depleted MOX Cell items, currently not meta sensitive + reactorMOXDual; + reactorMOXQuad; + RTGPellets; + + + // Recipe Parts + + coil; // Coil, meta sensitive + elemotor; // electric motor, meta sensitive + powerunit; // Item Power Unit, meta sensitive + powerunitsmall; // Item Power Unit, meta sensitive + + + // ItemCasing + + casingcopper; // Copper ItemCasing, meta sensitive + casingtin; // Tin ItemCasing, meta sensitive + casingbronze; // Bronze ItemCasing, meta sensitive + casinggold; // Gold ItemCasing, meta sensitive + casingiron; // Iron ItemCasing, meta sensitive + @Deprecated + casingadviron; // Refined Iron ItemCasing, meta sensitive + casinglead; // Lead ItemCasing, meta sensitive + + // Crushed Ore + crushedIronOre; // Crushed Iron Ore, meta sensitive + crushedCopperOre; // Crushed Copper Ore, meta sensitive + crushedGoldOre; // Crushed Gold Ore, meta sensitive + crushedTinOre; // Crushed Tin Ore, meta sensitive + crushedUraniumOre; // Crushed Uranium Ore, meta sensitive + crushedSilverOre; // Crushed Silver Ore, meta sensitive + crushedLeadOre; // Crushed Lead Ore, meta sensitive + + + //Purify Crushed Ore + purifiedCrushedIronOre; // Purify Crushed Iron Ore, meta sensitive + purifiedCrushedCopperOre; // Purify Crushed Copper Ore, meta sensitive + purifiedCrushedGoldOre; // Purify Crushed Gold Ore, meta sensitive + purifiedCrushedTinOre; // Purify Crushed Tin Ore, meta sensitive + purifiedCrushedUraniumOre; // Purify Crushed Uranium Ore, meta sensitive + purifiedCrushedSilverOre; // Purify Crushed Silver Ore, meta sensitive + purifiedCrushedLeadOre; // Purify Crushed Lead Ore, meta sensitive + + // dusts + stoneDust; + bronzeDust; // Bronze Dust item, meta sensitive, ore dictionary: dustBronze + clayDust; // Clay Dust item, meta sensitive, ore dictionary: dustClay + coalDust; // Coal Dust item, meta sensitive, ore dictionary: dustCoal + copperDust; // Copper Dust item, meta sensitive, ore dictionary: dustCopper + goldDust; // Gold Dust item, meta sensitive, ore dictionary: dustGold + ironDust; // Iron Dust item, meta sensitive, ore dictionary: dustIron + silverDust; // Silver Dust item, meta sensitive, ore dictionary: dustSilver + tinDust; // Tin Dust item, meta sensitive, ore dictionary: dustTin + hydratedCoalDust; // Hydrated Coal Dust item, meta sensitive + leadDust; // Lead Dust item, meta sensitive, ore dictionary: dustLead + obsidianDust; // Obsidian Dust item, meta sensitive, ore dictionary: dustObsidian + lapiDust; // Lapi Dust item, meta sensitive, ore dictionary: dustLapi + sulfurDust; // Sulfur Dust item, meta sensitive, ore dictionary: dustSulfur + lithiumDust; // Lithium dust, meta sensitive, ore dictionary: dustLithium + + // small dusts + + smallIronDust; // Small Iron Dust item, meta sensitive + smallCopperDust; // Small Copper Dust item, meta sensitive + smallGoldDust; // Small Gold Dust item, meta sensitive + smallTinDust; // Small Tin Dust item, meta sensitive + smallSilverDust; // Small Silver Dust item, meta sensitive + smallLeadDust; // Small Lead Dust item, meta sensitive + smallSulfurDust; // Small Sulfur Dust item, meta sensitive + smallLithiumDust; // Small Lithium Dust item, meta sensitive + + + // ingots + @Deprecated + refinedIronIngot; // Refined Iron Ingot item, currently not meta sensitive, ore dictionary: ingotRefinedIron + copperIngot; // Copper Ingot item, currently not meta sensitive, ore dictionary: ingotCopper + tinIngot; // Tin Ingot item, currently not meta sensitive, ore dictionary: ingotTin + bronzeIngot; // Bronze Ingot item, currently not meta sensitive, ore dictionary: ingotBronze + mixedMetalIngot; // Mixed Metal Ingot item, currently not meta sensitive + leadIngot; // Lead Ingot item, currently not meta sensitive + + + // tools/weapons (without electric tools) + treetap; // Treetap item, meta = damage value + wrench; // Wrench item, meta = damage value + cutter; // Insulation Cutter item, meta = damage value + constructionFoamSprayer; // Construction Foam Sprayer item, meta = charges (as of v1.45) + + bronzePickaxe; // Bronze Pickaxe item, meta = damage value + bronzeAxe; // Bronze Axe item, meta = damage value + bronzeSword; // Bronze Sword item, meta = damage value + bronzeShovel; // Bronze Shovel item, meta = damage value + bronzeHoe; // Bronze Hoe item, meta = damage value + + ForgeHammer; // Refine Iron Hammer item, meta = damage value + + // el. tools/devices/weapons + miningDrill; // Mining Drill item, meta = damage value for charge level + diamondDrill; // Diamond Tipped Mining Drill item, meta = damage value for charge level + chainsaw; // Chainsaw item, meta = damage value for charge level + electricWrench; // Electric Wrench item, meta = damage value for charge level + electricTreetap; // Electric Treetap item, meta = damage value for charge level + miningLaser; // Mining Laser item, meta = damage value for charge level + + ecMeter; // EC-Mater item, meta = itemdata db index (as of v1.45) + odScanner; // Ore Density Scanner item, meta = damage value for charge level + ovScanner; // Ore Value Scanner item, meta = damage value for charge level + obscurator; // Obscurator item, meta = damage value for charge level + + frequencyTransmitter; // Frequency Transmitter item, meta = itemdata db index (as of v1.45) + + nanoSaber; // Idle Nano Saber item, meta = damage value for charge level + enabledNanoSaber; // Enabled Nano Saber item, meta = damage value for charge level + + toolbox; // Open/Empty toolbox, meta = Open (0) / Closed (1) + + // armor/wearable + hazmatHelmet; // Hazmat Helmet item, meta = damage value + hazmatChestplate; // Hazmat Chestplate item, meta = damage value + hazmatLeggings; // Hazmat Leggings item, meta = damage value + hazmatBoots; // Hazmat Boots item, meta = damage value + + bronzeHelmet; // Bronze Helmet Armor item, meta = damage value + bronzeChestplate; // Bronze Chestplate Armor item, meta = damage value + bronzeLeggings; // Bronze Leggings Armor item, meta = damage value + bronzeBoots; // Bronze Boots Armor item, meta = damage value + + compositeArmor; // Composite Armor item, meta = damage value for charge level + + nanoHelmet; // Nano Helmet Armor item, meta = damage value for charge level + nanoBodyarmor; // Nano Bodyarmor item, meta = damage value for charge level + nanoLeggings; // Nano Leggings Armor item, meta = damage value for charge level + nanoBoots; // Nano Boots Armor item, meta = damage value for charge level + + quantumHelmet; // Quantum Helmet Armor item, meta = damage value for charge level + quantumBodyarmor; // Quantum Bodyarmor item, meta = damage value for charge level + quantumLeggings; // Quantum Leggings Armor item, meta = damage value for charge level + quantumBoots; // Quantum Boots Armor item, meta = damage value for charge level + + jetpack; // Jetpack item, meta = damage value for fuel level + electricJetpack; // Electric Jetpack item, meta = damage value for charge level + + batPack; // BatPack item, meta = damage value for charge level + advbatPack; // Adv.BatPack item, meta = damage value for charge level + lapPack; // LapPack item, meta = damage value for charge level + energyPack; // EnergyPack item, meta = damage value for charge level + + cfPack; // CF Pack item, meta = charges (as of v1.45) + solarHelmet; // Solar Helmet, currently not meta sensitive + staticBoots; // Static Boots, currently not meta sensitive + nightvisionGoggles; // Nightvision Goggles, meta = damage value for charge level + + // batteries + reBattery; // Empty RE Battery item, currently not meta sensitive + chargedReBattery; // RE Battery item, meta = damage value for charge level + advBattery; // Adv Batteryitem, meta = damage value for charge level + energyCrystal; // Energy Crystal item, meta = damage value for charge level + lapotronCrystal; // Lapotron Crystal item, meta = damage value for charge level + suBattery; // SU Battery item, meta = damage value for charge level + + // cables + copperCableItem; // Copper Cable item, meta sensitive + insulatedCopperCableItem; // Insulated Copper Cable item, meta sensitive + + goldCableItem; // Gold Cable item, meta sensitive + insulatedGoldCableItem; // Insulated Gold Cable item, meta sensitive + + @Deprecated + doubleInsulatedGoldCableItem; // Double Insulated Gold Cable item, meta sensitive + + ironCableItem; // Iron Cable item, meta sensitive + insulatedIronCableItem; // Insulated Iron Cable item, meta sensitive + + @Deprecated + doubleInsulatedIronCableItem; // Double Insulated Iron Cable item, meta sensitive + @Deprecated + trippleInsulatedIronCableItem; // Tripple Insulated Iron Cable item, meta sensitive + insulatedTinCableItem; + glassFiberCableItem; // Glass Fiber Cable item, meta sensitive + tinCableItem; // Tin Cable item, meta sensitive + + + detectorCableItem; // Detector Cable item, meta sensitive + splitterCableItem; // Splitter Cable item, meta sensitive + + // cells/containers (without reactor components) + + cell; // Empty Cell item, meta sensitive + lavaCell; // Lava Cell item, meta sensitive + waterCell; // Water Cell item, meta sensitive + UuMatterCell; // UUMatter Cell item, meta sensitive + CFCell; // constructionFoam Cell item, meta sensitive + + + fuelRod; // Empy Fuel Rod item, currently not meta sensitive + hydratedCoalCell; // Hydrated Coal Cell item, currently not meta sensitive + bioCell; // Bio Cell item, currently not meta sensitive + coalfuelCell; // Coalfuel Cell item, currently not meta sensitive + biofuelCell; // Biofuel Cell item, currently not meta sensitive + electrolyzedWaterCell; // Electrolyzed Water Cell item, currently not meta sensitive + airCell; // Compressed Air item, currently not meta sensitive + + fuelCan; // Empty Fuel Can item, currently not meta sensitive + filledFuelCan; // Fuel Can item, meta = fuel value (as of v1.45) + + tinCan; // Empty Tin Can item, currently not meta sensitive + filledTinCan; // Filled Tin Can item, currently not meta sensitive + + // reactor components + reactorUraniumSimple; // Uranium Cell items, meta = consumed uranium ticks + reactorUraniumDual; + reactorUraniumQuad; + + reactorCoolantSimple; + reactorCoolantTriple ; // Coolant Cell item, NBT for heat-storage, meta is 0-10000 for display + reactorCoolantSix; + + reactorPlating; // Integrated Reactor Plating item, currently not meta sensitive + reactorPlatingHeat; + reactorPlatingExplosive; + + reactorHeatSwitch; // Integrated Heat Disperser item, NBT for heat-storage, meta is 0-10000 for display + reactorHeatSwitchCore; + reactorHeatSwitchSpread; + reactorHeatSwitchDiamond; + + reactorVent; // Heat Venting component, NBT for heat-storage, meta is 0-10000 for display + reactorVentCore; + reactorVentGold; + reactorVentSpread;// Special: Does not store heat + reactorVentDiamond; + + reactorReflector; // Increase efficiency without additional ticks, NBT for heat-storage, meta is 0-10000 for display + reactorReflectorThick; // Increase efficiency without additional ticks, NBT for heat-storage, meta is 0-10000 for display + reactorCondensator; // Consumes redstone to absorb heat, NBT for storage, meta is 0-10000 for display + reactorCondensatorLap; // Consumes redstone/lapis to absorb heat, mNBT for storage, meta is 0-10000 for display + + // terraformer blueprints + terraformerBlueprint; // Empty Terraformer Blueprint item, currently not meta sensitive + cultivationTerraformerBlueprint; // Cultivation Terraformer Blueprint item, currently not meta sensitive + irrigationTerraformerBlueprint; // Irrigation Terraformer Blueprint item, currently not meta sensitive + chillingTerraformerBlueprint; // Chilling Terraformer Blueprint item, currently not meta sensitive + desertificationTerraformerBlueprint; // Desertification Terraformer Blueprint item, currently not meta sensitive + flatificatorTerraformerBlueprint; // Flatificator Terraformer Blueprint item, currently not meta sensitive + mushroomTerraformerBlueprint; // Mushroom Terraformer Blueprint item, currently not meta sensitive + + // diamond chain + coalBall; // Coal Ball item, currently not meta sensitive + compressedCoalBall; // Compressed Coal Ball item, currently not meta sensitive + coalChunk; // Coal Chunk item, currently not meta sensitive + industrialDiamond; // Industrial Diamond item, currently not meta sensitive, DEPRECATED + + // recycler chain + scrap; // Scrap item, currently not meta sensitive + scrapBox; // Scrap Box item, currently not meta sensitive + + // fuel production chain + hydratedCoalClump; // Hydrated Coal Clump item, currently not meta sensitive + plantBall; // Plant Ball item, currently not meta sensitive + compressedPlantBall; // Compressed Plant Ball item, currently not meta sensitive + + // painting + painter; // Painter item, currently not meta sensitive + + blackPainter; // Black Painter item, meta = damage value + redPainter; // Red Painter item, meta = damage value + greenPainter; // Green Painter item, meta = damage value + brownPainter; // Brown Painter item, meta = damage value + bluePainter; // Blue Painter item, meta = damage value + purplePainter; // Purple Painter item, meta = damage value + cyanPainter; // Cyan Painter item, meta = damage value + lightGreyPainter; // Light Grey Painter item, meta = damage value + darkGreyPainter; // Dark Grey Painter item, meta = damage value + pinkPainter; // Pink Painter item, meta = damage value + limePainter; // Lime Painter item, meta = damage value + yellowPainter; // Yellow Painter item, meta = damage value + cloudPainter; // Cloud Painter item, meta = damage value + magentaPainter; // Magenta Painter item, meta = damage value + orangePainter; // Orange Painter item, meta = damage value + whitePainter; // White Painter item, meta = damage value + + // explosives + related + dynamite; // Throwable Dynamite item, currently not meta sensitive + stickyDynamite; // Throwable Sticky Dynamite item, currently not meta sensitive + + remote; // Dynamite Remote item, currently not meta sensitive + + // misc intermediate recipe ingredients + electronicCircuit; // Electronic Circuit item, currently not meta sensitive + advancedCircuit; // Advanced Circuit item, currently not meta sensitive + + advancedAlloy; // Advanced Alloy item, currently not meta sensitive + + carbonFiber; // Raw Carbon Fiber item, currently not meta sensitive + carbonMesh; // Raw Carbon Mesh item, currently not meta sensitive + carbonPlate; // Carbon Plate item, currently not meta sensitive + + matter; // UUA item, currently not meta sensitive + iridiumOre; // Iridium Ore item, currently not meta sensitive + iridiumPlate; // Iridium Plate item, currently not meta sensitive + + + // Metal Plates + + platecopper; // Metal plate item, meta sensitive + platetin; // Metal plate item, meta sensitive + platebronze; // Metal plate item, meta sensitive + plategold; // Metal plate item, meta sensitive + plateiron; // Metal plate item, meta sensitive + platelead; // Metal plate item, meta sensitive + platelapi; // Metal plate item, meta sensitive + plateobsidian; // Metal plate item, meta sensitive + plateadviron; // Metal plate item, meta sensitive + + // Metal Dense Plates + denseplatecopper; // Metal dense plate item, meta sensitive + denseplatetin; // Metal dense plate item, meta sensitive + denseplatebronze; // Metal dense plate item, meta sensitive + denseplategold; // Metal dense plate item, meta sensitive + denseplateiron; // Metal dense plate item, meta sensitive + @Deprecated + denseplateadviron; // Metal dense plate item, meta sensitive + denseplatelead; // Metal dense plate item, meta sensitive + denseplatelapi; // Metal dense plate item, meta sensitive + denseplateobsidian; // Metal dense plate item, meta sensitive + + + + // upgrade modules + overclockerUpgrade; // overclocker upgrade item, meta sensitive + transformerUpgrade; // transformer upgrade item, meta sensitive + energyStorageUpgrade; // energy storage upgrade item, meta sensitive + ejectorUpgrade; // ejector upgrade item, meta sensitive + + // misc + coin; // Coin item, currently not meta sensitive + reinforcedDoor; // Reinforced Door item, currently not meta sensitive + constructionFoamPowder; // Construction Foam Powder item, currently not meta sensitive + grinPowder; // Poisonous ingrident, currently not meta sensitive + debug; // Debug item, currently not meta sensitive + boatCarbon; // Carbon Fiber Canoe item, meta sensitive + boatRubber; // Rubber Dinghy item, meta sensitive + boatRubberBroken; // Damaged Rubber Dinghy item, meta sensitive + boatElectric; // Electric Boat item, meta sensitive + + //Agriculture + cropSeed; // Crop seeds, stuff stored in NBT, don't use for crafting recipes! + cropnalyzer; // Cropnalyzer handheld device + fertilizer; // Basic IC2Item, used to provide nutrients toCropBlocks + hydratingCell; // Cell used to hydrate Crops, meta = Content, 0= Full, 9999 = Near empty + electricHoe; // Electric Hoe, Metadata indicates charge level + terraWart; // Mystic opposite of NEtherWart, cures StatusEffects, simply consumeable + weedEx; // Spraying can of WEED-EX, meta indicates usages left + + //Boozeception + mugEmpty; // Simple stone mug + coffeeBeans; // Harvested CoffeeBeans + coffeePowder; // Processed Coffee Beans, used to craft drinkable Coffee + mugCoffee; // Mug of Coffee, Meta indicates status 0 = cold, 1 = Normal, 2 = Sugar'd + hops; // Hops, harvested freshly from crop + barrel; // Carried Barrel, metadata encrypts the information about the liquid inside + blockBarrel; // Unobtainable "placed barrel", TileEntity controlling the Fermentation process + mugBooze; // Mug filled with booze, metadata encrypts the information about the liquid inside + */ /** @@ -344,12 +582,10 @@ public final class Items * * @return IC2 package name, if unable to be determined defaults to ic2 */ - private static String getPackage() - { + private static String getPackage() { Package pkg = Items.class.getPackage(); - if (pkg != null) - { + if (pkg != null) { String packageName = pkg.getName(); return packageName.substring(0, packageName.length() - ".api.item".length()); @@ -360,3 +596,4 @@ public final class Items private static Class Ic2Items; } + diff --git a/APIs/ic2/api/recipe/ICannerBottleRecipeManager.java b/APIs/ic2/api/recipe/ICannerBottleRecipeManager.java new file mode 100644 index 000000000..97fd94576 --- /dev/null +++ b/APIs/ic2/api/recipe/ICannerBottleRecipeManager.java @@ -0,0 +1,51 @@ +package ic2.api.recipe; + +import java.util.Map; + +import net.minecraft.item.ItemStack; + +public interface ICannerBottleRecipeManager { + /** + * Adds a recipe to the machine. + * + * @param container Container to be filled + * @param fill Item to fill into the container + * @param output Filled container + */ + public void addRecipe(IRecipeInput container, IRecipeInput fill, ItemStack output); + + /** + * Gets the recipe output for the given input. + * + * @param container Container to be filled + * @param fill Item to fill into the container + * @param adjustInput modify the input according to the recipe's requirements + * @param acceptTest allow either container or fill to be null to see if either of them is part of a recipe + * @return Recipe output, or null if none + */ + public RecipeOutput getOutputFor(ItemStack container, ItemStack fill, boolean adjustInput, boolean acceptTest); + + /** + * Gets a list of recipes. + * + * You're a mad evil scientist if you ever modify this. + * + * @return List of recipes + */ + public Map getRecipes(); + + + public static class Input { + public Input(IRecipeInput container, IRecipeInput fill) { + this.container = container; + this.fill = fill; + } + + public boolean matches(ItemStack container, ItemStack fill) { + return this.container.matches(container) && this.fill.matches(fill); + } + + public final IRecipeInput container; + public final IRecipeInput fill; + } +} diff --git a/APIs/ic2/api/recipe/ICannerEnrichRecipeManager.java b/APIs/ic2/api/recipe/ICannerEnrichRecipeManager.java new file mode 100644 index 000000000..0f05ad79d --- /dev/null +++ b/APIs/ic2/api/recipe/ICannerEnrichRecipeManager.java @@ -0,0 +1,54 @@ +package ic2.api.recipe; + +import java.util.Map; + +import net.minecraft.item.ItemStack; + +import net.minecraftforge.fluids.FluidStack; + +public interface ICannerEnrichRecipeManager { + /** + * Adds a recipe to the machine. + * + * @param input Fluid input + * @param additive Item to enrich the fluid with + * @param output Output fluid + */ + public void addRecipe(FluidStack input, IRecipeInput additive, FluidStack output); + + /** + * Gets the recipe output for the given input. + * + * @param input Fluid input + * @param additive Item to enrich the fluid with + * @param adjustInput modify the input according to the recipe's requirements + * @param acceptTest allow input or additive to be null to see if either of them is part of a recipe + * @return Recipe output, or null if none, output fluid in nbt + */ + public RecipeOutput getOutputFor(FluidStack input, ItemStack additive, boolean adjustInput, boolean acceptTest); + + /** + * Gets a list of recipes. + * + * You're a mad evil scientist if you ever modify this. + * + * @return List of recipes + */ + public Map getRecipes(); + + + public static class Input { + public Input(FluidStack fluid, IRecipeInput additive) { + this.fluid = fluid; + this.additive = additive; + } + + public boolean matches(FluidStack fluid, ItemStack additive) { + return (this.fluid == null || this.fluid.isFluidEqual(fluid)) && + this.additive.matches(additive); + } + + public final FluidStack fluid; + public final IRecipeInput additive; + } +} diff --git a/APIs/ic2/api/recipe/ICraftingRecipeManager.java b/APIs/ic2/api/recipe/ICraftingRecipeManager.java new file mode 100644 index 000000000..756eaf634 --- /dev/null +++ b/APIs/ic2/api/recipe/ICraftingRecipeManager.java @@ -0,0 +1,26 @@ +package ic2.api.recipe; + +import net.minecraft.item.ItemStack; + +/** + * Recipe manager interface for crafting recipes. + * + * @author Richard + */ +public interface ICraftingRecipeManager { + /** + * Adds a shaped crafting recipe. + * + * @param output Recipe output + * @param input Recipe input format + */ + public void addRecipe(ItemStack output, Object... input); + + /** + * Adds a shapeless crafting recipe. + * + * @param output Recipe output + * @param input Recipe input + */ + public void addShapelessRecipe(ItemStack output, Object... input); +} diff --git a/APIs/ic2/api/recipe/ILiquidAcceptManager.java b/APIs/ic2/api/recipe/ILiquidAcceptManager.java new file mode 100644 index 000000000..4f377b904 --- /dev/null +++ b/APIs/ic2/api/recipe/ILiquidAcceptManager.java @@ -0,0 +1,10 @@ +package ic2.api.recipe; + +import java.util.Set; + +import net.minecraftforge.fluids.Fluid; + +public interface ILiquidAcceptManager { + boolean acceptsFluid(Fluid fluid); + Set getAcceptedFluids(); +} diff --git a/APIs/ic2/api/recipe/IListRecipeManager.java b/APIs/ic2/api/recipe/IListRecipeManager.java new file mode 100644 index 000000000..5c0d30628 --- /dev/null +++ b/APIs/ic2/api/recipe/IListRecipeManager.java @@ -0,0 +1,36 @@ +package ic2.api.recipe; + +import java.util.List; + +import net.minecraft.item.ItemStack; + +/** + * Recipe manager interface for basic lists. + * + * @author Richard + */ +public interface IListRecipeManager extends Iterable { + /** + * Adds a stack to the list. + * + * @param stack Stack to add + */ + public void add(ItemStack stack); + + /** + * Checks whether the specified stack is in the list. + * + * @param stack Stack to check + * @return Whether the stack is in the list + */ + public boolean contains(ItemStack stack); + + /** + * Gets the list of stacks. + * + * You're a mad evil scientist if you ever modify this. + * + * @return List of stacks + */ + public List getStacks(); +} diff --git a/APIs/ic2/api/recipe/IMachineRecipeManager.java b/APIs/ic2/api/recipe/IMachineRecipeManager.java new file mode 100644 index 000000000..a788e09a4 --- /dev/null +++ b/APIs/ic2/api/recipe/IMachineRecipeManager.java @@ -0,0 +1,40 @@ +package ic2.api.recipe; + +import java.util.Map; + +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; + +/** + * Recipe manager interface for basic machines. + * + * @author RichardG, Player + */ +public interface IMachineRecipeManager { + /** + * Adds a recipe to the machine. + * + * @param input Recipe input + * @param metadata meta data for additional recipe properties, may be null + * @param outputs Recipe outputs, zero or more depending on the machine + */ + public void addRecipe(IRecipeInput input, NBTTagCompound metadata, ItemStack... outputs); + + /** + * Gets the recipe output for the given input. + * + * @param input Recipe input + * @param adjustInput modify the input according to the recipe's requirements + * @return Recipe output, or null if none + */ + public RecipeOutput getOutputFor(ItemStack input, boolean adjustInput); + + /** + * Gets a list of recipes. + * + * You're a mad evil scientist if you ever modify this. + * + * @return List of recipes + */ + public Map getRecipes(); +} diff --git a/APIs/ic2/api/recipe/IPatternStorage.java b/APIs/ic2/api/recipe/IPatternStorage.java new file mode 100644 index 000000000..f51f0de7d --- /dev/null +++ b/APIs/ic2/api/recipe/IPatternStorage.java @@ -0,0 +1,15 @@ +package ic2.api.recipe; + +import net.minecraft.item.ItemStack; + +public interface IPatternStorage { + + boolean transferPattern(ItemStack itemstack, int amountUU , int amountEU); + + int[] getPatternvalus(ItemStack itemstack); + + short getPatternCount(); + + ItemStack getPatternItemstack(int index); + +} diff --git a/APIs/ic2/api/recipe/IRecipeInput.java b/APIs/ic2/api/recipe/IRecipeInput.java new file mode 100644 index 000000000..0c842d639 --- /dev/null +++ b/APIs/ic2/api/recipe/IRecipeInput.java @@ -0,0 +1,31 @@ +package ic2.api.recipe; + +import java.util.List; + +import net.minecraft.item.ItemStack; + +public interface IRecipeInput { + /** + * Check if subject matches this recipe input, ignoring the amount. + * + * @param subject ItemStack to check + * @return true if it matches the requirement + */ + boolean matches(ItemStack subject); + + /** + * Determine the minimum input stack size. + * + * @return input amount required + */ + int getAmount(); + + /** + * List all possible inputs (best effort). + * + * The stack size is undefined, use getAmount to get the correct one. + * + * @return list of inputs, may be incomplete + */ + List getInputs(); +} diff --git a/APIs/ic2/api/recipe/IScrapboxManager.java b/APIs/ic2/api/recipe/IScrapboxManager.java new file mode 100644 index 000000000..41b694dcc --- /dev/null +++ b/APIs/ic2/api/recipe/IScrapboxManager.java @@ -0,0 +1,13 @@ +package ic2.api.recipe; + +import java.util.Map; + +import net.minecraft.item.ItemStack; + +public interface IScrapboxManager { + void addDrop(ItemStack drop, float rawChance); + + ItemStack getDrop(ItemStack input, boolean adjustInput); + + Map getDrops(); +} diff --git a/APIs/ic2/api/recipe/ISemiFluidFuelManager.java b/APIs/ic2/api/recipe/ISemiFluidFuelManager.java new file mode 100644 index 000000000..cf6af6542 --- /dev/null +++ b/APIs/ic2/api/recipe/ISemiFluidFuelManager.java @@ -0,0 +1,32 @@ +package ic2.api.recipe; + +import java.util.Map; + +import net.minecraftforge.fluids.Fluid; + + +public interface ISemiFluidFuelManager extends ILiquidAcceptManager { + /** + * Add a new fluid to the semi fluid generator. + * + * @param fluidName the fluid to burn + * @param amount amount of fluid to consume per tick + * @param power amount of energy generated per tick + */ + void addFluid(String fluidName, int amount, double power); + + BurnProperty getBurnProperty(Fluid fluid); + + Map getBurnProperties(); + + + public static class BurnProperty { + public BurnProperty(int amount, double power) { + this.amount = amount; + this.power = power; + } + + public final int amount; + public final double power; + } +} diff --git a/APIs/ic2/api/recipe/RecipeInputItemStack.java b/APIs/ic2/api/recipe/RecipeInputItemStack.java new file mode 100644 index 000000000..a2a9195d7 --- /dev/null +++ b/APIs/ic2/api/recipe/RecipeInputItemStack.java @@ -0,0 +1,38 @@ +package ic2.api.recipe; + +import java.util.Arrays; +import java.util.List; + +import net.minecraft.item.ItemStack; + +import net.minecraftforge.oredict.OreDictionary; + +public class RecipeInputItemStack implements IRecipeInput { + public RecipeInputItemStack(ItemStack input) { + this(input, input.stackSize); + } + + public RecipeInputItemStack(ItemStack input, int amount) { + this.input = input; + this.amount = amount; + } + + @Override + public boolean matches(ItemStack subject) { + return subject.itemID == input.itemID && + (subject.getItemDamage() == input.getItemDamage() || input.getItemDamage() == OreDictionary.WILDCARD_VALUE); + } + + @Override + public int getAmount() { + return amount; + } + + @Override + public List getInputs() { + return Arrays.asList(input); + } + + public final ItemStack input; + public final int amount; +} diff --git a/APIs/ic2/api/recipe/RecipeInputOreDict.java b/APIs/ic2/api/recipe/RecipeInputOreDict.java new file mode 100644 index 000000000..eb804b2aa --- /dev/null +++ b/APIs/ic2/api/recipe/RecipeInputOreDict.java @@ -0,0 +1,45 @@ +package ic2.api.recipe; + +import java.util.List; + +import net.minecraft.item.ItemStack; + +import net.minecraftforge.oredict.OreDictionary; + +public class RecipeInputOreDict implements IRecipeInput { + public RecipeInputOreDict(String input) { + this(input, 1); + } + + public RecipeInputOreDict(String input, int amount) { + this.input = input; + this.amount = amount; + } + + @Override + public boolean matches(ItemStack subject) { + List inputs = OreDictionary.getOres(input); + + for (ItemStack input : inputs) { + if (subject.itemID == input.itemID && + (subject.getItemDamage() == input.getItemDamage() || input.getItemDamage() == OreDictionary.WILDCARD_VALUE)) { + return true; + } + } + + return false; + } + + @Override + public int getAmount() { + return amount; + } + + @Override + public List getInputs() { + return OreDictionary.getOres(input); + } + + public final String input; + public final int amount; +} diff --git a/APIs/ic2/api/recipe/RecipeOutput.java b/APIs/ic2/api/recipe/RecipeOutput.java new file mode 100644 index 000000000..e0ee71ab9 --- /dev/null +++ b/APIs/ic2/api/recipe/RecipeOutput.java @@ -0,0 +1,21 @@ +package ic2.api.recipe; + +import java.util.Arrays; +import java.util.List; + +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; + +public final class RecipeOutput { + public RecipeOutput(NBTTagCompound metadata, List items) { + this.metadata = metadata; + this.items = items; + } + + public RecipeOutput(NBTTagCompound metadata, ItemStack... items) { + this(metadata, Arrays.asList(items)); + } + + public final List items; + public final NBTTagCompound metadata; +} diff --git a/APIs/ic2/api/recipe/Recipes.java b/APIs/ic2/api/recipe/Recipes.java new file mode 100644 index 000000000..849c4cab4 --- /dev/null +++ b/APIs/ic2/api/recipe/Recipes.java @@ -0,0 +1,55 @@ +package ic2.api.recipe; + + + +/** + * General recipe registry. + * + * @author Richard + */ +public class Recipes { + public static IMachineRecipeManager macerator; + public static IMachineRecipeManager extractor; + public static IMachineRecipeManager compressor; + public static IMachineRecipeManager centrifuge; + public static IMachineRecipeManager recycler; + public static IMachineRecipeManager metalformerExtruding; + public static IMachineRecipeManager metalformerCutting; + public static IMachineRecipeManager metalformerRolling; + public static IMachineRecipeManager oreWashing; + public static IMachineRecipeManager Scanner; + public static ICannerBottleRecipeManager cannerBottle; + public static ICannerEnrichRecipeManager cannerEnrich; + + /** + * Reference amplifier values: + * + * 5000: Scrap + * 45000: Scrapbox + * + * As Parameter for the Amplification Value you have to use the NBTTagCompound + * + * NBTTagCompound nbt = new NBTTagCompound(); + * nbt.setInteger("amplification", aValue); + * matterAmplifier.addRecipe(yourStack, nbt); + */ + public static IMachineRecipeManager matterAmplifier; + /** + * Reference scrap box chance values: + * + * 0.1: Diamond + * 0.5: Cake, Gold Helmet, Iron Ore, Gold Ore + * 1.0: Wooden tools, Soul Sand, Sign, Leather, Feather, Bone + * 1.5: Apple, Bread + * 2.0: Netherrack, Rotten Flesh + * 3.0: Grass, Gravel + * 4.0: Stick + * 5.0: Dirt, Wooden Hoe + */ + public static IScrapboxManager scrapboxDrops; + public static IListRecipeManager recyclerBlacklist; + public static ICraftingRecipeManager advRecipes; + + public static ISemiFluidFuelManager semiFluidGenerator; + +} diff --git a/APIs/ic2/api/tile/ExplosionWhitelist.java b/APIs/ic2/api/tile/ExplosionWhitelist.java new file mode 100644 index 000000000..01322b6c0 --- /dev/null +++ b/APIs/ic2/api/tile/ExplosionWhitelist.java @@ -0,0 +1,46 @@ +package ic2.api.tile; + +import java.util.*; + +import net.minecraft.block.Block; + +/** + * Blocks on this whitelist will not resist an explosion but won't be destroyed. + * + * The explosion code by default ignores blocks which absorb more than 1000 explosion power to + * prevent abusing personal safes, Trade-O-Mats and other blocks to serve as a cheap and + * invulnerable reactor chambers. Said blocks will not shield the explosion and won't get + * destroyed. + */ +public final class ExplosionWhitelist { + /** + * Add a block to the whitelist. + * + * @param block block to add + */ + public static void addWhitelistedBlock(Block block) { + whitelist.add(block); + } + + /** + * Remove a block from the whitelist. + * + * @param block block to remove + */ + public static void removeWhitelistedBlock(Block block) { + whitelist.remove(block); + } + + /** + * Check if a block is on the whitelist. + * + * @param block block to check if whitelisted + * @return Whether the block is whitelisted + */ + public static boolean isBlockWhitelisted(Block block) { + return whitelist.contains(block); + } + + private static Set whitelist = new HashSet(); +} + diff --git a/APIs/ic2/api/tile/IEnergyStorage.java b/APIs/ic2/api/tile/IEnergyStorage.java new file mode 100644 index 000000000..d20eb0475 --- /dev/null +++ b/APIs/ic2/api/tile/IEnergyStorage.java @@ -0,0 +1,61 @@ +package ic2.api.tile; + +import net.minecraftforge.common.ForgeDirection; + +/** + * Interface implemented by the tile entity of energy storage blocks. + */ +public interface IEnergyStorage { + /** + * Get the amount of energy currently stored in the block. + * + * @return Energy stored in the block + */ + public int getStored(); + + /** + * Set the amount of energy currently stored in the block. + * + * @param energy stored energy + */ + public void setStored(int energy); + + /** + * Add the specified amount of energy. + * + * Use negative values to decrease. + * + * @param amount of energy to add + * @return Energy stored in the block after adding the specified amount + */ + public int addEnergy(int amount); + + /** + * Get the maximum amount of energy the block can store. + * + * @return Maximum energy stored + */ + public int getCapacity(); + + /** + * Get the block's energy output. + * + * @return Energy output in EU/t + */ + public int getOutput(); + + /** + * Get the block's energy output. + * + * @return Energy output in EU/t + */ + public double getOutputEnergyUnitsPerTick(); + + /** + * Get whether this block can have its energy used by an adjacent teleporter. + * + * @param side side the teleporter is draining energy from + * @return Whether the block is teleporter compatible + */ + public boolean isTeleporterCompatible(ForgeDirection side); +} diff --git a/APIs/ic2/api/tile/IWrenchable.java b/APIs/ic2/api/tile/IWrenchable.java new file mode 100644 index 000000000..f01441698 --- /dev/null +++ b/APIs/ic2/api/tile/IWrenchable.java @@ -0,0 +1,59 @@ +package ic2.api.tile; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; + +/** + * Allows a tile entity to make use of the wrench's removal and rotation functions. + */ +public interface IWrenchable { + /** + * Determine if the wrench can be used to set the block's facing. + * Called before wrenchCanRemove(). + * + * @param entityPlayer player using the wrench, may be null + * @param side block's side the wrench was clicked on + * @return Whether the wrenching was done and the wrench should be damaged + */ + boolean wrenchCanSetFacing(EntityPlayer entityPlayer, int side); + + /** + * Get the block's facing. + * + * @return Block facing + */ + short getFacing(); + + /** + * Set the block's facing + * + * @param facing facing to set the block to + */ + void setFacing(short facing); + + /** + * Determine if the wrench can be used to remove the block. + * Called if wrenchSetFacing fails. + * + * @param entityPlayer player using the wrench, may be null + * @return Whether the wrenching was done and the wrench should be damaged + */ + boolean wrenchCanRemove(EntityPlayer entityPlayer); + + /** + * Determine the probability to drop the block as it is. + * The first entry in getBlockDropped will be replaced by blockid:meta if the drop is successful. + * + * @return Probability from 0 to 1 + */ + float getWrenchDropRate(); + + /** + * Determine the item the block will drop when the wrenching is successful. + * + * @param entityPlayer player using the wrench, may be null + * @return Item to drop, may be null + */ + ItemStack getWrenchDrop(EntityPlayer entityPlayer); +} + diff --git a/APIs/org/modstats/IModstatsReporter.java b/APIs/org/modstats/IModstatsReporter.java index 8fe62722b..f275bf737 100644 --- a/APIs/org/modstats/IModstatsReporter.java +++ b/APIs/org/modstats/IModstatsReporter.java @@ -29,6 +29,7 @@ package org.modstats; public interface IModstatsReporter { - public void registerMod(Object mod); - public void doManualCheck(); + public void registerMod(Object mod); + + public void doManualCheck(); } diff --git a/APIs/org/modstats/ModVersionData.java b/APIs/org/modstats/ModVersionData.java index ab3fbcd09..4139a1536 100644 --- a/APIs/org/modstats/ModVersionData.java +++ b/APIs/org/modstats/ModVersionData.java @@ -32,83 +32,86 @@ import java.util.Map; public class ModVersionData { - public String prefix; - public String name; - public String version; - public String downloadUrl; - public String changeLogUrl; - - public Map extraFields; - - - public ModVersionData() - { - extraFields = new HashMap(); - } - - public ModVersionData(String prefix, String name, String version) - { - this.prefix = prefix; - this.name = name; - this.version = version; - extraFields = new HashMap(); - } + public String prefix; + public String name; + public String version; + public String downloadUrl; + public String changeLogUrl; - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + ((changeLogUrl == null) ? 0 : changeLogUrl.hashCode()); - result = prime * result + ((downloadUrl == null) ? 0 : downloadUrl.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((prefix == null) ? 0 : prefix.hashCode()); - result = prime * result + ((version == null) ? 0 : version.hashCode()); - return result; - } + public Map extraFields; + + public ModVersionData() + { + extraFields = new HashMap(); + } + + public ModVersionData(String prefix, String name, String version) + { + this.prefix = prefix; + this.name = name; + this.version = version; + extraFields = new HashMap(); + } + + @Override + public int hashCode() + { + final int prime = 31; + int result = 1; + result = prime * result + ((changeLogUrl == null) ? 0 : changeLogUrl.hashCode()); + result = prime * result + ((downloadUrl == null) ? 0 : downloadUrl.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((prefix == null) ? 0 : prefix.hashCode()); + result = prime * result + ((version == null) ? 0 : version.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) + { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ModVersionData other = (ModVersionData) obj; + if (changeLogUrl == null) + { + if (other.changeLogUrl != null) + return false; + } + else if (!changeLogUrl.equals(other.changeLogUrl)) + return false; + if (downloadUrl == null) + { + if (other.downloadUrl != null) + return false; + } + else if (!downloadUrl.equals(other.downloadUrl)) + return false; + if (name == null) + { + if (other.name != null) + return false; + } + else if (!name.equals(other.name)) + return false; + if (prefix == null) + { + if (other.prefix != null) + return false; + } + else if (!prefix.equals(other.prefix)) + return false; + if (version == null) + { + if (other.version != null) + return false; + } + else if (!version.equals(other.version)) + return false; + return true; + } - @Override - public boolean equals(Object obj) - { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ModVersionData other = (ModVersionData) obj; - if (changeLogUrl == null) - { - if (other.changeLogUrl != null) - return false; - } else if (!changeLogUrl.equals(other.changeLogUrl)) - return false; - if (downloadUrl == null) - { - if (other.downloadUrl != null) - return false; - } else if (!downloadUrl.equals(other.downloadUrl)) - return false; - if (name == null) - { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (prefix == null) - { - if (other.prefix != null) - return false; - } else if (!prefix.equals(other.prefix)) - return false; - if (version == null) - { - if (other.version != null) - return false; - } else if (!version.equals(other.version)) - return false; - return true; - } - - } diff --git a/APIs/org/modstats/ModsUpdateEvent.java b/APIs/org/modstats/ModsUpdateEvent.java index a29eb817c..649ef1004 100644 --- a/APIs/org/modstats/ModsUpdateEvent.java +++ b/APIs/org/modstats/ModsUpdateEvent.java @@ -37,28 +37,28 @@ import cpw.mods.fml.common.FMLLog; @Cancelable public class ModsUpdateEvent extends Event { - private List updatedMods; - - public ModsUpdateEvent() - { - updatedMods = new LinkedList(); - } - - public void add(ModVersionData data) - { - if(!updatedMods.contains(data)) - { - updatedMods.add(data); - } - else - { - FMLLog.info("ModsUpdateEvent shouldn't have same mods data", data); - } - } - - public List getUpdatedMods() - { - return updatedMods; - } - + private List updatedMods; + + public ModsUpdateEvent() + { + updatedMods = new LinkedList(); + } + + public void add(ModVersionData data) + { + if (!updatedMods.contains(data)) + { + updatedMods.add(data); + } + else + { + FMLLog.info("ModsUpdateEvent shouldn't have same mods data", data); + } + } + + public List getUpdatedMods() + { + return updatedMods; + } + } diff --git a/APIs/org/modstats/ModstatInfo.java b/APIs/org/modstats/ModstatInfo.java index 1927e52f3..19da5d86f 100644 --- a/APIs/org/modstats/ModstatInfo.java +++ b/APIs/org/modstats/ModstatInfo.java @@ -34,23 +34,26 @@ import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) -public @interface ModstatInfo +public @interface ModstatInfo { - /** - * Modstats mod prefix. - * @return - */ - public String prefix(); - - /** - * Mod name. Use this if your mod doesn't have @Mod annotation - * @return - */ - public String name() default ""; + /** + * Modstats mod prefix. + * + * @return + */ + public String prefix(); - /** - * Mod version. Use this if your mod doesn't have @Mod annotation - * @return - */ - public String version() default ""; + /** + * Mod name. Use this if your mod doesn't have @Mod annotation + * + * @return + */ + public String name() default ""; + + /** + * Mod version. Use this if your mod doesn't have @Mod annotation + * + * @return + */ + public String version() default ""; } diff --git a/APIs/org/modstats/Modstats.java b/APIs/org/modstats/Modstats.java index c9753e4d8..8527e853e 100644 --- a/APIs/org/modstats/Modstats.java +++ b/APIs/org/modstats/Modstats.java @@ -31,59 +31,61 @@ import cpw.mods.fml.common.FMLLog; public class Modstats { - private static final Modstats INSTANCE = new Modstats(); - private static final String CLASS_TEMPLATE = "org.modstats.reporter.v%d.Reporter"; - private IModstatsReporter reporter; + private static final Modstats INSTANCE = new Modstats(); + private static final String CLASS_TEMPLATE = "org.modstats.reporter.v%d.Reporter"; + private IModstatsReporter reporter; + + private Modstats() + { + reporter = locateReporter(); + } + + public IModstatsReporter getReporter() + { + return reporter; + } + + private IModstatsReporter locateReporter() + { + int i = 1; + Class latest = null; + while (i < 100) + { + try + { + Class candidate = Class.forName(String.format(CLASS_TEMPLATE, i)); + if (IModstatsReporter.class.isAssignableFrom(candidate)) + { + latest = candidate; + } + } + catch (Exception e) + { + break; + } + i++; + } + if (latest == null) + { + FMLLog.warning("Modstats reporter class not found."); + } + else + { + try + { + return (IModstatsReporter) latest.newInstance(); + } + catch (Exception e) + { + FMLLog.warning("Modstats reporter class can't be instantiated."); + } + } + return null; + } + + public static Modstats instance() + { + return INSTANCE; + } - private Modstats() - { - reporter = locateReporter(); - } - - public IModstatsReporter getReporter() - { - return reporter; - } - - private IModstatsReporter locateReporter() - { - int i=1; - Class latest = null; - while(i<100) - { - try - { - Class candidate = Class.forName(String.format(CLASS_TEMPLATE, i)); - if(IModstatsReporter.class.isAssignableFrom(candidate)) - { - latest = candidate; - } - } - catch (Exception e) { - break; - } - i++; - } - if(latest == null) - { - FMLLog.warning("Modstats reporter class not found."); - } - else - { - try - { - return (IModstatsReporter)latest.newInstance(); - } catch (Exception e) - { - FMLLog.warning("Modstats reporter class can't be instantiated."); - } - } - return null; - } - - public static Modstats instance() - { - return INSTANCE; - } - } diff --git a/APIs/org/modstats/reporter/v1/Config.java b/APIs/org/modstats/reporter/v1/Config.java index 708e3a93e..61eff08aa 100644 --- a/APIs/org/modstats/reporter/v1/Config.java +++ b/APIs/org/modstats/reporter/v1/Config.java @@ -36,38 +36,38 @@ import cpw.mods.fml.common.Loader; public class Config { - private static final String CONFIG_NAME = "modstats.cfg"; - - public boolean allowUpdates; - public boolean betaNotifications; - public boolean forCurrentMinecraftVersion; - public boolean logOnly; - - public Config() - { - File configLocation = new File(Loader.instance().getConfigDir(), CONFIG_NAME); - Configuration configuration = new Configuration(configLocation); - configuration.load(); - - Property prop = configuration.get("updates", "AllowUpdates", true); - prop.comment = "Allow to send current mod versions to the server and check for updates.\nIt allows to mod authors to see mod's popularity. Please don't disable it without necessity"; - allowUpdates = prop.getBoolean(true); - - prop = configuration.get("updates", "LogOnly", false); - prop.comment = "Don't display chat message, just add message to the log."; - logOnly = prop.getBoolean(false); - - prop = configuration.get("updates", "BetaNotifications", false); - prop.comment = "Set true to receive notifications about beta versions. Otherwise you will only receive information about stable versions"; - betaNotifications = prop.getBoolean(false); - - prop = configuration.get("updates", "ForCurrentMinecraftVersion", false); - prop.comment = "Check for updates only for current MC version.\nEx:if you have MC 1.4.2 and ForCurrentMinecraftVersion is true, then you wouldn't receive notifications about versions for MC 1.4.5"; - forCurrentMinecraftVersion = prop.getBoolean(false); - - configuration.save(); - - FMLLog.info("[Modstats] Config loaded. allowUpdates: %b, betaNotification: %b, strict: %b", allowUpdates, betaNotifications, forCurrentMinecraftVersion); - } + private static final String CONFIG_NAME = "modstats.cfg"; + + public boolean allowUpdates; + public boolean betaNotifications; + public boolean forCurrentMinecraftVersion; + public boolean logOnly; + + public Config() + { + File configLocation = new File(Loader.instance().getConfigDir(), CONFIG_NAME); + Configuration configuration = new Configuration(configLocation); + configuration.load(); + + Property prop = configuration.get("updates", "AllowUpdates", true); + prop.comment = "Allow to send current mod versions to the server and check for updates.\nIt allows to mod authors to see mod's popularity. Please don't disable it without necessity"; + allowUpdates = prop.getBoolean(true); + + prop = configuration.get("updates", "LogOnly", false); + prop.comment = "Don't display chat message, just add message to the log."; + logOnly = prop.getBoolean(false); + + prop = configuration.get("updates", "BetaNotifications", false); + prop.comment = "Set true to receive notifications about beta versions. Otherwise you will only receive information about stable versions"; + betaNotifications = prop.getBoolean(false); + + prop = configuration.get("updates", "ForCurrentMinecraftVersion", false); + prop.comment = "Check for updates only for current MC version.\nEx:if you have MC 1.4.2 and ForCurrentMinecraftVersion is true, then you wouldn't receive notifications about versions for MC 1.4.5"; + forCurrentMinecraftVersion = prop.getBoolean(false); + + configuration.save(); + + FMLLog.info("[Modstats] Config loaded. allowUpdates: %b, betaNotification: %b, strict: %b", allowUpdates, betaNotifications, forCurrentMinecraftVersion); + } } diff --git a/APIs/org/modstats/reporter/v1/DataSender.java b/APIs/org/modstats/reporter/v1/DataSender.java index 5cbbcc081..475359b66 100644 --- a/APIs/org/modstats/reporter/v1/DataSender.java +++ b/APIs/org/modstats/reporter/v1/DataSender.java @@ -66,229 +66,231 @@ import cpw.mods.fml.common.versioning.ComparableVersion; class DataSender extends Thread { - private static final String urlAutoTemplate = "http://modstats.org/api/v1/report?mc=%s&user=%s&data=%s&sign=%s&beta=%b&strict=%b"; - private static final String urlManualTemplate = "http://modstats.org/api/v1/check?mc=%s&user=%s&data=%s&sign=%s&beta=%b&strict=%b"; - - private final Reporter reporter; - public final boolean manual; - - public DataSender(Reporter reporter, boolean manual) - { - this.reporter = reporter; - this.manual = manual; - } - - private String toHexString(byte[] bytes) { - char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; - char[] hexChars = new char[bytes.length * 2]; - int v; - for ( int j = 0; j < bytes.length; j++ ) { - v = bytes[j] & 0xFF; - hexChars[j*2] = hexArray[v/16]; - hexChars[j*2 + 1] = hexArray[v%16]; - } - return new String(hexChars); - } - - private String getPlayerId() throws IOException - { - File statDir = new File(Minecraft.getMinecraft().mcDataDir, "stats"); - if(!statDir.exists()) - { - statDir.mkdirs(); - } - String mac = ""; - try - { - InetAddress address = InetAddress.getLocalHost(); - NetworkInterface ni = NetworkInterface.getByInetAddress(address); - byte[] macArray = ni.getHardwareAddress(); - if(macArray != null) - { - mac = toHexString(macArray); - } - } - catch(Exception ex) - { - } - File uidFile = new File(statDir, "player.uid"); - if(uidFile.exists() && uidFile.canRead() && uidFile.length() == 32+mac.length()) - { - String data = Files.toString(uidFile, Charsets.US_ASCII); - String storedMac = data.substring(32); - if(storedMac.equalsIgnoreCase(mac)) - return data.substring(0, 32); - } - uidFile.createNewFile(); - if(uidFile.canWrite()) - { - String uid = UUID.randomUUID().toString().replace("-", ""); - FileOutputStream output = new FileOutputStream(uidFile); - output.write((uid+mac).getBytes()); - output.close(); - return uid; - } - return ""; - } - - private String getSignature(String data) - { - return Hashing.md5().hashString(data).toString(); - } - - private String getData() - { - StringBuilder b = new StringBuilder(); - for (Map.Entry item : reporter.registeredMods.entrySet()) - { - b.append(item.getKey()).append("+").append(item.getValue().version).append("$"); - } - return b.toString(); - } - - private boolean checkIsNewer(String current, String received) - { - return new ComparableVersion(received).compareTo(new ComparableVersion(current)) > 0; - } - - - private void parseResponse(String response) - { - try - { - JsonRootNode json = (new JdomParser()).parse(response); - //empty result - if(!json.isNode("mods")) - { - FMLLog.info("[Modstats] Empty result"); - return; - } - List modList = json.getArrayNode("mods"); - ModsUpdateEvent event = new ModsUpdateEvent(); - for (JsonNode modObject : modList) - { - String prefix = modObject.getStringValue("code"); - if(!reporter.registeredMods.containsKey(prefix)) - { - FMLLog.warning("[Modstats] Extra mod '%s' in service response", prefix); - continue; - } - String version = modObject.getStringValue("ver"); - if(version==null || version.equals(reporter.registeredMods.get(prefix).version)) - { - continue; - } - if(checkIsNewer(reporter.registeredMods.get(prefix).version, version)) - { - ModVersionData data = new ModVersionData(prefix, reporter.registeredMods.get(prefix).name, version); - Map fields = modObject.getFields(); - for (Map.Entry entry : fields.entrySet()) - { - String fieldName = entry.getKey().getText(); - if(fieldName.equals("code") || fieldName.equals("ver")) - continue; - if(!(entry.getValue() instanceof JsonStringNode)) - { - FMLLog.warning(String.format("[Modstats] Too complex data in response for field '%s'.", fieldName)); - continue; - } - String value = ((JsonStringNode)entry.getValue()).getText(); - if(fieldName.equals("chlog")) - { - data.changeLogUrl = value; - } - else if(fieldName.equals("link")) - { - data.downloadUrl = value; - } - else - { - data.extraFields.put(fieldName, value); - } - } - event.add(data); - } - - } - if(event.getUpdatedMods().size() > 0) - { - MinecraftForge.EVENT_BUS.post(event); - } - if(!event.isCanceled() && event.getUpdatedMods().size() > 0) - { - List updatedModsToOutput = event.getUpdatedMods(); - StringBuilder builder = new StringBuilder("Updates found: "); - Iterator iterator = updatedModsToOutput.iterator(); - while(iterator.hasNext()) - { - ModVersionData modVersionData = iterator.next(); - builder.append(modVersionData.name) - .append(" (") - .append(modVersionData.version) - .append(")") - .append(iterator.hasNext()?",":"."); - } - FMLLog.info("[Modstats] %s", builder.toString()); - if(!reporter.config.logOnly && FMLCommonHandler.instance().getSide().isClient()) - { - Minecraft mc = FMLClientHandler.instance().getClient(); - int maxTries = 30; - while(mc.thePlayer==null && maxTries>0) - { - try - { - sleep(1000); - } catch (InterruptedException e) - { - } - maxTries--; - } - if(mc.thePlayer != null) - { - mc.thePlayer.addChatMessage(builder.toString()); - } - } - } - - } catch (InvalidSyntaxException e) - { - FMLLog.warning("[Modstats] Can't parse response: '%s'.", e.getMessage()); - } - } + private static final String urlAutoTemplate = "http://modstats.org/api/v1/report?mc=%s&user=%s&data=%s&sign=%s&beta=%b&strict=%b"; + private static final String urlManualTemplate = "http://modstats.org/api/v1/check?mc=%s&user=%s&data=%s&sign=%s&beta=%b&strict=%b"; - - @Override - public void run() - { - try - { - String data = getData(); - String playerId = getPlayerId(); - String hash = getSignature(playerId+"!"+data); - String template = manual?urlManualTemplate:urlAutoTemplate; - String mcVersion = new CallableMinecraftVersion(null).minecraftVersion(); - URL url = new URL(String.format(template, mcVersion, playerId, data, hash, reporter.config.betaNotifications, reporter.config.forCurrentMinecraftVersion)); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setConnectTimeout(5000); - connection.setReadTimeout(5000); - BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); - String line; - String out = ""; - while ((line = reader.readLine()) != null) { - //in most cases it will contain just one line - out += line; - } - reader.close(); - parseResponse(out); - } catch (MalformedURLException e) - { - FMLLog.warning("[Modstats] Invalid stat report url"); - } catch (IOException e) - { - FMLLog.info("[Modstats] Stat wasn't reported '"+e.getMessage()+"'"); - } catch(Exception e) - { - FMLLog.warning("[Modstats] Something wrong: "+e.toString()); - } - } + private final Reporter reporter; + public final boolean manual; + + public DataSender(Reporter reporter, boolean manual) + { + this.reporter = reporter; + this.manual = manual; + } + + private String toHexString(byte[] bytes) + { + char[] hexArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; + char[] hexChars = new char[bytes.length * 2]; + int v; + for (int j = 0; j < bytes.length; j++) + { + v = bytes[j] & 0xFF; + hexChars[j * 2] = hexArray[v / 16]; + hexChars[j * 2 + 1] = hexArray[v % 16]; + } + return new String(hexChars); + } + + private String getPlayerId() throws IOException + { + File statDir = new File(FMLClientHandler.instance().getClient().mcDataDir, "stats"); + if (!statDir.exists()) + { + statDir.mkdirs(); + } + String mac = ""; + try + { + InetAddress address = InetAddress.getLocalHost(); + NetworkInterface ni = NetworkInterface.getByInetAddress(address); + byte[] macArray = ni.getHardwareAddress(); + if (macArray != null) + { + mac = toHexString(macArray); + } + } + catch (Exception ex) + { + } + File uidFile = new File(statDir, "player.uid"); + if (uidFile.exists() && uidFile.canRead() && uidFile.length() == 32 + mac.length()) + { + String data = Files.toString(uidFile, Charsets.US_ASCII); + String storedMac = data.substring(32); + if (storedMac.equalsIgnoreCase(mac)) + return data.substring(0, 32); + } + uidFile.createNewFile(); + if (uidFile.canWrite()) + { + String uid = UUID.randomUUID().toString().replace("-", ""); + FileOutputStream output = new FileOutputStream(uidFile); + output.write((uid + mac).getBytes()); + output.close(); + return uid; + } + return ""; + } + + private String getSignature(String data) + { + return Hashing.md5().hashString(data).toString(); + } + + private String getData() + { + StringBuilder b = new StringBuilder(); + for (Map.Entry item : reporter.registeredMods.entrySet()) + { + b.append(item.getKey()).append("+").append(item.getValue().version).append("$"); + } + return b.toString(); + } + + private boolean checkIsNewer(String current, String received) + { + return new ComparableVersion(received).compareTo(new ComparableVersion(current)) > 0; + } + + private void parseResponse(String response) + { + try + { + JsonRootNode json = (new JdomParser()).parse(response); + // empty result + if (!json.isNode("mods")) + { + FMLLog.info("[Modstats] Empty result"); + return; + } + List modList = json.getArrayNode("mods"); + ModsUpdateEvent event = new ModsUpdateEvent(); + for (JsonNode modObject : modList) + { + String prefix = modObject.getStringValue("code"); + if (!reporter.registeredMods.containsKey(prefix)) + { + FMLLog.warning("[Modstats] Extra mod '%s' in service response", prefix); + continue; + } + String version = modObject.getStringValue("ver"); + if (version == null || version.equals(reporter.registeredMods.get(prefix).version)) + { + continue; + } + if (checkIsNewer(reporter.registeredMods.get(prefix).version, version)) + { + ModVersionData data = new ModVersionData(prefix, reporter.registeredMods.get(prefix).name, version); + Map fields = modObject.getFields(); + for (Map.Entry entry : fields.entrySet()) + { + String fieldName = entry.getKey().getText(); + if (fieldName.equals("code") || fieldName.equals("ver")) + continue; + if (!(entry.getValue() instanceof JsonStringNode)) + { + FMLLog.warning(String.format("[Modstats] Too complex data in response for field '%s'.", fieldName)); + continue; + } + String value = ((JsonStringNode) entry.getValue()).getText(); + if (fieldName.equals("chlog")) + { + data.changeLogUrl = value; + } + else if (fieldName.equals("link")) + { + data.downloadUrl = value; + } + else + { + data.extraFields.put(fieldName, value); + } + } + event.add(data); + } + + } + if (event.getUpdatedMods().size() > 0) + { + MinecraftForge.EVENT_BUS.post(event); + } + if (!event.isCanceled() && event.getUpdatedMods().size() > 0) + { + List updatedModsToOutput = event.getUpdatedMods(); + StringBuilder builder = new StringBuilder("Updates found: "); + Iterator iterator = updatedModsToOutput.iterator(); + while (iterator.hasNext()) + { + ModVersionData modVersionData = iterator.next(); + builder.append(modVersionData.name).append(" (").append(modVersionData.version).append(")").append(iterator.hasNext() ? "," : "."); + } + FMLLog.info("[Modstats] %s", builder.toString()); + if (!reporter.config.logOnly && FMLCommonHandler.instance().getSide().isClient()) + { + Minecraft mc = FMLClientHandler.instance().getClient(); + int maxTries = 30; + while (mc.thePlayer == null && maxTries > 0) + { + try + { + sleep(1000); + } + catch (InterruptedException e) + { + } + maxTries--; + } + if (mc.thePlayer != null) + { + mc.thePlayer.addChatMessage(builder.toString()); + } + } + } + + } + catch (InvalidSyntaxException e) + { + FMLLog.warning("[Modstats] Can't parse response: '%s'.", e.getMessage()); + } + } + + @Override + public void run() + { + try + { + String data = getData(); + String playerId = getPlayerId(); + String hash = getSignature(playerId + "!" + data); + String template = manual ? urlManualTemplate : urlAutoTemplate; + String mcVersion = new CallableMinecraftVersion(null).minecraftVersion(); + URL url = new URL(String.format(template, mcVersion, playerId, data, hash, reporter.config.betaNotifications, reporter.config.forCurrentMinecraftVersion)); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setConnectTimeout(5000); + connection.setReadTimeout(5000); + BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + String line; + String out = ""; + while ((line = reader.readLine()) != null) + { + // in most cases it will contain just one line + out += line; + } + reader.close(); + parseResponse(out); + } + catch (MalformedURLException e) + { + FMLLog.warning("[Modstats] Invalid stat report url"); + } + catch (IOException e) + { + FMLLog.info("[Modstats] Stat wasn't reported '" + e.getMessage() + "'"); + } + catch (Exception e) + { + FMLLog.warning("[Modstats] Something wrong: " + e.toString()); + } + } } diff --git a/APIs/org/modstats/reporter/v1/Reporter.java b/APIs/org/modstats/reporter/v1/Reporter.java index 2744b6d79..06b4b079d 100644 --- a/APIs/org/modstats/reporter/v1/Reporter.java +++ b/APIs/org/modstats/reporter/v1/Reporter.java @@ -42,104 +42,101 @@ import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.Mod; - public class Reporter implements IModstatsReporter { - public Map registeredMods; - private DataSender sender; - public Config config; - - /** - * At least one auto check was completed successfully - */ - private boolean checkedAuto; + public Map registeredMods; + private DataSender sender; + public Config config; - public Reporter() - { - checkedAuto = false; - registeredMods = new ConcurrentHashMap(2, 0.9f, 1); - MinecraftForge.EVENT_BUS.register(this); - config = new Config(); - } - - - private void startCheck(boolean manual) - { - if(!config.allowUpdates) - return; - //only manual check is allowed on servers - if(!FMLCommonHandler.instance().getSide().isClient() && !manual) - return; - if(registeredMods.isEmpty()) - return; - DataSender currentSender = sender; - if(!manual && checkedAuto) - return; - if(currentSender!=null && (currentSender.manual == false || manual)) - return; - currentSender = new DataSender(this, manual); - currentSender.start(); - sender = currentSender; - - } - - @ForgeSubscribe - public void worldLoad(WorldEvent.Load event) - { - startCheck(false); - } + /** + * At least one auto check was completed successfully + */ + private boolean checkedAuto; - - @Override - public void registerMod(Object mod) - { - if(!config.allowUpdates) - return; - if(mod == null) - { - FMLLog.warning("[Modstats] Can't register null mod."); - return; - } - ModstatInfo info = mod.getClass().getAnnotation(ModstatInfo.class); - if(info == null) - { - FMLLog.warning("[Modstats] ModstatsInfo annotation not found for given mod."); - return; - } - - if(info.prefix() == null || info.prefix().equals("")) - { - FMLLog.warning("[Modstats] Mod prefix can't be empty."); - return; - } - Mod modData = mod.getClass().getAnnotation(Mod.class); - ModVersionData data; - if(modData == null) - { - if(info.name() == null || info.name().equals("")) - { - FMLLog.warning("[Modstats] Mod name can't be empty."); - return; - } - if(info.version() == null || info.version().equals("")) - { - FMLLog.warning("[Modstats] Mod version can't be empty."); - return; - } - data = new ModVersionData(info.prefix(), info.name(), info.version()); - } - else - { - data = new ModVersionData(info.prefix(), modData.name(), modData.version()); - } - registeredMods.put(info.prefix(), data); - } + public Reporter() + { + checkedAuto = false; + registeredMods = new ConcurrentHashMap(2, 0.9f, 1); + MinecraftForge.EVENT_BUS.register(this); + config = new Config(); + } - @Override - public void doManualCheck() - { - startCheck(true); - } + private void startCheck(boolean manual) + { + if (!config.allowUpdates) + return; + // only manual check is allowed on servers + if (!FMLCommonHandler.instance().getSide().isClient() && !manual) + return; + if (registeredMods.isEmpty()) + return; + DataSender currentSender = sender; + if (!manual && checkedAuto) + return; + if (currentSender != null && (currentSender.manual == false || manual)) + return; + currentSender = new DataSender(this, manual); + currentSender.start(); + sender = currentSender; + + } + + @ForgeSubscribe + public void worldLoad(WorldEvent.Load event) + { + startCheck(false); + } + + @Override + public void registerMod(Object mod) + { + if (!config.allowUpdates) + return; + if (mod == null) + { + FMLLog.warning("[Modstats] Can't register null mod."); + return; + } + ModstatInfo info = mod.getClass().getAnnotation(ModstatInfo.class); + if (info == null) + { + FMLLog.warning("[Modstats] ModstatsInfo annotation not found for given mod."); + return; + } + + if (info.prefix() == null || info.prefix().equals("")) + { + FMLLog.warning("[Modstats] Mod prefix can't be empty."); + return; + } + Mod modData = mod.getClass().getAnnotation(Mod.class); + ModVersionData data; + if (modData == null) + { + if (info.name() == null || info.name().equals("")) + { + FMLLog.warning("[Modstats] Mod name can't be empty."); + return; + } + if (info.version() == null || info.version().equals("")) + { + FMLLog.warning("[Modstats] Mod version can't be empty."); + return; + } + data = new ModVersionData(info.prefix(), info.name(), info.version()); + } + else + { + data = new ModVersionData(info.prefix(), modData.name(), modData.version()); + } + registeredMods.put(info.prefix(), data); + } + + @Override + public void doManualCheck() + { + startCheck(true); + } } diff --git a/APIs/universalelectricity/compatibility/Compatibility.java b/APIs/universalelectricity/compatibility/Compatibility.java index 8362841d0..60df3d5cd 100644 --- a/APIs/universalelectricity/compatibility/Compatibility.java +++ b/APIs/universalelectricity/compatibility/Compatibility.java @@ -4,67 +4,77 @@ import universalelectricity.core.UniversalElectricity; import universalelectricity.core.electricity.NetworkLoader; import cpw.mods.fml.common.Loader; -/** The Universal Electricity compatibility module allows your mod to be compatible with most major +/** + * The Universal Electricity compatibility module allows your mod to be compatible with most major * power systems in Minecraft. - * - * @author Calclavia, Micdoodle */ + * + * @author Calclavia, Micdoodle + */ public class Compatibility { - /** Version of build craft api UE was compiled with */ - public static String BCx_VERSION = "@BCxVersion@"; - /** Version of industrial craft api UE was compiled with */ - public static String ICx_VERSION = "@ICxVersion@"; - /** Version of thermal expansion api UE was compiled with */ - public static String TEx_VERSION = "@TExVersion@"; + /** Version of build craft api compiled with */ + public static String BCx_VERSION = "@BCxVersion@"; + /** Version of industrial craft api compiled with */ + public static String ICx_VERSION = "@ICxVersion@"; + /** Version of thermal expansion api compiled with */ + public static String TEx_VERSION = "@TExVersion@"; - /** Has the initiate method been called yet */ - public static boolean INIT = false; + /** Has the initiate method been called */ + public static boolean INIT = false; - /** Ratio of Build craft(MJ) power to UE power(KW). Multiply BC3 power by this to convert to UE */ - public static float BC3_RATIO = 1; - /** Ratio of Industrial craft(EU) power to UE power(KW). Multiply IC2 power by this to convert to UE */ - public static float IC2_RATIO = 0.04f; + /** Ratio of Build craft(MJ) power to UE power(KW). Multiply BC3 power by this to convert to UE */ + public static float BC3_RATIO = 1; + /** + * Ratio of Industrial craft(EU) power to UE power(KW). Multiply IC2 power by this to convert to + * UE + */ + public static float IC2_RATIO = 0.04f; - /** Ratio of UE power(KW) to Industrial craft(EU) power. Multiply UE power by this to convert it to IC2 power */ - public static float TO_IC2_RATIO = 1 / IC2_RATIO; - /** Ratio of UE power(KW) to Build craft(MJ) power. Multiply UE power by this to convert it to BC3 power */ - public static float TO_BC_RATIO = 1 / BC3_RATIO; + /** + * Ratio of UE power(KW) to Industrial craft(EU) power. Multiply UE power by this to convert it + * to IC2 power + */ + public static float TO_IC2_RATIO = 1 / IC2_RATIO; + /** + * Ratio of UE power(KW) to Build craft(MJ) power. Multiply UE power by this to convert it to + * BC3 power + */ + public static float TO_BC_RATIO = 1 / BC3_RATIO; - /** You must call this function to enable the Universal Network module. */ - public static void initiate() - { - if (!INIT) - { - /** Outputs basic version information */ - System.out.println("[UniversalElectricity] Loading compatibility API version " + UniversalElectricity.VERSION); - System.out.println("[UniversalElectricity] Compiled with IndustrialCraft API version " + Compatibility.ICx_VERSION); - System.out.println("[UniversalElectricity] Compiled with BuildCraft API version " + Compatibility.BCx_VERSION); - System.out.println("[UniversalElectricity] Compiled with ThermalExpansion API version " + Compatibility.TEx_VERSION); + /** You must call this function to enable the Universal Network module. */ + public static void initiate() + { + if (!INIT) + { + /** Outputs basic version information */ + System.out.println("[UniversalElectricity] Loading compatibility API version " + UniversalElectricity.VERSION); + System.out.println("[UniversalElectricity] Compiled with IndustrialCraft API version " + Compatibility.ICx_VERSION); + System.out.println("[UniversalElectricity] Compiled with BuildCraft API version " + Compatibility.BCx_VERSION); + System.out.println("[UniversalElectricity] Compiled with ThermalExpansion API version " + Compatibility.TEx_VERSION); - /** Loads the configuration and sets all the values. */ - UniversalElectricity.CONFIGURATION.load(); - IC2_RATIO = (float) UniversalElectricity.CONFIGURATION.get("Compatiblity", "IndustrialCraft Conversion Ratio", IC2_RATIO).getDouble(IC2_RATIO); - BC3_RATIO = (float) UniversalElectricity.CONFIGURATION.get("Compatiblity", "BuildCraft Conversion Ratio", BC3_RATIO).getDouble(BC3_RATIO); - TO_IC2_RATIO = 1 / IC2_RATIO; - TO_BC_RATIO = 1 / BC3_RATIO; - UniversalElectricity.CONFIGURATION.save(); + /** Loads the configuration and sets all the values. */ + UniversalElectricity.CONFIGURATION.load(); + IC2_RATIO = (float) UniversalElectricity.CONFIGURATION.get("Compatiblity", "IndustrialCraft Conversion Ratio", IC2_RATIO).getDouble(IC2_RATIO); + BC3_RATIO = (float) UniversalElectricity.CONFIGURATION.get("Compatiblity", "BuildCraft Conversion Ratio", BC3_RATIO).getDouble(BC3_RATIO); + TO_IC2_RATIO = 1 / IC2_RATIO; + TO_BC_RATIO = 1 / BC3_RATIO; + UniversalElectricity.CONFIGURATION.save(); - /** Sets the main network to the Universal version */ - NetworkLoader.setNetworkClass(UniversalNetwork.class); - } - } + NetworkLoader.setNetworkClass(UniversalNetwork.class); + } + } - /** Check to see using the FML loader too see if IC2 is loaded */ - public static boolean isIndustrialCraft2Loaded() - { - return Loader.isModLoaded("IC2"); - } + /** Checks using the FML loader too see if IC2 is loaded */ + public static boolean isIndustrialCraft2Loaded() + { + return Loader.isModLoaded("IC2"); + } - /** Check to see using the FML loader too see if BC3 is loaded */ - public static boolean isBuildcraftLoaded() - { - return Loader.isModLoaded("BuildCraft|Energy"); - } + /** Checks using the FML loader too see if BC3 is loaded */ + public static boolean isBuildcraftLoaded() + { + return Loader.isModLoaded("BuildCraft|Energy"); + } - //TODO add Thermal expansion isLoaded check + // TODO add Thermal expansion isLoaded check } diff --git a/APIs/universalelectricity/compatibility/TileEntityUniversalConductor.java b/APIs/universalelectricity/compatibility/TileEntityUniversalConductor.java index e339e93de..59b5b7e28 100644 --- a/APIs/universalelectricity/compatibility/TileEntityUniversalConductor.java +++ b/APIs/universalelectricity/compatibility/TileEntityUniversalConductor.java @@ -6,7 +6,12 @@ import ic2.api.energy.tile.IEnergyAcceptor; import ic2.api.energy.tile.IEnergyEmitter; import ic2.api.energy.tile.IEnergySink; import ic2.api.energy.tile.IEnergyTile; + +import java.util.HashSet; +import java.util.Set; + import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; import net.minecraftforge.common.ForgeDirection; import net.minecraftforge.common.MinecraftForge; import universalelectricity.core.block.IConnector; @@ -15,6 +20,9 @@ import universalelectricity.core.vector.Vector3; import universalelectricity.core.vector.VectorHelper; import universalelectricity.prefab.tile.TileEntityConductor; import buildcraft.api.power.IPowerReceptor; +import buildcraft.api.power.PowerHandler; +import buildcraft.api.power.PowerHandler.PowerReceiver; +import buildcraft.api.power.PowerHandler.Type; /** * A universal conductor class. @@ -22,14 +30,21 @@ import buildcraft.api.power.IPowerReceptor; * Extend this class or use as a reference for your own implementation of compatible conductor * tiles. * - * TODO: Need working BuildCraft support! - * - * @author micdoodle8 + * @author Calclavia, micdoodle8 * */ -public abstract class TileEntityUniversalConductor extends TileEntityConductor implements IEnergySink +public abstract class TileEntityUniversalConductor extends TileEntityConductor implements IEnergySink, IPowerReceptor { protected boolean isAddedToEnergyNet; + public PowerHandler powerHandler; + public float buildcraftBuffer = Compatibility.BC3_RATIO * 50; + + public TileEntityUniversalConductor() + { + this.powerHandler = new PowerHandler(this, Type.PIPE); + this.powerHandler.configure(0, this.buildcraftBuffer, this.buildcraftBuffer, this.buildcraftBuffer * 2); + this.powerHandler.configurePowerPerdition(0, 0); + } @Override public TileEntity[] getAdjacentConnections() @@ -74,7 +89,10 @@ public abstract class TileEntityUniversalConductor extends TileEntityConductor i } else if (Compatibility.isBuildcraftLoaded() && tileEntity instanceof IPowerReceptor) { - this.adjacentConnections[i] = tileEntity; + if (((IPowerReceptor) tileEntity).getPowerReceiver(side.getOpposite()) != null) + { + this.adjacentConnections[i] = tileEntity; + } } } } @@ -82,11 +100,9 @@ public abstract class TileEntityUniversalConductor extends TileEntityConductor i return this.adjacentConnections; } - @Override - public boolean canUpdate() - { - return !this.isAddedToEnergyNet; - } + /* + * @Override public boolean canUpdate() { return !this.isAddedToEnergyNet; } + */ @Override public void updateEntity() @@ -167,4 +183,35 @@ public abstract class TileEntityUniversalConductor extends TileEntityConductor i { return true; } + + /** + * BuildCraft functions + */ + @Override + public PowerReceiver getPowerReceiver(ForgeDirection side) + { + return this.powerHandler.getPowerReceiver(); + } + + @Override + public void doWork(PowerHandler workProvider) + { + Set ignoreTiles = new HashSet(); + ignoreTiles.add(this); + + for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS) + { + TileEntity tile = new Vector3(this).modifyPositionFromSide(direction).getTileEntity(this.worldObj); + ignoreTiles.add(tile); + } + + ElectricityPack pack = ElectricityPack.getFromWatts(workProvider.useEnergy(0, this.getNetwork().getRequest(this).getWatts() * Compatibility.TO_BC_RATIO, true) * Compatibility.BC3_RATIO, 120); + this.getNetwork().produce(pack, ignoreTiles.toArray(new TileEntity[0])); + } + + @Override + public World getWorld() + { + return this.getWorldObj(); + } } diff --git a/APIs/universalelectricity/compatibility/TileEntityUniversalElectrical.java b/APIs/universalelectricity/compatibility/TileEntityUniversalElectrical.java new file mode 100644 index 000000000..6767b89b9 --- /dev/null +++ b/APIs/universalelectricity/compatibility/TileEntityUniversalElectrical.java @@ -0,0 +1,314 @@ +package universalelectricity.compatibility; + +import ic2.api.energy.event.EnergyTileLoadEvent; +import ic2.api.energy.event.EnergyTileUnloadEvent; +import ic2.api.energy.tile.IEnergySink; +import ic2.api.energy.tile.IEnergySource; +import ic2.api.energy.tile.IEnergyTile; +import ic2.api.item.IElectricItemManager; +import ic2.api.item.ISpecialElectricItem; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraftforge.common.ForgeDirection; +import net.minecraftforge.common.MinecraftForge; +import thermalexpansion.api.item.IChargeableItem; +import universalelectricity.core.electricity.ElectricityPack; +import universalelectricity.core.item.IItemElectric; +import universalelectricity.core.vector.Vector3; +import universalelectricity.prefab.tile.TileEntityElectrical; +import buildcraft.api.power.IPowerReceptor; +import buildcraft.api.power.PowerHandler; +import buildcraft.api.power.PowerHandler.PowerReceiver; +import buildcraft.api.power.PowerHandler.Type; + +/** + * A universal electricity tile used for tiles that consume or produce electricity. + * + * Extend this class or use as a reference for your own implementation of compatible electrical + * tiles. + * + * @author micdoodle8, Calclavia + * + */ +public abstract class TileEntityUniversalElectrical extends TileEntityElectrical implements IEnergySink, IEnergySource, IPowerReceptor +{ + protected boolean isAddedToEnergyNet; + public PowerHandler bcPowerHandler; + public Type bcBlockType = Type.MACHINE; + public float maxInputEnergy = 100; + + /** + * Recharges electric item. + */ + @Override + public void recharge(ItemStack itemStack) + { + if (itemStack != null) + { + if (itemStack.getItem() instanceof IItemElectric) + { + super.recharge(itemStack); + } + else if (itemStack.getItem() instanceof ISpecialElectricItem) + { + ISpecialElectricItem electricItem = (ISpecialElectricItem) itemStack.getItem(); + IElectricItemManager manager = electricItem.getManager(itemStack); + float energy = Math.max(this.getProvide(ForgeDirection.UNKNOWN) * Compatibility.IC2_RATIO, 0); + energy = manager.charge(itemStack, (int) (energy * Compatibility.TO_IC2_RATIO), 0, false, false) * Compatibility.IC2_RATIO; + this.provideElectricity(energy, true); + } + else if (itemStack.getItem() instanceof IChargeableItem) + { + float accepted = ((IChargeableItem) itemStack.getItem()).receiveEnergy(itemStack, this.getProvide(ForgeDirection.UNKNOWN) * Compatibility.BC3_RATIO, true); + this.provideElectricity(accepted, true); + } + } + } + + /** + * Discharges electric item. + */ + @Override + public void discharge(ItemStack itemStack) + { + if (itemStack != null) + { + if (itemStack.getItem() instanceof IItemElectric) + { + super.discharge(itemStack); + } + else if (itemStack.getItem() instanceof ISpecialElectricItem) + { + ISpecialElectricItem electricItem = (ISpecialElectricItem) itemStack.getItem(); + + if (electricItem.canProvideEnergy(itemStack)) + { + IElectricItemManager manager = electricItem.getManager(itemStack); + float energy = Math.max(this.getRequest(ForgeDirection.UNKNOWN) * Compatibility.IC2_RATIO, 0); + energy = manager.discharge(itemStack, (int) (energy * Compatibility.TO_IC2_RATIO), 0, false, false); + this.receiveElectricity(energy, true); + } + } + else if (itemStack.getItem() instanceof IChargeableItem) + { + float given = ((IChargeableItem) itemStack.getItem()).transferEnergy(itemStack, this.getRequest(ForgeDirection.UNKNOWN) * Compatibility.BC3_RATIO, true); + this.receiveElectricity(given, true); + } + } + } + + @Override + public void initiate() + { + super.initiate(); + this.initBuildCraft(); + } + + @Override + public void updateEntity() + { + super.updateEntity(); + + // Register to the IC2 Network + if (!this.worldObj.isRemote) + { + if (!this.isAddedToEnergyNet) + { + this.initIC(); + } + + if (this.bcPowerHandler == null) + { + this.initBuildCraft(); + } + + if (Compatibility.isBuildcraftLoaded()) + { + if (this.bcPowerHandler.getEnergyStored() > 0) + { + /** + * Cheat BuildCraft powerHandler and always empty energy inside of it. + */ + this.receiveElectricity(this.bcPowerHandler.getEnergyStored() * Compatibility.BC3_RATIO, true); + this.bcPowerHandler.setEnergy(0); + } + } + } + } + + @Override + public void produce() + { + if (!this.worldObj.isRemote) + { + for (ForgeDirection outputDirection : this.getOutputDirections()) + { + if (outputDirection != ForgeDirection.UNKNOWN) + { + if (!this.produceUE(outputDirection)) + { + this.produceBuildCraft(outputDirection); + } + + } + } + } + } + + public boolean produceBuildCraft(ForgeDirection outputDirection) + { + if (!this.worldObj.isRemote && outputDirection != null && outputDirection != ForgeDirection.UNKNOWN) + { + float provide = this.getProvide(outputDirection); + + if (this.getEnergyStored() >= provide && provide > 0) + { + if (Compatibility.isBuildcraftLoaded()) + { + TileEntity tileEntity = new Vector3(this).modifyPositionFromSide(outputDirection).getTileEntity(this.worldObj); + + if (tileEntity instanceof IPowerReceptor) + { + PowerReceiver receiver = ((IPowerReceptor) tileEntity).getPowerReceiver(outputDirection.getOpposite()); + + if (receiver != null) + { + float bc3Provide = provide * Compatibility.TO_BC_RATIO; + float energyUsed = Math.min(receiver.receiveEnergy(this.bcBlockType, bc3Provide, outputDirection.getOpposite()), bc3Provide); + this.provideElectricity((bc3Provide - (energyUsed * Compatibility.TO_BC_RATIO)), true); + } + + return true; + } + } + } + } + + return false; + } + + /** + * IC2 Methods + */ + @Override + public boolean acceptsEnergyFrom(TileEntity emitter, ForgeDirection direction) + { + return this.getInputDirections().contains(direction); + } + + @Override + public double getOfferedEnergy() + { + return this.getProvide(ForgeDirection.UNKNOWN) * Compatibility.TO_IC2_RATIO; + } + + @Override + public void drawEnergy(double amount) + { + this.provideElectricity((float) amount * Compatibility.IC2_RATIO, true); + } + + @Override + public void invalidate() + { + this.unloadTileIC2(); + super.invalidate(); + } + + @Override + public void onChunkUnload() + { + this.unloadTileIC2(); + super.onChunkUnload(); + } + + protected void initIC() + { + if (Compatibility.isIndustrialCraft2Loaded()) + { + MinecraftForge.EVENT_BUS.post(new EnergyTileLoadEvent(this)); + } + + this.isAddedToEnergyNet = true; + } + + private void unloadTileIC2() + { + if (this.isAddedToEnergyNet && this.worldObj != null) + { + if (Compatibility.isIndustrialCraft2Loaded()) + { + MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this)); + } + + this.isAddedToEnergyNet = false; + } + } + + @Override + public double demandedEnergyUnits() + { + return Math.ceil(this.getRequest(ForgeDirection.UNKNOWN) * Compatibility.TO_IC2_RATIO); + } + + @Override + public double injectEnergyUnits(ForgeDirection direction, double amount) + { + if (this.getInputDirections().contains(direction)) + { + float convertedEnergy = (float) (amount * Compatibility.IC2_RATIO); + ElectricityPack toSend = ElectricityPack.getFromWatts(convertedEnergy, this.getVoltage()); + float receive = this.receiveElectricity(direction, toSend, true); + + // Return the difference, since injectEnergy returns left over energy, and + // receiveElectricity returns energy used. + return Math.round(amount - (receive * Compatibility.TO_IC2_RATIO)); + } + + return amount; + } + + @Override + public boolean emitsEnergyTo(TileEntity receiver, ForgeDirection direction) + { + return receiver instanceof IEnergyTile && this.getOutputDirections().contains(direction); + } + + @Override + public int getMaxSafeInput() + { + return Integer.MAX_VALUE; + } + + /** + * BuildCraft power support + */ + public void initBuildCraft() + { + if (this.bcPowerHandler == null) + { + this.bcPowerHandler = new PowerHandler(this, this.bcBlockType); + } + this.bcPowerHandler.configure(0, this.maxInputEnergy, 0, (int) Math.ceil(this.getMaxEnergyStored() * Compatibility.BC3_RATIO)); + } + + @Override + public PowerReceiver getPowerReceiver(ForgeDirection side) + { + this.initBuildCraft(); + return this.bcPowerHandler.getPowerReceiver(); + } + + @Override + public void doWork(PowerHandler workProvider) + { + + } + + @Override + public World getWorld() + { + return this.getWorldObj(); + } +} diff --git a/APIs/universalelectricity/compatibility/UniversalNetwork.java b/APIs/universalelectricity/compatibility/UniversalNetwork.java index 1ce9ae757..a1442c043 100644 --- a/APIs/universalelectricity/compatibility/UniversalNetwork.java +++ b/APIs/universalelectricity/compatibility/UniversalNetwork.java @@ -26,6 +26,8 @@ import universalelectricity.core.path.PathfinderChecker; import universalelectricity.core.vector.Vector3; import universalelectricity.core.vector.VectorHelper; import buildcraft.api.power.IPowerReceptor; +import buildcraft.api.power.PowerHandler.PowerReceiver; +import buildcraft.api.power.PowerHandler.Type; import cpw.mods.fml.common.FMLLog; /** @@ -103,6 +105,26 @@ public class UniversalNetwork extends ElectricityNetwork } } } + else if (Compatibility.isBuildcraftLoaded() && tileEntity instanceof IPowerReceptor) + { + IPowerReceptor electricalTile = (IPowerReceptor) tileEntity; + + for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS) + { + TileEntity conductor = VectorHelper.getConnectorFromSide(tileEntity.worldObj, new Vector3(tileEntity), direction); + PowerReceiver receiver = electricalTile.getPowerReceiver(direction); + + if (this.getConductors().contains(conductor)) + { + float energyToSend = totalUsableEnergy * ((receiver.powerRequest() * Compatibility.TO_BC_RATIO) / totalEnergyRequest); + + if (energyToSend > 0) + { + remainingUsableEnergy -= receiver.receiveEnergy(Type.PIPE, energyToSend * Compatibility.TO_BC_RATIO, direction); + } + } + } + } } } else @@ -167,12 +189,15 @@ public class UniversalNetwork extends ElectricityNetwork { for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS) { - ElectricityPack pack = ElectricityPack.getFromWatts(((IPowerReceptor) tileEntity).getPowerReceiver(direction).powerRequest() * Compatibility.BC3_RATIO, 120); - - if (pack.getWatts() > 0) + if (((IPowerReceptor) tileEntity).getPowerReceiver(direction) != null) { - requests.add(pack); - break; + ElectricityPack pack = ElectricityPack.getFromWatts(((IPowerReceptor) tileEntity).getPowerReceiver(direction).powerRequest() * Compatibility.BC3_RATIO, 120); + + if (pack.getWatts() > 0) + { + requests.add(pack); + break; + } } } diff --git a/APIs/universalelectricity/core/UniversalElectricity.java b/APIs/universalelectricity/core/UniversalElectricity.java index 520f40f7b..a2016d707 100644 --- a/APIs/universalelectricity/core/UniversalElectricity.java +++ b/APIs/universalelectricity/core/UniversalElectricity.java @@ -10,9 +10,9 @@ import cpw.mods.fml.common.Loader; /** * General Universal Electricity class. - * + * * @author Calclavia - * + * */ public class UniversalElectricity { @@ -60,7 +60,6 @@ public class UniversalElectricity { if (!INIT) { - System.out.println("[UniversalElectricity] Loading core API version " + UniversalElectricity.VERSION); /** * Loads the configuration and sets all the values. */ @@ -79,6 +78,6 @@ public class UniversalElectricity } } - INIT = true; - } + INIT = true; + } } diff --git a/APIs/universalelectricity/core/electricity/ElectricityDisplay.java b/APIs/universalelectricity/core/electricity/ElectricityDisplay.java index 136fa1249..f3e5221d5 100644 --- a/APIs/universalelectricity/core/electricity/ElectricityDisplay.java +++ b/APIs/universalelectricity/core/electricity/ElectricityDisplay.java @@ -1,201 +1,199 @@ package universalelectricity.core.electricity; -/** An easy way to display information on electricity for the client. - * - * @author Calclavia */ +/** + * An easy way to display information on electricity for the client. + * + * @author Calclavia + */ public class ElectricityDisplay { - /** Universal Electricity's units are in KILOJOULES, KILOWATTS and KILOVOLTS. Try to make your - * energy ratio as close to real life as possible. */ - public static enum ElectricUnit - { - AMPERE("Amp", "I"), - AMP_HOUR("Amp Hour", "Ah"), - VOLTAGE("Volt", "V"), - WATT("Watt", "W"), - WATT_HOUR("Watt Hour", "Wh"), - RESISTANCE("Ohm", "R"), - CONDUCTANCE("Siemen", "S"), - JOULES("Joule", "J"); + /** + * Universal Electricity's units are in KILOJOULES, KILOWATTS and KILOVOLTS. Try to make your + * energy ratio as close to real life as possible. + */ + public static enum ElectricUnit + { + AMPERE("Amp", "I"), AMP_HOUR("Amp Hour", "Ah"), VOLTAGE("Volt", "V"), WATT("Watt", "W"), + WATT_HOUR("Watt Hour", "Wh"), RESISTANCE("Ohm", "R"), CONDUCTANCE("Siemen", "S"), + JOULES("Joule", "J"); - public String name; - public String symbol; + public String name; + public String symbol; - private ElectricUnit(String name, String symbol) - { - this.name = name; - this.symbol = symbol; - } + private ElectricUnit(String name, String symbol) + { + this.name = name; + this.symbol = symbol; + } - public String getPlural() - { - return this.name + "s"; - } - } + public String getPlural() + { + return this.name + "s"; + } + } - /** Metric system of measurement. */ - public static enum MeasurementUnit - { - MICRO("Micro", "u", 0.000001f), - MILLI("Milli", "m", 0.001f), - BASE("", "", 1), - KILO("Kilo", "k", 1000f), - MEGA("Mega", "M", 1000000f), - GIGA("Giga", "G", 1000000000f), - TERA("Tera", "T", 1000000000000f), - PETA("Peta", "P", 1000000000000000f), - EXA("Exa", "E", 1000000000000000000f), - ZETTA("Zetta", "Z", 1000000000000000000000f), - YOTTA("Yotta", "Y", 1000000000000000000000000f); + /** Metric system of measurement. */ + public static enum MeasurementUnit + { + MICRO("Micro", "u", 0.000001f), MILLI("Milli", "m", 0.001f), BASE("", "", 1), + KILO("Kilo", "k", 1000f), MEGA("Mega", "M", 1000000f), GIGA("Giga", "G", 1000000000f), + TERA("Tera", "T", 1000000000000f), PETA("Peta", "P", 1000000000000000f), + EXA("Exa", "E", 1000000000000000000f), ZETTA("Zetta", "Z", 1000000000000000000000f), + YOTTA("Yotta", "Y", 1000000000000000000000000f); - /** long name for the unit */ - public String name; - /** short unit version of the unit */ - public String symbol; - /** Point by which a number is consider to be of this unit */ - public float value; + /** long name for the unit */ + public String name; + /** short unit version of the unit */ + public String symbol; + /** Point by which a number is consider to be of this unit */ + public float value; - private MeasurementUnit(String name, String symbol, float value) - { - this.name = name; - this.symbol = symbol; - this.value = value; - } + private MeasurementUnit(String name, String symbol, float value) + { + this.name = name; + this.symbol = symbol; + this.value = value; + } - public String getName(boolean getShort) - { - if (getShort) - { - return symbol; - } - else - { - return name; - } - } + public String getName(boolean getShort) + { + if (getShort) + { + return symbol; + } + else + { + return name; + } + } - /** Divides the value by the unit value start */ - public double process(double value) - { - return value / this.value; - } + /** Divides the value by the unit value start */ + public double process(double value) + { + return value / this.value; + } - /** Checks if a value is above the unit value start */ - public boolean isAbove(float value) - { - return value > this.value; - } + /** Checks if a value is above the unit value start */ + public boolean isAbove(float value) + { + return value > this.value; + } - /** Checks if a value is lower than the unit value start */ - public boolean isBellow(float value) - { - return value < this.value; - } - } + /** Checks if a value is lower than the unit value start */ + public boolean isBellow(float value) + { + return value < this.value; + } + } - /** By default, mods should store energy in Kilo-Joules, hence a multiplier of 1/1000. */ - public static String getDisplay(float value, ElectricUnit unit, int decimalPlaces, boolean isShort) - { - return getDisplay(value, unit, decimalPlaces, isShort, 1000); - } + /** By default, mods should store energy in Kilo-Joules, hence a multiplier of 1/1000. */ + public static String getDisplay(float value, ElectricUnit unit, int decimalPlaces, boolean isShort) + { + return getDisplay(value, unit, decimalPlaces, isShort, 1000); + } - /** Displays the unit as text. Does handle negative numbers, and will place a negative sign in - * front of the output string showing this. Use string.replace to remove the negative sign if unwanted */ - public static String getDisplay(float value, ElectricUnit unit, int decimalPlaces, boolean isShort, float multiplier) - { - String unitName = unit.name; - String prefix = ""; - if (value < 0) - { - value = Math.abs(value); - prefix = "-"; - } - value *= multiplier; + /** + * Displays the unit as text. Does handle negative numbers, and will place a negative sign in + * front of the output string showing this. Use string.replace to remove the negative sign if + * unwanted + */ + public static String getDisplay(float value, ElectricUnit unit, int decimalPlaces, boolean isShort, float multiplier) + { + String unitName = unit.name; + String prefix = ""; + if (value < 0) + { + value = Math.abs(value); + prefix = "-"; + } + value *= multiplier; - if (isShort) - { - unitName = unit.symbol; - } - else if (value > 1) - { - unitName = unit.getPlural(); - } + if (isShort) + { + unitName = unit.symbol; + } + else if (value > 1) + { + unitName = unit.getPlural(); + } - if (value == 0) - { - return value + " " + unitName; - } - else - { - for (int i = 0; i < MeasurementUnit.values().length; i++) - { - MeasurementUnit lowerMeasure = MeasurementUnit.values()[i]; - if (lowerMeasure.isBellow(value) && lowerMeasure.ordinal() == 0) - { - return prefix + roundDecimals(lowerMeasure.process(value), decimalPlaces) + " " + lowerMeasure.getName(isShort) + unitName; - } - if (lowerMeasure.ordinal() + 1 >= MeasurementUnit.values().length) - { - return prefix + roundDecimals(lowerMeasure.process(value), decimalPlaces) + " " + lowerMeasure.getName(isShort) + unitName; - } - MeasurementUnit upperMeasure = MeasurementUnit.values()[i + 1]; - if ((lowerMeasure.isAbove(value) && upperMeasure.isBellow(value)) || lowerMeasure.value == value) - { - return prefix + roundDecimals(lowerMeasure.process(value), decimalPlaces) + " " + lowerMeasure.getName(isShort) + unitName; - } - } - } + if (value == 0) + { + return value + " " + unitName; + } + else + { + for (int i = 0; i < MeasurementUnit.values().length; i++) + { + MeasurementUnit lowerMeasure = MeasurementUnit.values()[i]; + if (lowerMeasure.isBellow(value) && lowerMeasure.ordinal() == 0) + { + return prefix + roundDecimals(lowerMeasure.process(value), decimalPlaces) + " " + lowerMeasure.getName(isShort) + unitName; + } + if (lowerMeasure.ordinal() + 1 >= MeasurementUnit.values().length) + { + return prefix + roundDecimals(lowerMeasure.process(value), decimalPlaces) + " " + lowerMeasure.getName(isShort) + unitName; + } + MeasurementUnit upperMeasure = MeasurementUnit.values()[i + 1]; + if ((lowerMeasure.isAbove(value) && upperMeasure.isBellow(value)) || lowerMeasure.value == value) + { + return prefix + roundDecimals(lowerMeasure.process(value), decimalPlaces) + " " + lowerMeasure.getName(isShort) + unitName; + } + } + } - return prefix + roundDecimals(value, decimalPlaces) + " " + unitName; - } + return prefix + roundDecimals(value, decimalPlaces) + " " + unitName; + } - public static String getDisplay(float value, ElectricUnit unit) - { - return getDisplay(value, unit, 2, false); - } + public static String getDisplay(float value, ElectricUnit unit) + { + return getDisplay(value, unit, 2, false); + } - public static String getDisplayShort(float value, ElectricUnit unit) - { - return getDisplay(value, unit, 2, true); - } + public static String getDisplayShort(float value, ElectricUnit unit) + { + return getDisplay(value, unit, 2, true); + } - public static String getDisplayShort(float value, ElectricUnit unit, int decimalPlaces) - { - return getDisplay(value, unit, decimalPlaces, true); - } + public static String getDisplayShort(float value, ElectricUnit unit, int decimalPlaces) + { + return getDisplay(value, unit, decimalPlaces, true); + } - public static String getDisplaySimple(float value, ElectricUnit unit, int decimalPlaces) - { - if (value > 1) - { - if (decimalPlaces < 1) - { - return (int) value + " " + unit.getPlural(); - } + public static String getDisplaySimple(float value, ElectricUnit unit, int decimalPlaces) + { + if (value > 1) + { + if (decimalPlaces < 1) + { + return (int) value + " " + unit.getPlural(); + } - return roundDecimals(value, decimalPlaces) + " " + unit.getPlural(); - } + return roundDecimals(value, decimalPlaces) + " " + unit.getPlural(); + } - if (decimalPlaces < 1) - { - return (int) value + " " + unit.name; - } + if (decimalPlaces < 1) + { + return (int) value + " " + unit.name; + } - return roundDecimals(value, decimalPlaces) + " " + unit.name; - } + return roundDecimals(value, decimalPlaces) + " " + unit.name; + } - /** Rounds a number to a specific number place places - * - * @param The number - * @return The rounded number */ - public static double roundDecimals(double d, int decimalPlaces) - { - int j = (int) (d * Math.pow(10, decimalPlaces)); - return j / Math.pow(10, decimalPlaces); - } + /** + * Rounds a number to a specific number place places + * + * @param The number + * @return The rounded number + */ + public static double roundDecimals(double d, int decimalPlaces) + { + int j = (int) (d * Math.pow(10, decimalPlaces)); + return j / Math.pow(10, decimalPlaces); + } - public static double roundDecimals(double d) - { - return roundDecimals(d, 2); - } + public static double roundDecimals(double d) + { + return roundDecimals(d, 2); + } } diff --git a/APIs/universalelectricity/core/item/ItemElectric.java b/APIs/universalelectricity/core/item/ItemElectric.java index a281c465d..2d4d2b1ab 100644 --- a/APIs/universalelectricity/core/item/ItemElectric.java +++ b/APIs/universalelectricity/core/item/ItemElectric.java @@ -6,144 +6,146 @@ import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagDouble; -import net.minecraft.nbt.NBTTagFloat; import net.minecraft.world.World; import universalelectricity.core.electricity.ElectricityDisplay; import universalelectricity.core.electricity.ElectricityDisplay.ElectricUnit; -/** Extend from this class if your item requires electricity or to be charged. Optionally, you can +/** + * Extend from this class if your item requires electricity or to be charged. Optionally, you can * implement IItemElectric instead. - * - * @author Calclavia */ + * + * @author Calclavia + * + */ public abstract class ItemElectric extends Item implements IItemElectric { - public ItemElectric(int id) - { - super(id); - this.setMaxStackSize(1); - this.setMaxDamage(100); - this.setNoRepair(); - } + public ItemElectric(int id) + { + super(id); + this.setMaxStackSize(1); + this.setMaxDamage(100); + this.setNoRepair(); + } - @Override - public void addInformation(ItemStack itemStack, EntityPlayer entityPlayer, List list, boolean par4) - { - String color = ""; - float joules = this.getElectricityStored(itemStack); + @Override + public void addInformation(ItemStack itemStack, EntityPlayer entityPlayer, List list, boolean par4) + { + String color = ""; + float joules = this.getElectricityStored(itemStack); - if (joules <= this.getMaxElectricityStored(itemStack) / 3) - { - color = "\u00a74"; - } - else if (joules > this.getMaxElectricityStored(itemStack) * 2 / 3) - { - color = "\u00a72"; - } - else - { - color = "\u00a76"; - } + if (joules <= this.getMaxElectricityStored(itemStack) / 3) + { + color = "\u00a74"; + } + else if (joules > this.getMaxElectricityStored(itemStack) * 2 / 3) + { + color = "\u00a72"; + } + else + { + color = "\u00a76"; + } - list.add(color + ElectricityDisplay.getDisplayShort(joules, ElectricUnit.JOULES) + "/" + ElectricityDisplay.getDisplayShort(this.getMaxElectricityStored(itemStack), ElectricUnit.JOULES)); - } + list.add(color + ElectricityDisplay.getDisplayShort(joules, ElectricUnit.JOULES) + "/" + ElectricityDisplay.getDisplayShort(this.getMaxElectricityStored(itemStack), ElectricUnit.JOULES)); + } - /** Makes sure the item is uncharged when it is crafted and not charged. Change this if you do - * not want this to happen! */ - @Override - public void onCreated(ItemStack itemStack, World par2World, EntityPlayer par3EntityPlayer) - { - this.setElectricity(itemStack, 0); - } + /** + * Makes sure the item is uncharged when it is crafted and not charged. Change this if you do + * not want this to happen! + */ + @Override + public void onCreated(ItemStack itemStack, World par2World, EntityPlayer par3EntityPlayer) + { + this.setElectricity(itemStack, 0); + } - @Override - public float recharge(ItemStack itemStack, float energy, boolean doReceive) - { - float rejectedElectricity = Math.max((this.getElectricityStored(itemStack) + energy) - this.getMaxElectricityStored(itemStack), 0); - float energyToReceive = energy - rejectedElectricity; + @Override + public float recharge(ItemStack itemStack, float energy, boolean doReceive) + { + float rejectedElectricity = Math.max((this.getElectricityStored(itemStack) + energy) - this.getMaxElectricityStored(itemStack), 0); + float energyToReceive = energy - rejectedElectricity; - if (doReceive) - { - this.setElectricity(itemStack, this.getElectricityStored(itemStack) + energyToReceive); - } + if (doReceive) + { + this.setElectricity(itemStack, this.getElectricityStored(itemStack) + energyToReceive); + } - return energyToReceive; - } + return energyToReceive; + } - @Override - public float discharge(ItemStack itemStack, float energy, boolean doTransfer) - { - float energyToTransfer = Math.min(this.getElectricityStored(itemStack), energy); + @Override + public float discharge(ItemStack itemStack, float energy, boolean doTransfer) + { + float energyToTransfer = Math.min(this.getElectricityStored(itemStack), energy); - if (doTransfer) - { - this.setElectricity(itemStack, this.getElectricityStored(itemStack) - energyToTransfer); - } + if (doTransfer) + { + this.setElectricity(itemStack, this.getElectricityStored(itemStack) - energyToTransfer); + } - return energyToTransfer; - } + return energyToTransfer; + } - @Override - public float getVoltage(ItemStack itemStack) - { - return 0.120f; - } + @Override + public float getVoltage(ItemStack itemStack) + { + return 120; + } - @Override - public void setElectricity(ItemStack itemStack, float joules) - { - // Saves the frequency in the ItemStack - if (itemStack.getTagCompound() == null) - { - itemStack.setTagCompound(new NBTTagCompound()); - } + @Override + public void setElectricity(ItemStack itemStack, float joules) + { + // Saves the frequency in the ItemStack + if (itemStack.getTagCompound() == null) + { + itemStack.setTagCompound(new NBTTagCompound()); + } - float electricityStored = Math.max(Math.min(joules, this.getMaxElectricityStored(itemStack)), 0); - itemStack.getTagCompound().setFloat("electricity", electricityStored); + float electricityStored = Math.max(Math.min(joules, this.getMaxElectricityStored(itemStack)), 0); + itemStack.getTagCompound().setFloat("electricity", electricityStored); - /** Sets the damage as a percentage to render the bar properly. */ - itemStack.setItemDamage((int) (100 - (electricityStored / getMaxElectricityStored(itemStack)) * 100)); - } + /** + * Sets the damage as a percentage to render the bar properly. + */ + itemStack.setItemDamage((int) (100 - (electricityStored / getMaxElectricityStored(itemStack)) * 100)); + } - @Override - public float getTransfer(ItemStack itemStack) - { - return this.getMaxElectricityStored(itemStack) - this.getElectricityStored(itemStack); - } + @Override + public float getTransfer(ItemStack itemStack) + { + return this.getMaxElectricityStored(itemStack) - this.getElectricityStored(itemStack); + } - /** Gets the energy stored in the item. Energy is stored using item NBT */ - @Override - public float getElectricityStored(ItemStack itemStack) - { - if (itemStack.getTagCompound() == null) - { - itemStack.setTagCompound(new NBTTagCompound()); - } - float energyStored = 0f; - if (itemStack.getTagCompound().hasKey("electricity")) - { - NBTBase obj = itemStack.getTagCompound().getTag("electricity"); - if (obj instanceof NBTTagDouble) - { - energyStored = (float) ((NBTTagDouble) obj).data; - } - else if (obj instanceof NBTTagFloat) - { - energyStored = ((NBTTagFloat) obj).data; - } - } + /** + * This function is called to get the electricity stored in this item + * + * @return - The amount of electricity stored in watts + */ + @Override + public float getElectricityStored(ItemStack itemStack) + { + if (itemStack.getTagCompound() == null) + { + itemStack.setTagCompound(new NBTTagCompound()); + } - /** Sets the damage as a percentage to render the bar properly. */ - itemStack.setItemDamage((int) (100 - (energyStored / getMaxElectricityStored(itemStack)) * 100)); - return energyStored; - } + float electricityStored = itemStack.getTagCompound().getFloat("electricity"); - @Override - public void getSubItems(int par1, CreativeTabs par2CreativeTabs, List par3List) - { - par3List.add(ElectricItemHelper.getUncharged(new ItemStack(this))); - par3List.add(ElectricItemHelper.getWithCharge(new ItemStack(this), this.getMaxElectricityStored(new ItemStack(this)))); - } + /** + * Sets the damage as a percentage to render the bar properly. + */ + itemStack.setItemDamage((int) (100 - (electricityStored / getMaxElectricityStored(itemStack)) * 100)); + return electricityStored; + } + + @Override + public void getSubItems(int par1, CreativeTabs par2CreativeTabs, List par3List) + { + // Add an uncharged version of the electric item + par3List.add(ElectricItemHelper.getUncharged(new ItemStack(this))); + // Add an electric item to the creative list that is fully charged + ItemStack chargedItem = new ItemStack(this); + par3List.add(ElectricItemHelper.getWithCharge(chargedItem, this.getMaxElectricityStored(chargedItem))); + } } diff --git a/APIs/universalelectricity/prefab/RecipeHelper.java b/APIs/universalelectricity/prefab/RecipeHelper.java new file mode 100644 index 000000000..514c0db45 --- /dev/null +++ b/APIs/universalelectricity/prefab/RecipeHelper.java @@ -0,0 +1,192 @@ +package universalelectricity.prefab; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.CraftingManager; +import net.minecraft.item.crafting.IRecipe; +import net.minecraftforge.common.Configuration; +import cpw.mods.fml.common.registry.GameRegistry; + +/** + * This class is used to replace recipes that are already added in the existing recipe pool for + * crafting and smelting. All recipe functions take account of the Forge Ore Dictionary. It also + * includes some recipe helper functions to shorten some of your function calls. + * + * @author Calclavia + * + */ +public class RecipeHelper +{ + public static List getRecipesByOutput(ItemStack output) + { + List list = new ArrayList(); + + for (Object obj : CraftingManager.getInstance().getRecipeList()) + { + if (obj instanceof IRecipe) + { + if (((IRecipe) obj).getRecipeOutput() == output) + { + list.add((IRecipe) obj); + } + } + } + + return list; + } + + /** + * Replaces a recipe with a new IRecipe. + * + * @return True if successful + */ + public static boolean replaceRecipe(IRecipe recipe, IRecipe newRecipe) + { + for (Object obj : CraftingManager.getInstance().getRecipeList()) + { + if (obj instanceof IRecipe) + { + if (((IRecipe) obj).equals(recipe) || obj == recipe) + { + CraftingManager.getInstance().getRecipeList().remove(obj); + CraftingManager.getInstance().getRecipeList().add(newRecipe); + return true; + } + } + } + + return false; + } + + /** + * Replaces a recipe with the resulting ItemStack with a new IRecipe. + * + * @return True if successful + */ + public static boolean replaceRecipe(ItemStack recipe, IRecipe newRecipe) + { + if (removeRecipe(recipe)) + { + CraftingManager.getInstance().getRecipeList().add(newRecipe); + return true; + } + + return false; + } + + /** + * Removes a recipe by its IRecipe class. + * + * @return True if successful + */ + public static boolean removeRecipe(IRecipe recipe) + { + for (Object obj : CraftingManager.getInstance().getRecipeList()) + { + if (obj != null) + { + if (obj instanceof IRecipe) + { + if (((IRecipe) obj).equals(recipe) || obj == recipe) + { + CraftingManager.getInstance().getRecipeList().remove(obj); + return true; + } + } + } + } + + return false; + } + + /** + * Removes the first recipe found by its output. + * + * @return True if successful + */ + public static boolean removeRecipe(ItemStack stack) + { + for (Object obj : CraftingManager.getInstance().getRecipeList()) + { + if (obj != null) + { + if (obj instanceof IRecipe) + { + if (((IRecipe) obj).getRecipeOutput() != null) + { + if (((IRecipe) obj).getRecipeOutput().isItemEqual(stack)) + { + CraftingManager.getInstance().getRecipeList().remove(obj); + return true; + } + } + } + } + } + + return false; + } + + /** + * Removes all recipes found that has this output. You may use this with Forge Ore Dictionary to + * remove all recipes with the FoD ID. + * + * @return True if successful + */ + public static boolean removeRecipes(ItemStack... itemStacks) + { + boolean didRemove = false; + + for (Iterator itr = CraftingManager.getInstance().getRecipeList().iterator(); itr.hasNext();) + { + Object obj = itr.next(); + + if (obj != null) + { + if (obj instanceof IRecipe) + { + if (((IRecipe) obj).getRecipeOutput() != null) + { + for (ItemStack itemStack : itemStacks) + { + if (((IRecipe) obj).getRecipeOutput().isItemEqual(itemStack)) + { + itr.remove(); + didRemove = true; + break; + } + } + } + } + } + } + + return didRemove; + } + + /** + * Use this function if you want to check if the recipe is allowed in the configuration file. + */ + public static void addRecipe(IRecipe recipe, String name, Configuration configuration, boolean defaultBoolean) + { + if (configuration != null) + { + configuration.load(); + + if (configuration.get("Crafting", "Allow " + name + " Crafting", defaultBoolean).getBoolean(defaultBoolean)) + { + GameRegistry.addRecipe(recipe); + } + + configuration.save(); + } + } + + public static void addRecipe(IRecipe recipe, Configuration config, boolean defaultBoolean) + { + addRecipe(recipe, recipe.getRecipeOutput().getUnlocalizedName(), config, defaultBoolean); + } +} diff --git a/APIs/universalelectricity/prefab/network/PacketManager.java b/APIs/universalelectricity/prefab/network/PacketManager.java new file mode 100644 index 000000000..311f29337 --- /dev/null +++ b/APIs/universalelectricity/prefab/network/PacketManager.java @@ -0,0 +1,336 @@ +package universalelectricity.prefab.network; + +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.INetworkManager; +import net.minecraft.network.packet.Packet; +import net.minecraft.network.packet.Packet250CustomPayload; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import universalelectricity.core.vector.Vector3; + +import com.google.common.io.ByteArrayDataInput; +import com.google.common.io.ByteArrayDataOutput; +import com.google.common.io.ByteStreams; + +import cpw.mods.fml.common.network.IPacketHandler; +import cpw.mods.fml.common.network.PacketDispatcher; +import cpw.mods.fml.common.network.Player; + +/** + * This class is used for sending and receiving packets between the server and the client. You can + * directly use this by registering this packet manager with NetworkMod. Example: + * + * @NetworkMod(channels = { "BasicComponents" }, clientSideRequired = true, serverSideRequired = + * false, packetHandler = PacketManager.class) + * + * Check out {@link #BasicComponents} for better reference. + * + * @author Calclavia + */ +public class PacketManager implements IPacketHandler, IPacketReceiver +{ + public enum PacketType + { + UNSPECIFIED, TILEENTITY; + + public static PacketType get(int id) + { + if (id >= 0 && id < PacketType.values().length) + { + return PacketType.values()[id]; + } + return UNSPECIFIED; + } + } + + /** + * Writes a compressed NBTTagCompound to the OutputStream + */ + public static void writeNBTTagCompound(NBTTagCompound tag, DataOutputStream dataStream) throws IOException + { + if (tag == null) + { + dataStream.writeShort(-1); + } + else + { + byte[] var2 = CompressedStreamTools.compress(tag); + dataStream.writeShort((short) var2.length); + dataStream.write(var2); + } + } + + public static void writeNBTTagCompound(NBTTagCompound tag, ByteArrayDataOutput dataStream) throws IOException + { + if (tag == null) + { + dataStream.writeShort(-1); + } + else + { + byte[] var2 = CompressedStreamTools.compress(tag); + dataStream.writeShort((short) var2.length); + dataStream.write(var2); + } + } + + /** + * Reads a compressed NBTTagCompount in a ByteStream. + */ + public static NBTTagCompound readNBTTagCompound(DataInputStream dataStream) throws IOException + { + short var1 = dataStream.readShort(); + + if (var1 < 0) + { + return null; + } + else + { + byte[] var2 = new byte[var1]; + dataStream.readFully(var2); + return CompressedStreamTools.decompress(var2); + } + } + + public static NBTTagCompound readNBTTagCompound(ByteArrayDataInput dataStream) throws IOException + { + short var1 = dataStream.readShort(); + + if (var1 < 0) + { + return null; + } + else + { + byte[] var2 = new byte[var1]; + dataStream.readFully(var2); + return CompressedStreamTools.decompress(var2); + } + } + + @SuppressWarnings("resource") + public static Packet getPacketWithID(String channelName, int id, Object... sendData) + { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + DataOutputStream data = new DataOutputStream(bytes); + + try + { + data.writeInt(id); + data = encodeDataStream(data, sendData); + + Packet250CustomPayload packet = new Packet250CustomPayload(); + packet.channel = channelName; + packet.data = bytes.toByteArray(); + packet.length = packet.data.length; + + return packet; + } + catch (IOException e) + { + System.out.println("Failed to create packet."); + e.printStackTrace(); + } + + return null; + } + + public static Packet getPacket(String channelName, Object... sendData) + { + return getPacketWithID(channelName, PacketType.UNSPECIFIED.ordinal(), sendData); + } + + /** + * Gets a packet for the tile entity. + * + * @return + */ + @SuppressWarnings("resource") + public static Packet getPacket(String channelName, TileEntity sender, Object... sendData) + { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + DataOutputStream data = new DataOutputStream(bytes); + + try + { + data.writeInt(PacketType.TILEENTITY.ordinal()); + + data.writeInt(sender.xCoord); + data.writeInt(sender.yCoord); + data.writeInt(sender.zCoord); + data = encodeDataStream(data, sendData); + + Packet250CustomPayload packet = new Packet250CustomPayload(); + packet.channel = channelName; + packet.data = bytes.toByteArray(); + packet.length = packet.data.length; + + return packet; + } + catch (IOException e) + { + System.out.println("Failed to create packet."); + e.printStackTrace(); + } + + return null; + } + + /** + * Sends packets to clients around a specific coordinate. A wrapper using Vector3. See + * {@PacketDispatcher} for detailed information. + */ + public static void sendPacketToClients(Packet packet, World worldObj, Vector3 position, double range) + { + try + { + PacketDispatcher.sendPacketToAllAround(position.x, position.y, position.z, range, worldObj.provider.dimensionId, packet); + } + catch (Exception e) + { + System.out.println("Sending packet to client failed."); + e.printStackTrace(); + } + } + + /** + * Sends a packet to all the clients on this server. + */ + public static void sendPacketToClients(Packet packet, World worldObj) + { + try + { + PacketDispatcher.sendPacketToAllInDimension(packet, worldObj.provider.dimensionId); + } + catch (Exception e) + { + System.out.println("Sending packet to client failed."); + e.printStackTrace(); + } + } + + public static void sendPacketToClients(Packet packet) + { + try + { + PacketDispatcher.sendPacketToAllPlayers(packet); + } + catch (Exception e) + { + System.out.println("Sending packet to client failed."); + e.printStackTrace(); + } + } + + public static DataOutputStream encodeDataStream(DataOutputStream data, Object... sendData) + { + try + { + for (Object dataValue : sendData) + { + if (dataValue instanceof Integer) + { + data.writeInt((Integer) dataValue); + } + else if (dataValue instanceof Float) + { + data.writeFloat((Float) dataValue); + } + else if (dataValue instanceof Double) + { + data.writeDouble((Double) dataValue); + } + else if (dataValue instanceof Byte) + { + data.writeByte((Byte) dataValue); + } + else if (dataValue instanceof Boolean) + { + data.writeBoolean((Boolean) dataValue); + } + else if (dataValue instanceof String) + { + data.writeUTF((String) dataValue); + } + else if (dataValue instanceof Short) + { + data.writeShort((Short) dataValue); + } + else if (dataValue instanceof Long) + { + data.writeLong((Long) dataValue); + } + else if (dataValue instanceof NBTTagCompound) + { + writeNBTTagCompound((NBTTagCompound) dataValue, data); + } + } + + return data; + } + catch (IOException e) + { + System.out.println("Packet data encoding failed."); + e.printStackTrace(); + } + + return data; + } + + @Override + public void onPacketData(INetworkManager network, Packet250CustomPayload packet, Player player) + { + try + { + ByteArrayDataInput data = ByteStreams.newDataInput(packet.data); + + int packetTypeID = data.readInt(); + + PacketType packetType = PacketType.get(packetTypeID); + + if (packetType == PacketType.TILEENTITY) + { + int x = data.readInt(); + int y = data.readInt(); + int z = data.readInt(); + + World world = ((EntityPlayer) player).worldObj; + + if (world != null) + { + TileEntity tileEntity = world.getBlockTileEntity(x, y, z); + + if (tileEntity != null) + { + if (tileEntity instanceof IPacketReceiver) + { + ((IPacketReceiver) tileEntity).handlePacketData(network, packetTypeID, packet, ((EntityPlayer) player), data); + } + } + } + } + else + { + this.handlePacketData(network, packetTypeID, packet, ((EntityPlayer) player), data); + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + @Override + public void handlePacketData(INetworkManager network, int packetType, Packet250CustomPayload packet, EntityPlayer player, ByteArrayDataInput dataStream) + { + + } +} \ No newline at end of file diff --git a/APIs/universalelectricity/prefab/tile/IRotatable.java b/APIs/universalelectricity/prefab/tile/IRotatable.java index 46806e170..ec515f94c 100644 --- a/APIs/universalelectricity/prefab/tile/IRotatable.java +++ b/APIs/universalelectricity/prefab/tile/IRotatable.java @@ -2,15 +2,22 @@ package universalelectricity.prefab.tile; import net.minecraftforge.common.ForgeDirection; -/** The interface is applied to TileEntities that can rotate. - * - * @author Calclavia */ +/** + * The interface is applied to TileEntities that can rotate. + * + * @author Calclavia + * + */ public interface IRotatable { - /** @return Gets the facing direction. Always returns the front side of the block. */ - public ForgeDirection getDirection(); + /** + * @return Gets the facing direction. Always returns the front side of the block. + */ + public ForgeDirection getDirection(); - /** @param Sets the facing direction. */ - public void setDirection(ForgeDirection direction); + /** + * @param Sets the facing direction. + */ + public void setDirection(ForgeDirection direection); } diff --git a/APIs/universalelectricity/prefab/tile/TileEntityElectrical.java b/APIs/universalelectricity/prefab/tile/TileEntityElectrical.java new file mode 100644 index 000000000..84beadfec --- /dev/null +++ b/APIs/universalelectricity/prefab/tile/TileEntityElectrical.java @@ -0,0 +1,224 @@ +package universalelectricity.prefab.tile; + +import java.util.EnumSet; + +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.ForgeDirection; +import universalelectricity.core.block.IElectrical; +import universalelectricity.core.block.IElectricalStorage; +import universalelectricity.core.electricity.ElectricityHelper; +import universalelectricity.core.electricity.ElectricityPack; +import universalelectricity.core.grid.IElectricityNetwork; +import universalelectricity.core.item.ElectricItemHelper; +import universalelectricity.core.vector.Vector3; +import universalelectricity.core.vector.VectorHelper; + +public abstract class TileEntityElectrical extends TileEntityAdvanced implements IElectrical, IElectricalStorage +{ + public float energyStored = 0; + + /** + * Recharges electric item. + */ + public void recharge(ItemStack itemStack) + { + this.setEnergyStored(this.getEnergyStored() - ElectricItemHelper.chargeItem(itemStack, this.getProvide(ForgeDirection.UNKNOWN))); + } + + /** + * Discharges electric item. + */ + public void discharge(ItemStack itemStack) + { + this.setEnergyStored(this.getEnergyStored() + ElectricItemHelper.dischargeItem(itemStack, this.getRequest(ForgeDirection.UNKNOWN))); + } + + /** + * Called to produce the potential electricity inside this block. + */ + public void produce() + { + if (!this.worldObj.isRemote) + { + for (ForgeDirection outputDirection : this.getOutputDirections()) + { + this.produceUE(outputDirection); + } + } + } + + /** + * Produces UE power towards a specific direction. + * + * @param outputDirection - The output direction. + */ + public boolean produceUE(ForgeDirection outputDirection) + { + if (!this.worldObj.isRemote && outputDirection != null && outputDirection != ForgeDirection.UNKNOWN) + { + float provide = this.getProvide(outputDirection); + + if (provide > 0) + { + TileEntity outputTile = VectorHelper.getConnectorFromSide(this.worldObj, new Vector3(this), outputDirection); + IElectricityNetwork outputNetwork = ElectricityHelper.getNetworkFromTileEntity(outputTile, outputDirection); + + if (outputNetwork != null) + { + ElectricityPack powerRequest = outputNetwork.getRequest(this); + + if (powerRequest.getWatts() > 0) + { + ElectricityPack sendPack = ElectricityPack.min(ElectricityPack.getFromWatts(this.getEnergyStored(), this.getVoltage()), ElectricityPack.getFromWatts(provide, this.getVoltage())); + float rejectedPower = outputNetwork.produce(sendPack, this); + this.provideElectricity(sendPack.getWatts() - rejectedPower, true); + } + + return true; + } + } + } + + return false; + } + + /** + * The electrical input direction. + * + * @return The direction that electricity is entered into the tile. Return null for no input. By + * default you can accept power from all sides. + */ + public EnumSet getInputDirections() + { + return EnumSet.allOf(ForgeDirection.class); + } + + /** + * The electrical output direction. + * + * @return The direction that electricity is output from the tile. Return null for no output. By + * default it will return an empty EnumSet. + */ + public EnumSet getOutputDirections() + { + return EnumSet.noneOf(ForgeDirection.class); + } + + @Override + public float receiveElectricity(ForgeDirection from, ElectricityPack receive, boolean doReceive) + { + if (this.getInputDirections().contains(from)) + { + return this.receiveElectricity(receive, doReceive); + } + + return 0; + } + + @Override + public ElectricityPack provideElectricity(ForgeDirection from, ElectricityPack request, boolean doProvide) + { + if (this.getOutputDirections().contains(from)) + { + return this.provideElectricity(request, doProvide); + } + + return new ElectricityPack(); + } + + /** + * A non-side specific version of receiveElectricity for you to optionally use it internally. + */ + public float receiveElectricity(ElectricityPack receive, boolean doReceive) + { + if (receive != null) + { + float prevEnergyStored = this.getEnergyStored(); + float newStoredEnergy = Math.min(this.getEnergyStored() + receive.getWatts(), this.getMaxEnergyStored()); + + if (doReceive) + { + this.setEnergyStored(newStoredEnergy); + } + + return Math.max(newStoredEnergy - prevEnergyStored, 0); + } + + return 0; + } + + public float receiveElectricity(float energy, boolean doReceive) + { + return this.receiveElectricity(ElectricityPack.getFromWatts(energy, this.getVoltage()), doReceive); + } + + /** + * A non-side specific version of provideElectricity for you to optionally use it internally. + */ + public ElectricityPack provideElectricity(ElectricityPack request, boolean doProvide) + { + if (request != null) + { + float requestedEnergy = Math.min(request.getWatts(), this.energyStored); + + if (doProvide) + { + this.setEnergyStored(this.energyStored - requestedEnergy); + } + + return ElectricityPack.getFromWatts(requestedEnergy, this.getVoltage()); + } + + return new ElectricityPack(); + } + + public ElectricityPack provideElectricity(float energy, boolean doProvide) + { + return this.provideElectricity(ElectricityPack.getFromWatts(energy, this.getVoltage()), doProvide); + } + + @Override + public void setEnergyStored(float energy) + { + this.energyStored = Math.max(Math.min(energy, this.getMaxEnergyStored()), 0); + } + + @Override + public float getEnergyStored() + { + return this.energyStored; + } + + @Override + public boolean canConnect(ForgeDirection direction) + { + if (direction == null || direction.equals(ForgeDirection.UNKNOWN)) + { + return false; + } + + return this.getInputDirections().contains(direction) || this.getOutputDirections().contains(direction); + } + + @Override + public float getVoltage() + { + return 0.120F; + } + + @Override + public void readFromNBT(NBTTagCompound nbt) + { + super.readFromNBT(nbt); + this.energyStored = nbt.getFloat("energyStored"); + } + + @Override + public void writeToNBT(NBTTagCompound nbt) + { + super.writeToNBT(nbt); + nbt.setFloat("energyStored", this.energyStored); + } +} diff --git a/src/com/builtbroken/common/Vector.java b/src/com/builtbroken/common/Vector.java new file mode 100644 index 000000000..8dcfaf428 --- /dev/null +++ b/src/com/builtbroken/common/Vector.java @@ -0,0 +1,42 @@ +package com.builtbroken.common; + +/** Simple class uses to plot a vector on a line + * + * @author Robert seifert */ +public class Vector +{ + protected float x; + + public Vector(float x) + { + this.x = x; + } + + public int X() + { + return (int) x; + } + + public float XX() + { + return x; + } + + /** Magnitude between two points */ + public float mag(Vector vec) + { + return vec.x - x; + } + + /** Distance to another point */ + public float distance(Vector vec) + { + return Math.abs(mag(vec)); + } + + @Override + public String toString() + { + return super.toString() + "[" + x + "x]"; + } +} diff --git a/src/com/builtbroken/common/Vector2.java b/src/com/builtbroken/common/Vector2.java new file mode 100644 index 000000000..cb019ee42 --- /dev/null +++ b/src/com/builtbroken/common/Vector2.java @@ -0,0 +1,31 @@ +package com.builtbroken.common; + +/** Simple class to plot a vector on a plane + * + * @author Robert Seifert */ +public class Vector2 extends Vector +{ + protected float y; + + public Vector2(float x, float y) + { + super(x); + this.y = y; + } + + public int Y() + { + return (int) y; + } + + public float YY() + { + return y; + } + + @Override + public String toString() + { + return super.toString() +"["+y+"y]"; + } +} diff --git a/src/com/builtbroken/common/Vector3.java b/src/com/builtbroken/common/Vector3.java new file mode 100644 index 000000000..37d579221 --- /dev/null +++ b/src/com/builtbroken/common/Vector3.java @@ -0,0 +1,31 @@ +package com.builtbroken.common; + +/** Simple class to plot a vector in a 3D space + * + * @author Robert Seifert */ +public class Vector3 extends Vector2 +{ + protected float z; + + public Vector3(float x, float y, float z) + { + super(x, y); + this.z = z; + } + + public int Z() + { + return (int) z; + } + + public float ZZ() + { + return z; + } + + @Override + public String toString() + { + return super.toString() +"["+z+"z]"; + } +} diff --git a/src/com/builtbroken/common/Vector4.java b/src/com/builtbroken/common/Vector4.java new file mode 100644 index 000000000..48b387657 --- /dev/null +++ b/src/com/builtbroken/common/Vector4.java @@ -0,0 +1,26 @@ +package com.builtbroken.common; + +/** class used to plot a point in a 3D space over time. Also used for ploting a vector in a 4D space + * + * @author Robert seifert */ +public class Vector4 extends Vector3 +{ + protected float time; + + public Vector4(float x, float y, float z, float time) + { + super(x, y, z); + this.time = time; + } + + public float time() + { + return time; + } + + @Override + public String toString() + { + return super.toString() +"["+time+"t]"; + } +} diff --git a/src/com/builtbroken/common/animation/Joint.java b/src/com/builtbroken/common/animation/Joint.java new file mode 100644 index 000000000..1ab9ac864 --- /dev/null +++ b/src/com/builtbroken/common/animation/Joint.java @@ -0,0 +1,63 @@ +package com.builtbroken.common.animation; + +import java.util.HashSet; +import java.util.Set; + +import com.builtbroken.common.Vector3; + +public class Joint +{ + protected Set childJoints = new HashSet(); + protected Joint parentJoint = null; + protected Vector3 offset, boxmin, boxmax, pose; + protected String name = "joint"; + + public Joint(String name, Vector3 boxmin, Vector3 boxmax, Vector3 pose, Joint... joints) + { + this.name = name; + this.boxmin = boxmin; + this.boxmax = boxmax; + this.pose = pose; + for (Joint joint : joints) + { + joint.setParent(this); + childJoints.add(joint); + } + } + + public Joint getParent() + { + return this.parentJoint; + } + + public Vector3 getOffset() + { + return this.offset; + } + + public Vector3 getBoxmin() + { + return this.boxmin; + } + + public Vector3 getBoxmax() + { + return this.boxmax; + } + + public Vector3 getPose() + { + return this.pose; + } + + public String getString() + { + return this.name; + } + + public void setParent(Joint joint) + { + this.parentJoint = joint; + } + +} diff --git a/src/com/builtbroken/common/animation/Skeleton.java b/src/com/builtbroken/common/animation/Skeleton.java new file mode 100644 index 000000000..0635fe3a5 --- /dev/null +++ b/src/com/builtbroken/common/animation/Skeleton.java @@ -0,0 +1,14 @@ +package com.builtbroken.common.animation; + +import java.io.File; + +public class Skeleton +{ + + + + public void read(File file) + { + + } +} diff --git a/src/dark/core/common/debug/TileEntityInfSupply.java b/src/dark/core/common/debug/TileEntityInfSupply.java index f6bcff9d9..5cf5834bc 100644 --- a/src/dark/core/common/debug/TileEntityInfSupply.java +++ b/src/dark/core/common/debug/TileEntityInfSupply.java @@ -47,7 +47,7 @@ public class TileEntityInfSupply extends TileEntityEnergyMachine implements IDeb public float getProvide(ForgeDirection direction) { // TODO Auto-generated method stub - return 1000; + return 10000; } @Override