diff --git a/README.md b/README.md index 7acd4e178..0c288fd55 100755 --- a/README.md +++ b/README.md @@ -9,7 +9,9 @@ Forestry is a modification for the game Minecraft and known primarily for its fa [Wiki](http://forestry.sengir.net/) -[IRC #forestry on esper.net](http://webchat.esper.net/?nick=ForestryWiki...&channels=forestry&prompt=1) +[Latest Builds for 1.7.10](http://jenkins.ic2.player.to/job/Forestry/) + +[IRC #forestry on esper.net](http://webchat.esper.net/?nick=ForestryGithub...&channels=forestry&prompt=1) ### Building diff --git a/application.properties b/application.properties index 67cdae7af..fcd208741 100644 --- a/application.properties +++ b/application.properties @@ -1,5 +1,5 @@ mcversion=1.7.10 -forgeversion=10.13.0.1180 +forgeversion=10.13.0.1207 version_major=3 version_minor=0 version_patch=0 diff --git a/build.gradle b/build.gradle index b90a1b73e..1dea9f73e 100755 --- a/build.gradle +++ b/build.gradle @@ -73,7 +73,7 @@ configurations { dependencies { compile 'net.industrial-craft:industrialcraft-2:2.2.575-experimental:api' - buildcraft 'com.mod-buildcraft:buildcraft:6.0.17:dev' + buildcraft 'com.mod-buildcraft:buildcraft:6.0.18:dev' } processResources { diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 3c7abdf12..b76121670 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 244a668fb..678d9d8de 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Wed Mar 26 13:33:58 CDT 2014 +#Wed Jul 02 15:54:47 CDT 2014 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=http\://services.gradle.org/distributions/gradle-1.11-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-2.0-bin.zip diff --git a/src/main/java/codechicken/nei/LICENSE.txt b/src/main/java/codechicken/nei/LICENSE.txt new file mode 100644 index 000000000..186cfbbc0 --- /dev/null +++ b/src/main/java/codechicken/nei/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 ChickenBones + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/src/main/java/codechicken/nei/VisiblityData.java b/src/main/java/codechicken/nei/VisiblityData.java new file mode 100644 index 000000000..f5753aa8e --- /dev/null +++ b/src/main/java/codechicken/nei/VisiblityData.java @@ -0,0 +1,38 @@ +package codechicken.nei; + +public class VisiblityData +{ + public boolean showUtilityButtons = true; + public boolean showStateButtons = true; + /** + * Item panel and associated buttons + */ + public boolean showItemPanel = true; + /** + * Item and search section + */ + public boolean showItemSection = true; + /** + * Dropdown and Item search field + */ + public boolean showSearchSection = true; + /** + * All widgets except options button + */ + public boolean showWidgets = true; + /** + * The entire NEI interface, aka hidden + */ + public boolean showNEI = true; + public boolean enableDeleteMode = true; + + public void translateDependancies() + { + if(!showNEI) + showWidgets = false; + if(!showWidgets) + showItemSection = showUtilityButtons = showStateButtons = false; + if(!showItemSection) + showSearchSection = showItemPanel = false; + } +} diff --git a/src/main/java/codechicken/nei/api/INEIGuiHandler.java b/src/main/java/codechicken/nei/api/INEIGuiHandler.java new file mode 100644 index 000000000..9ca8fb6cb --- /dev/null +++ b/src/main/java/codechicken/nei/api/INEIGuiHandler.java @@ -0,0 +1,49 @@ +package codechicken.nei.api; + +import codechicken.nei.VisiblityData; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.item.ItemStack; + +import java.util.List; + +/** + * If this is implemented on a gui, it will be automatically registered + */ +public interface INEIGuiHandler +{ + public VisiblityData modifyVisiblity(GuiContainer gui, VisiblityData currentVisibility); + + /** + * NEI will give the specified item to the InventoryRange returned if the player's inventory is full. + * return null for no range + */ + public Iterable getItemSpawnSlots(GuiContainer gui, ItemStack item); + + /** + * @return A list of TaggedInventoryAreas that will be used with the savestates. + */ + public List getInventoryAreas(GuiContainer gui); + + /** + * Handles clicks while an itemstack has been dragged from the item panel. Use this to set configurable slots and the like. + * Changes made to the stackSize of the dragged stack will be kept + * @param gui The current gui instance + * @param mousex The x position of the mouse + * @param mousey The y position of the mouse + * @param draggedStack The stack being dragged from the item panel + * @param button The button presed + * @return True if the drag n drop was handled. False to resume processing through other routes. The held stack will be deleted if draggedStack.stackSize == 0 + */ + public boolean handleDragNDrop(GuiContainer gui, int mousex, int mousey, ItemStack draggedStack, int button); + + /** + * Used to prevent the item panel from drawing on top of other gui elements. + * This function will also be called with a 1x1 size rectangle on the mouse position for determining if the given coordinate should override item panel functions such as scrolling + * @param x The x coordinate of the rectangle bounding the slot + * @param y The y coordinate of the rectangle bounding the slot + * @param w The w coordinate of the rectangle bounding the slot + * @param h The h coordinate of the rectangle bounding the slot + * @return true if the item panel slot within the specified rectangle should not be rendered. + */ + public boolean hideItemPanelSlot(GuiContainer gui, int x, int y, int w, int h); +} diff --git a/src/main/java/codechicken/nei/api/TaggedInventoryArea.java b/src/main/java/codechicken/nei/api/TaggedInventoryArea.java new file mode 100644 index 000000000..b50d2e239 --- /dev/null +++ b/src/main/java/codechicken/nei/api/TaggedInventoryArea.java @@ -0,0 +1,48 @@ +package codechicken.nei.api; + +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; + +import java.util.HashSet; + +public class TaggedInventoryArea +{ + public HashSet slots = new HashSet(); + public String tagName; + /** + * Only for player inventories. + */ + private IInventory inventory; + /** + * Other inventories + */ + private Container container; + + public TaggedInventoryArea(InventoryPlayer invPlayer) + { + this("InventoryPlayer", 0, 39, null); + inventory = invPlayer; + } + + public TaggedInventoryArea(String name, int first, int last, Container container) + { + this.container = container; + tagName = name; + for(int i = first; i <= last; i++) + slots.add(i); + } + + public ItemStack getStackInSlot(int i) + { + if(inventory != null) + return inventory.getStackInSlot(i); + return container.getSlot(i).getStack(); + } + + public boolean isContainer() + { + return inventory == null; + } +} diff --git a/src/main/java/forestry/Forestry.java b/src/main/java/forestry/Forestry.java index 9d6f077b5..5a75c7a50 100755 --- a/src/main/java/forestry/Forestry.java +++ b/src/main/java/forestry/Forestry.java @@ -15,22 +15,31 @@ import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLInterModComms.IMCEvent; +import cpw.mods.fml.common.event.FMLMissingMappingsEvent; +import cpw.mods.fml.common.event.FMLMissingMappingsEvent.MissingMapping; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLServerStartingEvent; - +import cpw.mods.fml.common.registry.GameRegistry; +import cpw.mods.fml.common.registry.GameRegistry.Type; import forestry.api.fuels.EngineBronzeFuel; import forestry.api.fuels.EngineCopperFuel; import forestry.api.fuels.FermenterFuel; import forestry.api.fuels.FuelManager; +import forestry.api.fuels.GeneratorFuel; import forestry.api.fuels.MoistenerFuel; import forestry.api.fuels.RainSubstrate; import forestry.core.ForestryCore; import forestry.core.config.Defaults; +import forestry.core.config.ForestryItem; import forestry.core.config.Version; import forestry.core.network.PacketHandler; +import forestry.core.proxy.Proxies; import forestry.core.utils.FluidMap; import forestry.core.utils.ItemStackMap; +import forestry.core.utils.StringUtil; +import net.minecraft.block.Block; +import net.minecraft.item.Item; /** * Forestry Minecraft Mod @@ -41,11 +50,11 @@ import forestry.core.utils.ItemStackMap; modid = Defaults.MOD, name = "Forestry", version = Version.VERSION, - dependencies = "required-after:Forge@[10.13.0.1180,);" - + "after:Buildcraft|Core;" - + "after:ExtrabiomesXL;" - + "after:BiomesOPlenty;" - + "after:IC2") + dependencies = "required-after:Forge@[10.13.0.1207,);" + + "after:Buildcraft|Core;" + + "after:ExtrabiomesXL;" + + "after:BiomesOPlenty;" + + "after:IC2") //, certificateFingerprint = Version.FINGERPRINT) public class Forestry { @@ -58,6 +67,7 @@ public class Forestry { FuelManager.rainSubstrate = new ItemStackMap(); FuelManager.bronzeEngineFuel = new FluidMap(); FuelManager.copperEngineFuel = new ItemStackMap(); + FuelManager.generatorFuel = new FluidMap(); } @SidedProxy(clientSide = "forestry.core.ForestryClient", serverSide = "forestry.core.ForestryCore") public static ForestryCore core = new ForestryCore(); @@ -96,4 +106,37 @@ public class Forestry { public void processIMCMessages(IMCEvent event) { core.processIMCMessages(event.getMessages()); } + + @EventHandler + public void missingMapping(FMLMissingMappingsEvent event) { + for (MissingMapping mapping : event.get()) + if (mapping.type == Type.BLOCK) { + Block block = GameRegistry.findBlock(Defaults.MOD, StringUtil.cleanTags(mapping.name)); + if (block != null) { + mapping.remap(block); + Proxies.log.warning("Remapping block " + mapping.name + " to " + StringUtil.cleanBlockName(block)); + } + } else { + Block block = GameRegistry.findBlock(Defaults.MOD, StringUtil.cleanTags(mapping.name)); + if (block != null) { + mapping.remap(Item.getItemFromBlock(block)); + Proxies.log.warning("Remapping item " + mapping.name + " to " + StringUtil.cleanBlockName(block)); + } else if (mapping.name.equals("Forestry:builderBackpack")) { + mapping.remap(ForestryItem.builderBackpack.item()); + Proxies.log.warning("Remapping item " + mapping.name + " to " + ForestryItem.builderBackpack.name()); + } else if (mapping.name.equals("Forestry:builderBackpackT2")) { + mapping.remap(ForestryItem.builderBackpackT2.item()); + Proxies.log.warning("Remapping item " + mapping.name + " to " + ForestryItem.builderBackpackT2.name()); + } else if (mapping.name.equals("Forestry:adventurerBackpack")) { + mapping.remap(ForestryItem.adventurerBackpack.item()); + Proxies.log.warning("Remapping item " + mapping.name + " to " + ForestryItem.adventurerBackpack.name()); + } else if (mapping.name.equals("Forestry:adventurerBackpackT2")) { + mapping.remap(ForestryItem.adventurerBackpackT2.item()); + Proxies.log.warning("Remapping item " + mapping.name + " to " + ForestryItem.adventurerBackpackT2.name()); + } else if (mapping.name.equals("Forestry:shortMead")) { + mapping.remap(ForestryItem.beverage.item()); + Proxies.log.warning("Remapping item " + mapping.name + " to " + ForestryItem.beverage.name()); + } + } + } } diff --git a/src/main/java/forestry/apiculture/CommandBeekeepingMode.java b/src/main/java/forestry/apiculture/CommandBeekeepingMode.java index b55eebc72..2125b5756 100755 --- a/src/main/java/forestry/apiculture/CommandBeekeepingMode.java +++ b/src/main/java/forestry/apiculture/CommandBeekeepingMode.java @@ -204,7 +204,10 @@ public class CommandBeekeepingMode extends CommandMC { private void listModes(ICommandSender sender, String[] arguments) { World world = getWorld(sender, arguments); - sendChatMessage(sender, StringUtil.localize("chat.bees.command.mode.current").replaceAll("%MODE", PluginApiculture.beeInterface.getBeekeepingMode(world).getName()).replaceAll("%WORLD", String.valueOf(world.getWorldInfo().getSaveVersion()))); + String message = StringUtil.localize("chat.bees.command.mode.current"); + message = message.replaceAll("%MODE", PluginApiculture.beeInterface.getBeekeepingMode(world).getName()); + message = message.replaceAll("%WORLD", String.valueOf(world.getWorldInfo().getSaveVersion())); + sendChatMessage(sender, message); String help = ""; for (IBeekeepingMode mode : PluginApiculture.beeInterface.getBeekeepingModes()) { diff --git a/src/main/java/forestry/apiculture/gadgets/BlockAlveary.java b/src/main/java/forestry/apiculture/gadgets/BlockAlveary.java index f0ad0afec..9b3013afb 100755 --- a/src/main/java/forestry/apiculture/gadgets/BlockAlveary.java +++ b/src/main/java/forestry/apiculture/gadgets/BlockAlveary.java @@ -147,6 +147,8 @@ public class BlockAlveary extends BlockStructure { return icons[BOTTOM]; switch (metadata) { + case TileAlvearyPlain.BLOCK_META: + return icons[PLAIN]; case 1: return icons[ENTRANCE]; case TileAlvearySwarmer.BLOCK_META: @@ -162,7 +164,7 @@ public class BlockAlveary extends BlockStructure { case TileAlvearySieve.BLOCK_META: return icons[SIEVE]; default: - return icons[PLAIN]; + return null; } } diff --git a/src/main/java/forestry/apiculture/gadgets/BlockBeehives.java b/src/main/java/forestry/apiculture/gadgets/BlockBeehives.java index 1bdf838ca..7d59381b4 100755 --- a/src/main/java/forestry/apiculture/gadgets/BlockBeehives.java +++ b/src/main/java/forestry/apiculture/gadgets/BlockBeehives.java @@ -155,6 +155,9 @@ public class BlockBeehives extends BlockContainer { @Override @SideOnly(Side.CLIENT) public IIcon getIcon(int i, int j) { + if (j == 0 || j >= 8) + return null; + if (i == 0 || i == 1) { if (j * 2 < icons.length && icons[j * 2] != null) return icons[j * 2]; diff --git a/src/main/java/forestry/apiculture/gadgets/TileAlvearyClimatiser.java b/src/main/java/forestry/apiculture/gadgets/TileAlvearyClimatiser.java index b9d31566d..75f3648fb 100755 --- a/src/main/java/forestry/apiculture/gadgets/TileAlvearyClimatiser.java +++ b/src/main/java/forestry/apiculture/gadgets/TileAlvearyClimatiser.java @@ -136,10 +136,6 @@ public abstract class TileAlvearyClimatiser extends TileAlveary implements IPowe nbttagcompound.setInteger("Heating", transferTime); } - @Override - public String getInventoryName() { - return "tile.alveary.climatiser"; - } /* NETWORK */ @Override diff --git a/src/main/java/forestry/apiculture/gadgets/TileAlvearyHygroregulator.java b/src/main/java/forestry/apiculture/gadgets/TileAlvearyHygroregulator.java index 325e2c70c..a12b5af36 100755 --- a/src/main/java/forestry/apiculture/gadgets/TileAlvearyHygroregulator.java +++ b/src/main/java/forestry/apiculture/gadgets/TileAlvearyHygroregulator.java @@ -18,17 +18,20 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; import forestry.api.apiculture.IAlvearyComponent; import forestry.api.core.ForestryAPI; import forestry.core.config.Defaults; +import forestry.core.fluids.TankManager; +import forestry.core.fluids.tanks.FilteredTank; import forestry.core.interfaces.ILiquidTankContainer; import forestry.core.network.GuiId; import forestry.core.proxy.Proxies; -import forestry.core.utils.ForestryTank; import forestry.core.utils.InventoryAdapter; import forestry.core.utils.LiquidHelper; import forestry.core.utils.StackUtils; @@ -57,7 +60,8 @@ public class TileAlvearyHygroregulator extends TileAlveary implements IInventory /* MEMBERS */ InventoryAdapter canInventory = new InventoryAdapter(1, "CanInv"); - private ForestryTank liquidTank = new ForestryTank(Defaults.PROCESSOR_TANK_CAPACITY); + private final TankManager tankManager; + private FilteredTank liquidTank; private HygroregulatorRecipe currentRecipe; private int transferTime; @@ -65,9 +69,16 @@ public class TileAlvearyHygroregulator extends TileAlveary implements IInventory public TileAlvearyHygroregulator() { super(BLOCK_META); - recipes = new HygroregulatorRecipe[] { new HygroregulatorRecipe(new FluidStack(LiquidHelper.getFluid(Defaults.LIQUID_WATER), 1), 1, 0.01f, -0.005f), - new HygroregulatorRecipe(new FluidStack(LiquidHelper.getFluid(Defaults.LIQUID_LAVA), 1), 10, -0.01f, +0.005f), - new HygroregulatorRecipe(new FluidStack(LiquidHelper.getFluid(Defaults.LIQUID_ICE), 1), 10, 0.02f, -0.01f) }; + Fluid water = LiquidHelper.getFluid(Defaults.LIQUID_WATER); + Fluid lava = LiquidHelper.getFluid(Defaults.LIQUID_LAVA); + Fluid liquidIce = LiquidHelper.getFluid(Defaults.LIQUID_ICE); + + liquidTank = new FilteredTank(Defaults.PROCESSOR_TANK_CAPACITY, water, lava, liquidIce); + tankManager = new TankManager(liquidTank); + + recipes = new HygroregulatorRecipe[] { new HygroregulatorRecipe(new FluidStack(water, 1), 1, 0.01f, -0.005f), + new HygroregulatorRecipe(new FluidStack(lava, 1), 10, -0.01f, +0.005f), + new HygroregulatorRecipe(new FluidStack(liquidIce, 1), 10, 0.02f, -0.01f) }; } @Override @@ -77,7 +88,7 @@ public class TileAlvearyHygroregulator extends TileAlveary implements IInventory @Override public String getInventoryName() { - return "tile.alveary.5"; + return getUnlocalizedName(); } /* UPDATING */ @@ -146,9 +157,7 @@ public class TileAlvearyHygroregulator extends TileAlveary implements IInventory canInventory.readFromNBT(nbttagcompound); - liquidTank = new ForestryTank(Defaults.PROCESSOR_TANK_CAPACITY); - if (nbttagcompound.hasKey("LiquidTank")) - liquidTank.readFromNBT(nbttagcompound.getCompoundTag("LiquidTank")); + tankManager.readTanksFromNBT(nbttagcompound); transferTime = nbttagcompound.getInteger("TransferTime"); @@ -164,9 +173,7 @@ public class TileAlvearyHygroregulator extends TileAlveary implements IInventory canInventory.writeToNBT(nbttagcompound); - NBTTagCompound NBTresourceSlot = new NBTTagCompound(); - liquidTank.writeToNBT(NBTresourceSlot); - nbttagcompound.setTag("LiquidTank", NBTresourceSlot); + tankManager.writeTanksToNBT(nbttagcompound); nbttagcompound.setInteger("TransferTime", transferTime); if (currentRecipe != null) { @@ -268,30 +275,54 @@ public class TileAlvearyHygroregulator extends TileAlveary implements IInventory */ @Override public boolean isItemValidForSlot(int slotIndex, ItemStack itemstack) { + if (slotIndex == 0) { + FluidStack fluid = LiquidHelper.getFluidStackInContainer(itemstack); + if (fluid == null || fluid.amount <= 0) + return false; + return liquidTank.accepts(fluid.getFluid()); + } + return super.isItemValidForSlot(slotIndex, itemstack); } /* ILIQUIDTANKCONTAINER */ + @Override + public TankManager getTankManager() { + return tankManager; + } + @Override public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - return liquidTank.fill(resource, doFill); + return tankManager.fill(from, resource, doFill); + } + + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return tankManager.drain(from, resource, doDrain); } @Override public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { - return liquidTank.drain(maxDrain, doDrain); + return tankManager.drain(from, maxDrain, doDrain); } @Override - public ForestryTank[] getTanks() { - return new ForestryTank[] { liquidTank }; + public boolean canFill(ForgeDirection from, Fluid fluid) { + return tankManager.canFill(from, fluid); } - /* SMP GUI */ - public void getGUINetworkData(int i, int j) { + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return tankManager.canDrain(from, fluid); } - public void sendGUINetworkData(Container container, ICrafting iCrafting) { + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return tankManager.getTankInfo(from); } + @Override + public void getGUINetworkData(int messageId, int data) {} + + @Override + public void sendGUINetworkData(Container container, ICrafting iCrafting) {} } diff --git a/src/main/java/forestry/apiculture/gadgets/TileAlvearyPlain.java b/src/main/java/forestry/apiculture/gadgets/TileAlvearyPlain.java index 104284e46..35f2c398c 100755 --- a/src/main/java/forestry/apiculture/gadgets/TileAlvearyPlain.java +++ b/src/main/java/forestry/apiculture/gadgets/TileAlvearyPlain.java @@ -54,6 +54,8 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IS public static final int SLOT_DRONE = 1; public static final int SLOT_PRODUCT_1 = 2; public static final int SLOT_PRODUCTION_COUNT = 7; + public static final int BLOCK_META = 0; + // / MEMBERS protected IBeekeepingLogic beekeepingLogic; protected int biomeId; @@ -582,7 +584,7 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IS @Override public String getInventoryName() { - return "alveary.0"; + return getUnlocalizedName(); } @Override diff --git a/src/main/java/forestry/apiculture/gadgets/TileAlvearySieve.java b/src/main/java/forestry/apiculture/gadgets/TileAlvearySieve.java index 9c79627fc..59108854a 100755 --- a/src/main/java/forestry/apiculture/gadgets/TileAlvearySieve.java +++ b/src/main/java/forestry/apiculture/gadgets/TileAlvearySieve.java @@ -45,10 +45,6 @@ public class TileAlvearySieve extends TileAlveary implements ICrafter, IBeeListe player.openGui(ForestryAPI.instance, GuiId.AlvearySieveGUI.ordinal(), worldObj, xCoord, yCoord, zCoord); } - @Override - public String getInventoryName() { - return "tile.alveary.7"; - } @Override public boolean hasFunction() { diff --git a/src/main/java/forestry/apiculture/gadgets/TileAlvearyStabiliser.java b/src/main/java/forestry/apiculture/gadgets/TileAlvearyStabiliser.java index 1b0ff3200..a2da88c4c 100755 --- a/src/main/java/forestry/apiculture/gadgets/TileAlvearyStabiliser.java +++ b/src/main/java/forestry/apiculture/gadgets/TileAlvearyStabiliser.java @@ -46,10 +46,6 @@ public class TileAlvearyStabiliser extends TileAlveary implements IBeeModifier { ((IAlvearyComponent)getCentralTE()).registerBeeModifier(this); } - @Override - public String getInventoryName() { - return "tile.alveary.6"; - } @Override public boolean hasFunction() { diff --git a/src/main/java/forestry/apiculture/gadgets/TileAlvearySwarmer.java b/src/main/java/forestry/apiculture/gadgets/TileAlvearySwarmer.java index b05f393fb..a7339d22f 100755 --- a/src/main/java/forestry/apiculture/gadgets/TileAlvearySwarmer.java +++ b/src/main/java/forestry/apiculture/gadgets/TileAlvearySwarmer.java @@ -267,7 +267,7 @@ public class TileAlvearySwarmer extends TileAlveary implements ISpecialInventory @Override public String getInventoryName() { - return "tile.alveary.2"; + return getUnlocalizedName(); } @Override diff --git a/src/main/java/forestry/apiculture/gadgets/TileApiary.java b/src/main/java/forestry/apiculture/gadgets/TileApiary.java index 9c0693ff8..ca2d2f098 100755 --- a/src/main/java/forestry/apiculture/gadgets/TileApiary.java +++ b/src/main/java/forestry/apiculture/gadgets/TileApiary.java @@ -30,7 +30,7 @@ public class TileApiary extends TileBeehouse implements ISidedInventory { @Override public String getInventoryName() { - return "apiculture.0"; + return getUnlocalizedName(); } @Override diff --git a/src/main/java/forestry/apiculture/gadgets/TileBeehouse.java b/src/main/java/forestry/apiculture/gadgets/TileBeehouse.java index 3e4f38665..74d68a435 100755 --- a/src/main/java/forestry/apiculture/gadgets/TileBeehouse.java +++ b/src/main/java/forestry/apiculture/gadgets/TileBeehouse.java @@ -68,11 +68,6 @@ public class TileBeehouse extends TileBase implements IBeeHousing, IClimatised { logic = PluginApiculture.beeInterface.createBeekeepingLogic(this); } - @Override - public String getInventoryName() { - return "apiculture.2"; - } - @Override public void openGui(EntityPlayer player, TileBase tile) { player.openGui(ForestryAPI.instance, GuiId.BeehouseGUI.ordinal(), worldObj, xCoord, yCoord, zCoord); diff --git a/src/main/java/forestry/apiculture/gui/ContainerAlvearyHygroregulator.java b/src/main/java/forestry/apiculture/gui/ContainerAlvearyHygroregulator.java index 2692e7552..3f02bc80f 100755 --- a/src/main/java/forestry/apiculture/gui/ContainerAlvearyHygroregulator.java +++ b/src/main/java/forestry/apiculture/gui/ContainerAlvearyHygroregulator.java @@ -37,17 +37,4 @@ public class ContainerAlvearyHygroregulator extends ContainerLiquidTanks { } - @Override - public void updateProgressBar(int i, int j) { - tile.getGUINetworkData(i, j); - } - - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); - - for (int i = 0; i < crafters.size(); i++) - tile.sendGUINetworkData(this, (ICrafting) crafters.get(i)); - } - } diff --git a/src/main/java/forestry/apiculture/gui/ContainerBeealyzer.java b/src/main/java/forestry/apiculture/gui/ContainerBeealyzer.java index 60b9b493c..e2d562dc8 100755 --- a/src/main/java/forestry/apiculture/gui/ContainerBeealyzer.java +++ b/src/main/java/forestry/apiculture/gui/ContainerBeealyzer.java @@ -10,74 +10,17 @@ ******************************************************************************/ package forestry.apiculture.gui; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.item.ItemStack; - +import forestry.core.gui.ContainerAlyzer; +import forestry.core.config.ForestryItem; import forestry.apiculture.items.ItemBeeGE; import forestry.apiculture.items.ItemBeealyzer.BeealyzerInventory; -import forestry.core.config.ForestryItem; -import forestry.core.gui.ContainerItemInventory; -import forestry.core.gui.slots.SlotCustom; -import forestry.core.proxy.Proxies; -public class ContainerBeealyzer extends ContainerItemInventory { +import net.minecraft.entity.player.InventoryPlayer; - BeealyzerInventory inventory; +public class ContainerBeealyzer extends ContainerAlyzer { public ContainerBeealyzer(InventoryPlayer inventoryplayer, BeealyzerInventory inventory) { - super(inventory, inventoryplayer.player); - - this.inventory = inventory; - - // Energy - this.addSlot(new SlotCustom(inventory, BeealyzerInventory.SLOT_ENERGY, 172, 8, new Object[] { ForestryItem.honeydew, ForestryItem.honeyDrop })); - - // Bee to analyze - this.addSlot(new SlotCustom(inventory, BeealyzerInventory.SLOT_SPECIMEN, 172, 26, new Object[] { ItemBeeGE.class })); - - // Analyzed bee - this.addSlot(new SlotCustom(inventory, BeealyzerInventory.SLOT_ANALYZE_1, 172, 57, new Object[] { ItemBeeGE.class })); - this.addSlot(new SlotCustom(inventory, BeealyzerInventory.SLOT_ANALYZE_2, 172, 75, new Object[] { ItemBeeGE.class })); - this.addSlot(new SlotCustom(inventory, BeealyzerInventory.SLOT_ANALYZE_3, 172, 93, new Object[] { ItemBeeGE.class })); - this.addSlot(new SlotCustom(inventory, BeealyzerInventory.SLOT_ANALYZE_4, 172, 111, new Object[] { ItemBeeGE.class })); - this.addSlot(new SlotCustom(inventory, BeealyzerInventory.SLOT_ANALYZE_5, 172, 129, new Object[] { ItemBeeGE.class })); - - // Player inventory - for (int i1 = 0; i1 < 3; i1++) - for (int l1 = 0; l1 < 9; l1++) - addSecuredSlot(inventoryplayer, l1 + i1 * 9 + 9, 18 + l1 * 18, 156 + i1 * 18); - // Player hotbar - for (int j1 = 0; j1 < 9; j1++) - addSecuredSlot(inventoryplayer, j1, 18 + j1 * 18, 214); - - } - - @Override - public void onContainerClosed(EntityPlayer entityplayer) { - - if (!Proxies.common.isSimulating(entityplayer.worldObj)) - return; - - // Last slot is the energy slot, so we don't save that one. - for (int i = 0; i < inventory.getSizeInventory(); i++) { - if (i == BeealyzerInventory.SLOT_ENERGY) - continue; - ItemStack stack = inventory.getStackInSlot(i); - if (stack == null) - continue; - - Proxies.common.dropItemPlayer(entityplayer, stack); - inventory.setInventorySlotContents(i, null); - } - - inventory.onGuiSaved(entityplayer); - - } - - @Override - protected boolean isAcceptedItem(EntityPlayer player, ItemStack stack) { - return true; + super(inventoryplayer, inventory, new Object[] { ForestryItem.honeydew, ForestryItem.honeyDrop }, new Object[] { ItemBeeGE.class }); } } diff --git a/src/main/java/forestry/apiculture/gui/GuiAlveary.java b/src/main/java/forestry/apiculture/gui/GuiAlveary.java index 85da7f1d4..4285f6889 100755 --- a/src/main/java/forestry/apiculture/gui/GuiAlveary.java +++ b/src/main/java/forestry/apiculture/gui/GuiAlveary.java @@ -14,12 +14,11 @@ import net.minecraft.entity.player.InventoryPlayer; import forestry.apiculture.gadgets.TileAlvearyPlain; import forestry.core.config.Defaults; -import forestry.core.gui.GuiForestry; +import forestry.core.gui.GuiForestryTitled; import forestry.core.utils.EnumTankLevel; -import forestry.core.utils.StringUtil; import forestry.core.utils.Utils; -public class GuiAlveary extends GuiForestry { +public class GuiAlveary extends GuiForestryTitled { public GuiAlveary(InventoryPlayer inventory, TileAlvearyPlain tile) { super(Defaults.TEXTURE_PATH_GUI + "/alveary.png", new ContainerAlveary(inventory, tile), tile); @@ -27,13 +26,6 @@ public class GuiAlveary extends GuiForestry { ySize = 190; } - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - super.drawGuiContainerForegroundLayer(mouseX, mouseY); - String title = StringUtil.localize("tile." + tile.getInventoryName()); - this.fontRendererObj.drawString(title, getCenteredOffset(title), 6, fontColor.get("gui.title")); - } - @Override protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); diff --git a/src/main/java/forestry/apiculture/gui/GuiAlvearyHygroregulator.java b/src/main/java/forestry/apiculture/gui/GuiAlvearyHygroregulator.java index 3d5266c5d..6a7c16190 100755 --- a/src/main/java/forestry/apiculture/gui/GuiAlvearyHygroregulator.java +++ b/src/main/java/forestry/apiculture/gui/GuiAlvearyHygroregulator.java @@ -14,23 +14,15 @@ import net.minecraft.entity.player.InventoryPlayer; import forestry.apiculture.gadgets.TileAlvearyHygroregulator; import forestry.core.config.Defaults; -import forestry.core.gui.GuiForestry; +import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.widgets.TankWidget; -import forestry.core.utils.StringUtil; -public class GuiAlvearyHygroregulator extends GuiForestry { +public class GuiAlvearyHygroregulator extends GuiForestryTitled { public GuiAlvearyHygroregulator(InventoryPlayer inventory, TileAlvearyHygroregulator tile) { - super(Defaults.TEXTURE_PATH_GUI + "/hygroregulator.png", new ContainerAlvearyHygroregulator(inventory, tile)); + super(Defaults.TEXTURE_PATH_GUI + "/hygroregulator.png", new ContainerAlvearyHygroregulator(inventory, tile), tile); widgetManager.add(new TankWidget(this.widgetManager, 104, 17, 0)); } - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - super.drawGuiContainerForegroundLayer(mouseX, mouseY); - String name = StringUtil.localize("tile.alveary.5"); - this.fontRendererObj.drawString(name, getCenteredOffset(name), 6, fontColor.get("gui.title")); - } - } diff --git a/src/main/java/forestry/apiculture/gui/GuiApiary.java b/src/main/java/forestry/apiculture/gui/GuiApiary.java index c3cf7c821..1a73b16a3 100755 --- a/src/main/java/forestry/apiculture/gui/GuiApiary.java +++ b/src/main/java/forestry/apiculture/gui/GuiApiary.java @@ -15,12 +15,11 @@ import net.minecraft.entity.player.InventoryPlayer; import forestry.apiculture.gadgets.TileApiary; import forestry.apiculture.gadgets.TileBeehouse; import forestry.core.config.Defaults; -import forestry.core.gui.GuiForestry; +import forestry.core.gui.GuiForestryTitled; import forestry.core.utils.EnumTankLevel; -import forestry.core.utils.StringUtil; import forestry.core.utils.Utils; -public class GuiApiary extends GuiForestry { +public class GuiApiary extends GuiForestryTitled { public GuiApiary(InventoryPlayer inventory, TileApiary tile) { super(Defaults.TEXTURE_PATH_GUI + "/apiary.png", new ContainerApiary(inventory, tile, true), tile); @@ -34,13 +33,6 @@ public class GuiApiary extends GuiForestry { ySize = 190; } - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - super.drawGuiContainerForegroundLayer(mouseX, mouseY); - String name = StringUtil.localize("tile.for." + tile.getInventoryName()); - this.fontRendererObj.drawString(name, getCenteredOffset(name), 6, fontColor.get("gui.title")); - } - @Override protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); diff --git a/src/main/java/forestry/apiculture/gui/GuiBeealyzer.java b/src/main/java/forestry/apiculture/gui/GuiBeealyzer.java index 1f38a8a3d..7745dca4e 100755 --- a/src/main/java/forestry/apiculture/gui/GuiBeealyzer.java +++ b/src/main/java/forestry/apiculture/gui/GuiBeealyzer.java @@ -41,8 +41,7 @@ public class GuiBeealyzer extends GuiAlyzer { super(AlleleManager.alleleRegistry.getSpeciesRoot("rootBees"), player, new ContainerBeealyzer(player.inventory, inventory), inventory, 1, inventory.getSizeInventory()); - xSize = 196; - ySize = 238; + guiName = "gui.beealyzer"; ArrayList beeList = new ArrayList(); ((ItemBeeGE) ForestryItem.beeDroneGE.item()).addCreativeItems(beeList, false); @@ -96,45 +95,6 @@ public class GuiBeealyzer extends GuiAlyzer { } - private void drawAnalyticsOverview() { - - startPage(); - - newLine(); - String title = StringUtil.localize("gui.beealyzer").toUpperCase(); - drawCenteredLine(title, 8, 158); - newLine(); - - fontRendererObj.drawSplitString(StringUtil.localize("gui.beealyzer.help"), (int) ((guiLeft + COLUMN_0 + 4) * (1 / factor)), - (int) ((guiTop + 42) * (1 / factor)), (int) (158 * (1 / factor)), fontColor.get("gui.screen")); - newLine(); - newLine(); - newLine(); - newLine(); - - drawLine(StringUtil.localize("gui.beealyzer.overview") + ":", COLUMN_0 + 4); - newLine(); - drawLine("I : " + StringUtil.localize("gui.general"), COLUMN_0 + 4); - newLine(); - drawLine("II : " + StringUtil.localize("gui.environment"), COLUMN_0 + 4); - newLine(); - drawLine("III: " + StringUtil.localize("gui.produce"), COLUMN_0 + 4); - newLine(); - drawLine("IV : " + StringUtil.localize("gui.evolution"), COLUMN_0 + 4); - - newLine(); - - String mode = breedingTracker.getModeName(); - if (mode != null && !mode.isEmpty()) { - newLine(); - String rules = StringUtil.localize("gui.beealyzer.behaviour") + ": " + StringUtil.capitalize(mode); - drawLine(rules, 8 + getCenteredOffset(title, 158), fontColor.get("gui.beealyzer.binomial")); - } - - endPage(); - - } - private void drawAnalyticsPage1(IBee bee, EnumBeeType type) { startPage(COLUMN_0, COLUMN_1, COLUMN_2); @@ -268,16 +228,14 @@ public class GuiBeealyzer extends GuiAlyzer { if (!bee.isNatural()) displayText = "bees.stock.ignoble"; displayText = StringUtil.localize(displayText); - // int offset = (int)(((158 - fontRendererObj.getStringWidth(origin)) / 2)*(1/factor)); - drawCenteredLine(displayText, 8, 158, fontColor.get("gui.beealyzer.binomial"));; + drawCenteredLine(displayText, 8, 208, fontColor.get("gui.beealyzer.binomial")); } if (bee.getGeneration() >= 0) { newLine(); displayText = StringUtil.localizeAndFormat("gui.beealyzer.generations", bee.getGeneration()); - // offset = (int)(((158 - fontRendererObj.getStringWidth(origin)) / 2)*(1/factor)); - drawCenteredLine(displayText, 8, 158, fontColor.get("gui.beealyzer.binomial")); + drawCenteredLine(displayText, 8, 208, fontColor.get("gui.beealyzer.binomial")); } endPage(); @@ -285,6 +243,9 @@ public class GuiBeealyzer extends GuiAlyzer { private void drawAnalyticsPage3(IBee bee, EnumBeeType type) { + float factor = this.factor; + this.setFactor(1.0f); + tempProductList = bee.getProduceList(); startPage(COLUMN_0, COLUMN_1, COLUMN_2); @@ -295,8 +256,8 @@ public class GuiBeealyzer extends GuiAlyzer { int x = COLUMN_0; for (ItemStack stack : tempProductList) { - itemRender.renderItemIntoGUI(fontRendererObj, mc.renderEngine, stack, (int) ((guiLeft + x) * (1 / factor)), - (int) ((guiTop + getLineY()) * (1 / factor))); + widgetManager.add(new ItemStackWidget(adjustToFactor(x), adjustToFactor(getLineY()), stack)); + x += 18; if (x > adjustToFactor(148)) { x = COLUMN_0; @@ -304,16 +265,16 @@ public class GuiBeealyzer extends GuiAlyzer { } } + newLine(); newLine(); newLine(); drawLine(StringUtil.localize("gui.beealyzer.specialty") + ":", COLUMN_0); - newLine(); x = COLUMN_0; for (ItemStack stack : bee.getSpecialtyList()) { - itemRender.renderItemIntoGUI(fontRendererObj, mc.renderEngine, stack, (int) ((guiLeft + x) * (1 / factor)), - (int) ((guiTop + getLineY()) * (1 / factor))); + widgetManager.add(new ItemStackWidget(adjustToFactor(x), adjustToFactor(getLineY()), stack)); + x += 18; if (x > adjustToFactor(148)) { x = COLUMN_0; @@ -322,6 +283,8 @@ public class GuiBeealyzer extends GuiAlyzer { } endPage(); + + this.setFactor(factor); } } diff --git a/src/main/java/forestry/apiculture/items/ItemBeeGE.java b/src/main/java/forestry/apiculture/items/ItemBeeGE.java index 90b484238..be2a1768c 100755 --- a/src/main/java/forestry/apiculture/items/ItemBeeGE.java +++ b/src/main/java/forestry/apiculture/items/ItemBeeGE.java @@ -77,7 +77,10 @@ public class ItemBeeGE extends ItemGE { if(StatCollector.canTranslate("for." + customBeeKey)){ return StringUtil.localize(customBeeKey); } - return StringUtil.localize("bees.grammar." + type.getName()).replaceAll("%SPECIES", individual.getDisplayName()).replaceAll("%TYPE", StringUtil.localize("bees.grammar." + type.getName() + ".type")); + String beeGrammar = StringUtil.localize("bees.grammar." + type.getName()); + String beeSpecies = individual.getDisplayName(); + String beeType = StringUtil.localize("bees.grammar." + type.getName() + ".type"); + return beeGrammar.replaceAll("%SPECIES", beeSpecies).replaceAll("%TYPE", beeType); } @SuppressWarnings({ "rawtypes", "unchecked" }) diff --git a/src/main/java/forestry/apiculture/items/ItemBeealyzer.java b/src/main/java/forestry/apiculture/items/ItemBeealyzer.java index 1fa0bcab4..fc74aa51b 100755 --- a/src/main/java/forestry/apiculture/items/ItemBeealyzer.java +++ b/src/main/java/forestry/apiculture/items/ItemBeealyzer.java @@ -10,10 +10,10 @@ ******************************************************************************/ package forestry.apiculture.items; +import forestry.core.utils.AlyzerInventory; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; import net.minecraft.world.World; import forestry.api.apiculture.IBee; @@ -27,22 +27,11 @@ import forestry.core.interfaces.IHintSource; import forestry.core.items.ItemInventoried; import forestry.core.network.GuiId; import forestry.core.proxy.Proxies; -import forestry.core.utils.ItemInventory; import forestry.plugins.PluginApiculture; public class ItemBeealyzer extends ItemInventoried { - public static class BeealyzerInventory extends ItemInventory implements IErrorSource, IHintSource { - - public static final int SLOT_SPECIMEN = 0; - public static final int SLOT_ANALYZE_1 = 1; - public static final int SLOT_ANALYZE_2 = 2; - public static final int SLOT_ANALYZE_3 = 3; - public static final int SLOT_ANALYZE_4 = 4; - public static final int SLOT_ANALYZE_5 = 6; - public static final int SLOT_ENERGY = 5; - - EntityPlayer player; + public static class BeealyzerInventory extends AlyzerInventory implements IErrorSource, IHintSource { public BeealyzerInventory(EntityPlayer player) { super(ItemBeealyzer.class, 7); @@ -54,21 +43,6 @@ public class ItemBeealyzer extends ItemInventoried { this.player = player; } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - - NBTTagList nbttaglist = new NBTTagList(); - for (int i = SLOT_ENERGY; i < SLOT_ENERGY + 1; i++) - if (inventoryStacks[i] != null) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - nbttagcompound1.setByte("Slot", (byte) i); - inventoryStacks[i].writeToNBT(nbttagcompound1); - nbttaglist.appendTag(nbttagcompound1); - } - nbttagcompound.setTag("Items", nbttaglist); - - } - private boolean isEnergy(ItemStack itemstack) { if (itemstack == null || itemstack.stackSize <= 0) return false; diff --git a/src/main/java/forestry/arboriculture/gadgets/BlockLeaves.java b/src/main/java/forestry/arboriculture/gadgets/BlockLeaves.java index 3452d5474..f0052ec42 100755 --- a/src/main/java/forestry/arboriculture/gadgets/BlockLeaves.java +++ b/src/main/java/forestry/arboriculture/gadgets/BlockLeaves.java @@ -18,8 +18,10 @@ import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; +import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.ColorizerFoliage; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; @@ -35,6 +37,8 @@ import forestry.api.arboriculture.ITree; import forestry.api.core.IToolScoop; import forestry.api.lepidopterology.EnumFlutterType; import forestry.api.lepidopterology.IButterfly; +import forestry.arboriculture.items.ItemLeavesBlock; +import forestry.core.config.ForestryBlock; import forestry.core.config.Defaults; import forestry.core.proxy.Proxies; import forestry.core.render.TextureManager; @@ -147,6 +151,20 @@ public class BlockLeaves extends BlockTreeContainer { return prod; } + @Override + public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { + TileLeaves leaves = getLeafTile(world, x, y, z); + + NBTTagCompound nbttagcompound = new NBTTagCompound(); + leaves.getTree().writeToNBT(nbttagcompound); + + ItemLeavesBlock leavesItem = (ItemLeavesBlock)ForestryBlock.leaves.item(); + ItemStack leavesStack = new ItemStack(leavesItem); + leavesStack.setTagCompound(nbttagcompound); + + return leavesStack; + } + /* RENDERING */ @Override public boolean isOpaqueCube() { diff --git a/src/main/java/forestry/arboriculture/gadgets/BlockLog.java b/src/main/java/forestry/arboriculture/gadgets/BlockLog.java index 65e2b9802..2054ed499 100755 --- a/src/main/java/forestry/arboriculture/gadgets/BlockLog.java +++ b/src/main/java/forestry/arboriculture/gadgets/BlockLog.java @@ -103,6 +103,7 @@ public class BlockLog extends Block implements IWoodTyped { @Override public void getSubBlocks(Item item, CreativeTabs par2CreativeTabs, List itemList) { if(cat == LogCat.CAT6) { + itemList.add(new ItemStack(this, 1, 0)); return; } @@ -123,7 +124,10 @@ public class BlockLog extends Block implements IWoodTyped { int oriented = meta & 12; - WoodType type = getWoodType(getTypeFromMeta(meta)); + WoodType type = getWoodType(meta); + if (type == null) + return null; + switch (oriented) { case 4: if (side > 3) @@ -157,7 +161,7 @@ public class BlockLog extends Block implements IWoodTyped { /* PROPERTIES */ @Override public float getBlockHardness(World world, int x, int y, int z) { - return getWoodType(getTypeFromMeta(world.getBlockMetadata(x, y, z))).getHardness(); + return getWoodType(world.getBlockMetadata(x, y, z)).getHardness(); } @Override @@ -192,10 +196,11 @@ public class BlockLog extends Block implements IWoodTyped { @Override public WoodType getWoodType(int meta) { + meta = getTypeFromMeta(meta); if(meta + cat.ordinal() * 4 < WoodType.VALUES.length) return WoodType.VALUES[meta + cat.ordinal() * 4]; else - return WoodType.LARCH; + return null; } @Override diff --git a/src/main/java/forestry/arboriculture/gadgets/BlockSapling.java b/src/main/java/forestry/arboriculture/gadgets/BlockSapling.java index 83443a9a6..31ae5d07b 100755 --- a/src/main/java/forestry/arboriculture/gadgets/BlockSapling.java +++ b/src/main/java/forestry/arboriculture/gadgets/BlockSapling.java @@ -20,6 +20,7 @@ import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.IIcon; +import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; @@ -145,6 +146,12 @@ public class BlockSapling extends BlockTreeContainer { return new ArrayList(); } + @Override + public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { + TileSapling sapling = getSaplingTile(world, x, y, z); + return PluginArboriculture.treeInterface.getMemberStack(sapling.getTree(), EnumGermlingType.SAPLING.ordinal()); + } + @Override public boolean removedByPlayer(World world, EntityPlayer player, int x, int y, int z, boolean willHarvest) { if (Proxies.common.isSimulating(world) && canHarvestBlock(player, world.getBlockMetadata(x, y, z))) diff --git a/src/main/java/forestry/arboriculture/gadgets/TileLeaves.java b/src/main/java/forestry/arboriculture/gadgets/TileLeaves.java index c4cc844f1..83f2d81a3 100755 --- a/src/main/java/forestry/arboriculture/gadgets/TileLeaves.java +++ b/src/main/java/forestry/arboriculture/gadgets/TileLeaves.java @@ -277,16 +277,16 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru /* NETWORK */ @Override public Packet getDescriptionPacket() { - return new PacketLeafUpdate(xCoord, yCoord, zCoord, this).getPacket(); + return new PacketLeafUpdate(this).getPacket(); } @Override public void sendNetworkUpdate() { - Proxies.net.sendNetworkPacket(new PacketLeafUpdate(xCoord, yCoord, zCoord, this), xCoord, yCoord, zCoord); + Proxies.net.sendNetworkPacket(new PacketLeafUpdate(this), xCoord, yCoord, zCoord); } private void sendNetworkUpdateRipening() { - Proxies.net.sendNetworkPacket(new PacketLeafUpdate(xCoord, yCoord, zCoord, determineFruitColour()), xCoord, yCoord, zCoord); + Proxies.net.sendNetworkPacket(new PacketLeafUpdate(this, determineFruitColour()), xCoord, yCoord, zCoord); } @Override @@ -296,6 +296,7 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru if(packet.isRipeningUpdate()) { colourFruits = packet.colourFruits; } else { + readFromNBT(packet.getTagCompound()); isFruitLeaf = packet.isFruitLeaf(); isPollinatedState = packet.isPollinated(); textureIndexFancy = packet.textureIndexFancy; diff --git a/src/main/java/forestry/arboriculture/genetics/GrowthProvider.java b/src/main/java/forestry/arboriculture/genetics/GrowthProvider.java index eb290a320..9f367b6d2 100755 --- a/src/main/java/forestry/arboriculture/genetics/GrowthProvider.java +++ b/src/main/java/forestry/arboriculture/genetics/GrowthProvider.java @@ -39,7 +39,7 @@ public class GrowthProvider implements IGrowthProvider { @Override public String getDescription() { - return StringUtil.localize("gui.growth.normal"); + return StringUtil.localize("growth.normal"); } @Override diff --git a/src/main/java/forestry/arboriculture/genetics/GrowthProviderTropical.java b/src/main/java/forestry/arboriculture/genetics/GrowthProviderTropical.java index f13fbba1d..2c3125665 100755 --- a/src/main/java/forestry/arboriculture/genetics/GrowthProviderTropical.java +++ b/src/main/java/forestry/arboriculture/genetics/GrowthProviderTropical.java @@ -12,19 +12,20 @@ package forestry.arboriculture.genetics; import java.util.EnumSet; -import forestry.core.utils.StringUtil; +import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.World; import forestry.api.arboriculture.EnumGrowthConditions; import forestry.api.arboriculture.ITreeGenome; +import forestry.core.utils.StringUtil; public class GrowthProviderTropical extends GrowthProvider { @Override public EnumGrowthConditions getGrowthConditions(ITreeGenome genome, World world, int xPos, int yPos, int zPos) { EnumGrowthConditions light = getConditionFromLight(world, xPos, yPos, zPos); - EnumGrowthConditions moisture = getConditionsFromRainfall(world, xPos, yPos, zPos, 0.9f, 2.0f); - EnumGrowthConditions temperature = getConditionsFromTemperature(world, xPos, yPos, zPos, 1.2f, 1.9f); + EnumGrowthConditions moisture = getConditionsFromRainfall(world, xPos, yPos, zPos, BiomeGenBase.jungle.rainfall, 2.0f); + EnumGrowthConditions temperature = getConditionsFromTemperature(world, xPos, yPos, zPos, BiomeGenBase.jungle.temperature, BiomeGenBase.desert.temperature - 0.1f); EnumSet conditions = EnumSet.of(light, moisture, temperature); @@ -42,7 +43,7 @@ public class GrowthProviderTropical extends GrowthProvider { @Override public String getDescription() { - return StringUtil.localize("gui.growth.tropical"); + return StringUtil.localize("growth.tropical"); } } diff --git a/src/main/java/forestry/arboriculture/gui/ContainerTreealyzer.java b/src/main/java/forestry/arboriculture/gui/ContainerTreealyzer.java index 742414e68..6d92cae38 100755 --- a/src/main/java/forestry/arboriculture/gui/ContainerTreealyzer.java +++ b/src/main/java/forestry/arboriculture/gui/ContainerTreealyzer.java @@ -10,77 +10,23 @@ ******************************************************************************/ package forestry.arboriculture.gui; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.item.ItemStack; - -import org.apache.commons.lang3.ArrayUtils; - import forestry.api.genetics.AlleleManager; +import forestry.core.gui.ContainerAlyzer; +import forestry.core.config.ForestryItem; import forestry.arboriculture.items.ItemGermlingGE; import forestry.arboriculture.items.ItemTreealyzer.TreealyzerInventory; -import forestry.core.config.ForestryItem; -import forestry.core.gui.ContainerItemInventory; -import forestry.core.gui.slots.SlotCustom; -import forestry.core.proxy.Proxies; -public class ContainerTreealyzer extends ContainerItemInventory { +import net.minecraft.entity.player.InventoryPlayer; +import org.apache.commons.lang3.ArrayUtils; + +public class ContainerTreealyzer extends ContainerAlyzer { TreealyzerInventory inventory; + private static Object[] acceptedEnergy = new Object[] {ForestryItem.honeydew, ForestryItem.honeyDrop}; + private static Object[] acceptedSpecimens = ArrayUtils.addAll(AlleleManager.ersatzSaplings.keySet().toArray(), ItemGermlingGE.class); public ContainerTreealyzer(InventoryPlayer inventoryplayer, TreealyzerInventory inventory) { - super(inventory, inventoryplayer.player); - - this.inventory = inventory; - - // Energy - this.addSlot(new SlotCustom(inventory, TreealyzerInventory.SLOT_ENERGY, 172, 8, new Object[] { ForestryItem.honeydew, ForestryItem.honeyDrop })); - - // Tree to analyze - this.addSlot(new SlotCustom(inventory, TreealyzerInventory.SLOT_SPECIMEN, 172, 26, ArrayUtils.addAll(AlleleManager.ersatzSaplings.keySet().toArray(new Object[0]), ItemGermlingGE.class))); - - // Analyzed tree - this.addSlot(new SlotCustom(inventory, TreealyzerInventory.SLOT_ANALYZE_1, 172, 57, new Object[] { ItemGermlingGE.class })); - this.addSlot(new SlotCustom(inventory, TreealyzerInventory.SLOT_ANALYZE_2, 172, 75, new Object[] { ItemGermlingGE.class })); - this.addSlot(new SlotCustom(inventory, TreealyzerInventory.SLOT_ANALYZE_3, 172, 93, new Object[] { ItemGermlingGE.class })); - this.addSlot(new SlotCustom(inventory, TreealyzerInventory.SLOT_ANALYZE_4, 172, 111, new Object[] { ItemGermlingGE.class })); - this.addSlot(new SlotCustom(inventory, TreealyzerInventory.SLOT_ANALYZE_5, 172, 129, new Object[] { ItemGermlingGE.class })); - - // Player inventory - for (int i1 = 0; i1 < 3; i1++) - for (int l1 = 0; l1 < 9; l1++) - addSecuredSlot(inventoryplayer, l1 + i1 * 9 + 9, 18 + l1 * 18, 156 + i1 * 18); - // Player hotbar - for (int j1 = 0; j1 < 9; j1++) - addSecuredSlot(inventoryplayer, j1, 18 + j1 * 18, 214); - - } - - @Override - public void onContainerClosed(EntityPlayer entityplayer) { - - if (!Proxies.common.isSimulating(entityplayer.worldObj)) - return; - - // Last slot is the energy slot, so we don't save that one. - for (int i = 0; i < inventory.getSizeInventory(); i++) { - if (i == TreealyzerInventory.SLOT_ENERGY) - continue; - ItemStack stack = inventory.getStackInSlot(i); - if (stack == null) - continue; - - Proxies.common.dropItemPlayer(entityplayer, stack); - inventory.setInventorySlotContents(i, null); - } - - inventory.onGuiSaved(entityplayer); - - } - - @Override - protected boolean isAcceptedItem(EntityPlayer player, ItemStack stack) { - return true; + super(inventoryplayer, inventory, acceptedEnergy, acceptedSpecimens); } } diff --git a/src/main/java/forestry/arboriculture/gui/GuiTreealyzer.java b/src/main/java/forestry/arboriculture/gui/GuiTreealyzer.java index cc91b1848..6d55ed488 100755 --- a/src/main/java/forestry/arboriculture/gui/GuiTreealyzer.java +++ b/src/main/java/forestry/arboriculture/gui/GuiTreealyzer.java @@ -46,8 +46,7 @@ public class GuiTreealyzer extends GuiAlyzer { super(AlleleManager.alleleRegistry.getSpeciesRoot("rootTrees"), player, new ContainerTreealyzer(player.inventory, inventory), inventory, 1, inventory.getSizeInventory()); - xSize = 196; - ySize = 238; + guiName = "gui.treealyzer"; ArrayList treeList = new ArrayList(); ((ItemGermlingGE) ForestryItem.sapling.item()).addCreativeItems(treeList, false); @@ -99,35 +98,6 @@ public class GuiTreealyzer extends GuiAlyzer { } - private void drawAnalyticsOverview() { - - startPage(); - - newLine(); - String title = StringUtil.localize("gui.treealyzer").toUpperCase(); - drawCenteredLine(title, 8, 158); - newLine(); - - fontRendererObj.drawSplitString(StringUtil.localize("gui.treealyzer.help"), (int) ((guiLeft + COLUMN_0 + 4) * (1 / factor)), - (int) ((guiTop + 42) * (1 / factor)), (int) (158 * (1 / factor)), fontColor.get("gui.screen")); - newLine(); - newLine(); - newLine(); - newLine(); - - drawLine(StringUtil.localize("gui.treealyzer.overview") + ":", COLUMN_0 + 4); - newLine(); - drawLine("I : " + StringUtil.localize("gui.general"), COLUMN_0 + 4); - newLine(); - drawLine("II : " + StringUtil.localize("gui.environment"), COLUMN_0 + 4); - newLine(); - drawLine("III: " + StringUtil.localize("gui.produce"), COLUMN_0 + 4); - newLine(); - drawLine("IV : " + StringUtil.localize("gui.evolution"), COLUMN_0 + 4); - - endPage(); - } - private void drawAnalyticsPage1(ITree tree, EnumGermlingType type) { startPage(COLUMN_0, COLUMN_1, COLUMN_2); diff --git a/src/main/java/forestry/arboriculture/items/ItemLeavesBlock.java b/src/main/java/forestry/arboriculture/items/ItemLeavesBlock.java new file mode 100644 index 000000000..da1cda956 --- /dev/null +++ b/src/main/java/forestry/arboriculture/items/ItemLeavesBlock.java @@ -0,0 +1,43 @@ +package forestry.arboriculture.items; + +import forestry.api.arboriculture.ITree; +import forestry.arboriculture.genetics.Tree; +import forestry.core.items.ItemForestryBlock; +import forestry.core.utils.StringUtil; + +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; +import net.minecraft.util.StatCollector; + +public class ItemLeavesBlock extends ItemForestryBlock { + + public ItemLeavesBlock(Block block) { + super(block); + } + + @Override + public String getItemStackDisplayName(ItemStack itemstack) { + String type = StringUtil.localize("trees.grammar.leaves.type"); + if (!itemstack.hasTagCompound()) + return type; + ITree tree = getTree(itemstack); + String customTreeKey = "trees.custom.leaves." + tree.getGenome().getPrimary().getUnlocalizedName().replace("trees.species.",""); + if(StatCollector.canTranslate("for." + customTreeKey)){ + return StringUtil.localize(customTreeKey); + } + String grammar = StringUtil.localize("trees.grammar.leaves"); + + return grammar.replaceAll("%SPECIES", tree.getDisplayName()).replaceAll("%TYPE", type); + } + + @Override + public int getColorFromItemStack(ItemStack itemstack, int renderPass) { + ITree tree = getTree(itemstack); + return tree.getGenome().getPrimary().getLeafColour(tree); + } + + private ITree getTree(ItemStack itemStack) { + return new Tree(itemStack.getTagCompound()); + } + +} diff --git a/src/main/java/forestry/arboriculture/items/ItemTreealyzer.java b/src/main/java/forestry/arboriculture/items/ItemTreealyzer.java index 95004f75e..15a63b279 100755 --- a/src/main/java/forestry/arboriculture/items/ItemTreealyzer.java +++ b/src/main/java/forestry/arboriculture/items/ItemTreealyzer.java @@ -13,9 +13,9 @@ package forestry.arboriculture.items; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; import net.minecraft.world.World; +import forestry.core.utils.AlyzerInventory; import forestry.api.arboriculture.ITree; import forestry.api.core.ForestryAPI; import forestry.api.core.Tabs; @@ -27,22 +27,12 @@ import forestry.core.interfaces.IHintSource; import forestry.core.items.ItemInventoried; import forestry.core.network.GuiId; import forestry.core.proxy.Proxies; -import forestry.core.utils.ItemInventory; import forestry.core.utils.Utils; import forestry.plugins.PluginArboriculture; public class ItemTreealyzer extends ItemInventoried { - public static class TreealyzerInventory extends ItemInventory implements IErrorSource, IHintSource { - - public final static int SLOT_SPECIMEN = 0; - public final static int SLOT_ANALYZE_1 = 1; - public final static int SLOT_ANALYZE_2 = 2; - public final static int SLOT_ANALYZE_3 = 3; - public final static int SLOT_ANALYZE_4 = 4; - public final static int SLOT_ANALYZE_5 = 6; - public final static int SLOT_ENERGY = 5; - EntityPlayer player; + public static class TreealyzerInventory extends AlyzerInventory implements IErrorSource, IHintSource { public TreealyzerInventory(EntityPlayer player) { super(ItemTreealyzer.class, 7); @@ -54,22 +44,6 @@ public class ItemTreealyzer extends ItemInventoried { this.player = player; } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - - NBTTagList nbttaglist = new NBTTagList(); - for (int i = SLOT_ENERGY; i < SLOT_ENERGY + 1; i++) { - if (inventoryStacks[i] != null) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - nbttagcompound1.setByte("Slot", (byte) i); - inventoryStacks[i].writeToNBT(nbttagcompound1); - nbttaglist.appendTag(nbttagcompound1); - } - } - nbttagcompound.setTag("Items", nbttaglist); - - } - private boolean isEnergy(ItemStack itemstack) { if (itemstack == null || itemstack.stackSize <= 0) return false; diff --git a/src/main/java/forestry/arboriculture/items/ItemWoodBlock.java b/src/main/java/forestry/arboriculture/items/ItemWoodBlock.java index d7b4edb70..62387fae2 100755 --- a/src/main/java/forestry/arboriculture/items/ItemWoodBlock.java +++ b/src/main/java/forestry/arboriculture/items/ItemWoodBlock.java @@ -34,6 +34,8 @@ public class ItemWoodBlock extends ItemForestryBlock { IWoodTyped block = (IWoodTyped) getBlock(); int meta = itemstack.getItemDamage(); WoodType woodType = block.getWoodType(meta); + if (woodType == null) + return null; return "tile.for." + block.getBlockKind() + "." + woodType.ordinal(); } return super.getUnlocalizedName(itemstack); diff --git a/src/main/java/forestry/arboriculture/network/PacketLeafUpdate.java b/src/main/java/forestry/arboriculture/network/PacketLeafUpdate.java index 8367fa9d1..abcff5967 100755 --- a/src/main/java/forestry/arboriculture/network/PacketLeafUpdate.java +++ b/src/main/java/forestry/arboriculture/network/PacketLeafUpdate.java @@ -15,10 +15,10 @@ import java.io.DataOutputStream; import java.io.IOException; import forestry.arboriculture.gadgets.TileLeaves; -import forestry.core.network.PacketCoordinates; import forestry.core.network.PacketIds; +import forestry.core.network.PacketTileNBT; -public class PacketLeafUpdate extends PacketCoordinates { +public class PacketLeafUpdate extends PacketTileNBT { public byte isRipeningUpdate = 0; @@ -33,8 +33,8 @@ public class PacketLeafUpdate extends PacketCoordinates { public PacketLeafUpdate() { } - public PacketLeafUpdate(int posX, int posY, int posZ, TileLeaves leaves) { - super(PacketIds.LEAF_UPDATE, posX, posY, posZ); + public PacketLeafUpdate(TileLeaves leaves) { + super(PacketIds.LEAF_UPDATE, leaves); leafState = 0; if(leaves.hasFruit()) @@ -48,8 +48,8 @@ public class PacketLeafUpdate extends PacketCoordinates { colourFruits = leaves.determineFruitColour(); } - public PacketLeafUpdate(int posX, int posY, int posZ, int fruitColour) { - super(PacketIds.LEAF_UPDATE, posX, posY, posZ); + public PacketLeafUpdate(TileLeaves leaves, int fruitColour) { + super(PacketIds.LEAF_UPDATE, leaves); isRipeningUpdate = 1; colourFruits = fruitColour; diff --git a/src/main/java/forestry/arboriculture/worldgen/BlockTypeLeaf.java b/src/main/java/forestry/arboriculture/worldgen/BlockTypeLeaf.java index 14561fca7..ccf0eb716 100755 --- a/src/main/java/forestry/arboriculture/worldgen/BlockTypeLeaf.java +++ b/src/main/java/forestry/arboriculture/worldgen/BlockTypeLeaf.java @@ -24,6 +24,7 @@ public class BlockTypeLeaf extends BlockType { public BlockTypeLeaf(GameProfile owner) { super(ForestryBlock.leaves, 0); + this.owner = owner; } @Override diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenArboriculture.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenArboriculture.java index 3d44fd5e5..cb868ed4b 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenArboriculture.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenArboriculture.java @@ -58,10 +58,10 @@ public abstract class WorldGenArboriculture extends WorldGenBase { private GameProfile getOwner() { TileEntity tile = world.getTileEntity(startX, startY, startZ); - if (!(tile instanceof TileSapling)) - return Utils.getForestryPlayerProfile(); - - return ((TileSapling) tile).getOwnerProfile(); + if (tile instanceof TileSapling) + return ((TileSapling) tile).getOwnerProfile(); + else + return null; } public abstract void preGenerate(); diff --git a/src/main/java/forestry/core/EnumErrorCode.java b/src/main/java/forestry/core/EnumErrorCode.java index 0efcfb27e..64d96143b 100755 --- a/src/main/java/forestry/core/EnumErrorCode.java +++ b/src/main/java/forestry/core/EnumErrorCode.java @@ -66,7 +66,7 @@ public enum EnumErrorCode { NOHONEY("noHoney", 22), - NOTPOSTPAID("notPostpaid", 23), + NOTPOSTPAID("notPostpaid", "noStamps", 23), NORECIPIENT("noRecipient", 24), @@ -86,14 +86,28 @@ public enum EnumErrorCode { CIRCUITMISMATCH("circuitMismatch", 26), - NOLIQUID("noLiquid", 29); + NOLIQUID("noLiquid", 29), + + NOPAPER("noPaper", 30), + + NOSTAMPSNOPAPER("noStampsNoPaper", "noStamps", 31), + + NOSUPPLIES("noSupplies", "noResource", 32), + + NOTRADE("noTrade", "noResource", 33); private String name; + private String iconName; @SideOnly(Side.CLIENT) private IIcon icon; private EnumErrorCode(String name, int iconIndex) { + this(name, name, iconIndex); + } + + private EnumErrorCode(String name, String iconName, int iconIndex) { this.name = name; + this.iconName = iconName; } public String getDescription() { @@ -106,7 +120,7 @@ public enum EnumErrorCode { @SideOnly(Side.CLIENT) public void registerIcons(IIconRegister register) { - icon = TextureManager.getInstance().registerTex(register, "errors/" + name); + icon = TextureManager.getInstance().registerTex(register, "errors/" + iconName); } @SideOnly(Side.CLIENT) diff --git a/src/main/java/forestry/core/IItemTyped.java b/src/main/java/forestry/core/IItemTyped.java new file mode 100644 index 000000000..c53101f1c --- /dev/null +++ b/src/main/java/forestry/core/IItemTyped.java @@ -0,0 +1,5 @@ +package forestry.core; + +public interface IItemTyped { + public Enum getTypeFromMeta(int meta); +} diff --git a/src/main/java/forestry/core/circuits/Circuit.java b/src/main/java/forestry/core/circuits/Circuit.java index dadff587a..313b37b21 100755 --- a/src/main/java/forestry/core/circuits/Circuit.java +++ b/src/main/java/forestry/core/circuits/Circuit.java @@ -21,14 +21,10 @@ public abstract class Circuit implements ICircuit { String uid; int limit = 1; boolean requiresDiscovery; - String name; - String[] descriptions; - public Circuit(String uid, boolean requiresDiscovery, String name, String[] descriptions) { + public Circuit(String uid, boolean requiresDiscovery) { this.uid = uid; this.requiresDiscovery = requiresDiscovery; - this.name = name; - this.descriptions = descriptions; ChipsetManager.circuitRegistry.registerCircuit(this); } @@ -54,14 +50,23 @@ public abstract class Circuit implements ICircuit { @Override public String getName() { - return "circuit." + this.name; + return "circuit." + this.uid; } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void addTooltip(List list) { - for (String description : descriptions) - list.add(" - " + StringUtil.localize(description)); + list.add(StringUtil.localize(getName())); + + int i = 1; + while (true) { + String unlocalizedDescription = getName() + ".description." + i; + String description = StringUtil.localize(unlocalizedDescription); + if (description.endsWith(unlocalizedDescription)) + break; + list.add(" - " + description); + i++; + } } public static ICircuit energyElectricChoke1; diff --git a/src/main/java/forestry/core/config/Config.java b/src/main/java/forestry/core/config/Config.java index a063fe370..fa37af2aa 100755 --- a/src/main/java/forestry/core/config/Config.java +++ b/src/main/java/forestry/core/config/Config.java @@ -104,9 +104,6 @@ public class Config { // Mail public static boolean mailAlertEnabled = true; - public static String fakeUserLogin = "[Forestry]"; - public static boolean fakeUserAutoop = true; - // Hints public static boolean disableHints = false; public static HashMap hints = new HashMap(); @@ -254,14 +251,6 @@ public class Config { for (String str : disabledStructures) Proxies.log.finer("Disabled structure '%s'.", str); - property = config.get("permissions.login", CATEGORY_COMMON, "[Forestry]"); - property.Comment = "set the default login used by Forestry."; - Config.fakeUserLogin = property.Value; - - property = config.get("permissions.autoop", CATEGORY_COMMON, true); - property.Comment = "set to false to prevent Forestry's user from autooping."; - Config.fakeUserAutoop = Boolean.parseBoolean(property.Value); - registerClimates(); ForestryTrigger.initialize(); diff --git a/src/main/java/forestry/core/fluids/FluidHelper.java b/src/main/java/forestry/core/fluids/FluidHelper.java new file mode 100644 index 000000000..15a01d0ad --- /dev/null +++ b/src/main/java/forestry/core/fluids/FluidHelper.java @@ -0,0 +1,286 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.fluids; + +import forestry.core.fluids.tanks.StandardTank; +import forestry.core.inventory.InvTools; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraft.block.Block; +import net.minecraft.block.BlockLiquid; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.world.World; +import net.minecraftforge.fluids.*; +import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData; + +/** + * + * @author CovertJaguar + */ +public final class FluidHelper { + + public static final int BUCKET_FILL_TIME = 8; + public static final int NETWORK_UPDATE_INTERVAL = 128; + public static final int BUCKET_VOLUME = 1000; + + private FluidHelper() { + } + + public static boolean handleRightClick(IFluidHandler tank, ForgeDirection side, EntityPlayer player, boolean fill, boolean drain) { + if (player == null) + return false; + ItemStack current = player.inventory.getCurrentItem(); + if (current != null) { + + FluidStack liquid = getFluidStackInContainer(current); + + if (fill && liquid != null) { + int used = tank.fill(side, liquid, true); + + if (used > 0) { + if (!player.capabilities.isCreativeMode) { + player.inventory.setInventorySlotContents(player.inventory.currentItem, InvTools.depleteItem(current)); + player.inventory.markDirty(); + } + return true; + } + + } else if (drain) { + + FluidStack available = tank.drain(side, Integer.MAX_VALUE, false); + if (available != null) { + ItemStack filled = fillContainer(available, current); + + liquid = getFluidStackInContainer(filled); + if (liquid != null) { + + if (current.stackSize > 1) { + if (!player.inventory.addItemStackToInventory(filled)) + return false; + player.inventory.setInventorySlotContents(player.inventory.currentItem, InvTools.depleteItem(current)); + player.inventory.markDirty(); + } else { + player.inventory.setInventorySlotContents(player.inventory.currentItem, InvTools.depleteItem(current)); + player.inventory.setInventorySlotContents(player.inventory.currentItem, filled); + player.inventory.markDirty(); + } + + tank.drain(side, liquid.amount, true); + return true; + } + } + } + } + return false; + } + + public static void processContainers(StandardTank tank, IInventory inv, int inputSlot, int outputSlot) { + processContainers(tank, inv, inputSlot, outputSlot, tank.getFluidType(), true, true); + } + + public static void processContainers(StandardTank tank, IInventory inv, int inputSlot, int outputSlot, Fluid fluidToFill, boolean processFilled, boolean processEmpty) { + TankManager tankManger = new TankManager(); + tankManger.add(tank); + processContainers(tankManger, inv, inputSlot, outputSlot, fluidToFill, processFilled, processEmpty); + } + + public static void processContainers(TankManager tank, IInventory inv, int inputSlot, int outputSlot, Fluid fluidToFill) { + processContainers(tank, inv, inputSlot, outputSlot, fluidToFill, true, true); + } + + public static void processContainers(IFluidHandler fluidHandler, IInventory inv, int inputSlot, int outputSlot, Fluid fluidToFill, boolean processFilled, boolean processEmpty) { + ItemStack input = inv.getStackInSlot(inputSlot); + + if (input == null) + return; + + if (processFilled && drainContainers(fluidHandler, inv, inputSlot, outputSlot)) + return; + + if (processEmpty && fluidToFill != null) + fillContainers(fluidHandler, inv, inputSlot, outputSlot, fluidToFill); + } + + public static boolean fillContainers(IFluidHandler fluidHandler, IInventory inv, int inputSlot, int outputSlot, Fluid fluidToFill) { + ItemStack input = inv.getStackInSlot(inputSlot); + ItemStack output = inv.getStackInSlot(outputSlot); + ItemStack filled = getFilledContainer(fluidToFill, input); + if (filled != null && (output == null || (output.stackSize < output.getMaxStackSize() && InvTools.isItemEqual(filled, output)))) { + FluidStack fluidInContainer = getFluidStackInContainer(filled); + FluidStack drain = fluidHandler.drain(ForgeDirection.UNKNOWN, fluidInContainer, false); + if (drain != null && drain.amount == fluidInContainer.amount) { + fluidHandler.drain(ForgeDirection.UNKNOWN, fluidInContainer, true); + if (output == null) + inv.setInventorySlotContents(outputSlot, filled); + else + output.stackSize++; + inv.decrStackSize(inputSlot, 1); + return true; + } + } + return false; + } + + public static boolean drainContainers(IFluidHandler fluidHandler, IInventory inv, int inputSlot, int outputSlot) { + ItemStack input = inv.getStackInSlot(inputSlot); + ItemStack output = inv.getStackInSlot(outputSlot); + + if (input != null) { + FluidStack fluidInContainer = getFluidStackInContainer(input); + ItemStack emptyItem = input.getItem().getContainerItem(input); + if (fluidInContainer != null && (emptyItem == null || output == null || (output.stackSize < output.getMaxStackSize() && InvTools.isItemEqual(output, emptyItem)))) { + int used = fluidHandler.fill(ForgeDirection.UNKNOWN, fluidInContainer, false); + if (used >= fluidInContainer.amount) { + fluidHandler.fill(ForgeDirection.UNKNOWN, fluidInContainer, true); + if (emptyItem != null) + if (output == null) + inv.setInventorySlotContents(outputSlot, emptyItem); + else + output.stackSize++; + inv.decrStackSize(inputSlot, 1); + return true; + } + } + } + return false; + } + + public static boolean isBucket(ItemStack stack) { + return FluidContainerRegistry.isBucket(stack); + } + + public static boolean isContainer(ItemStack stack) { + if (stack != null && stack.getItem() instanceof IFluidContainerItem) + return true; + return FluidContainerRegistry.isContainer(stack); + } + + public static boolean isFilledContainer(ItemStack stack) { + return FluidContainerRegistry.isFilledContainer(stack); + } + + public static boolean isEmptyContainer(ItemStack stack) { + return FluidContainerRegistry.isEmptyContainer(stack); + } + + public static ItemStack getFilledContainer(Fluid fluid, ItemStack empty) { + if (fluid == null || empty == null) return null; + return FluidContainerRegistry.fillFluidContainer(new FluidStack(fluid, Integer.MAX_VALUE), empty); + } + + public static ItemStack getFilledContainer(FluidStack fluid, ItemStack empty) { + if (fluid == null || empty == null) return null; + fluid = fluid.copy(); + fluid.amount = Integer.MAX_VALUE; + return FluidContainerRegistry.fillFluidContainer(fluid, empty); + } + + public static ItemStack fillContainer(FluidStack liquid, ItemStack empty) { + if (liquid == null || empty == null) return null; + return FluidContainerRegistry.fillFluidContainer(liquid, empty); + } + + public static FluidStack getFluidStackInContainer(ItemStack stack) { + return FluidContainerRegistry.getFluidForFilledItem(stack); + } + + public static Fluid getFluidInContianer(ItemStack stack) { + FluidStack fluidStack = FluidContainerRegistry.getFluidForFilledItem(stack); + return fluidStack != null ? fluidStack.getFluid() : null; + } + + public static boolean containsFluidStack(ItemStack stack, FluidStack fluidStack) { + return FluidContainerRegistry.containsFluid(stack, fluidStack); + } + + public static boolean containsFluid(ItemStack stack, Fluid fluid) { + return FluidContainerRegistry.containsFluid(stack, new FluidStack(fluid, 1)); + } + + public static boolean isFluidEqual(FluidStack L1, FluidStack L2) { + if (L1 == null || L2 == null) + return false; + return L1.isFluidEqual(L2); + } + + public static Collection getContainersFilledWith(FluidStack fluidStack) { + List containers = new ArrayList(); + for (FluidContainerData data : FluidContainerRegistry.getRegisteredFluidContainerData()) { + FluidStack inContainer = getFluidStackInContainer(data.filledContainer); + if (inContainer != null && inContainer.containsFluid(fluidStack)) + containers.add(data.filledContainer.copy()); + } + return containers; + } + + public static void nerfWaterBottle() { + for (FluidContainerData data : FluidContainerRegistry.getRegisteredFluidContainerData()) { + if (data.filledContainer.getItem() == Items.potionitem && data.emptyContainer.getItem() == Items.glass_bottle && Fluids.WATER.is(data.fluid)) { + data.fluid.amount = 333; + return; + } + } + } + + public static FluidStack drainBlock(World world, int x, int y, int z, boolean doDrain) { + return drainBlock(world.getBlock(x, y, z), world, x, y, z, doDrain); + } + + public static FluidStack drainBlock(Block block, World world, int x, int y, int z, boolean doDrain) { + if (block instanceof IFluidBlock) { + IFluidBlock fluidBlock = (IFluidBlock)block; + if (fluidBlock.canDrain(world, x, y, z)) + return fluidBlock.drain(world, x, y, z, doDrain); + } else if (block == Blocks.water || block == Blocks.flowing_water) { + int meta = world.getBlockMetadata(x, y, z); + if (meta != 0) + return null; + if (doDrain) + world.setBlockToAir(x, y, z); + return new FluidStack(FluidRegistry.WATER, FluidContainerRegistry.BUCKET_VOLUME); + } else if (block == Blocks.lava || block == Blocks.flowing_lava) { + int meta = world.getBlockMetadata(x, y, z); + if (meta != 0) + return null; + if (doDrain) + world.setBlockToAir(x, y, z); + return new FluidStack(FluidRegistry.LAVA, FluidContainerRegistry.BUCKET_VOLUME); + } + return null; + } + + public static boolean isFullFluidBlock(World world, int x, int y, int z) { + return isFullFluidBlock(world.getBlock(x, y, z), world, x, y, z); + } + + public static boolean isFullFluidBlock(Block block, World world, int x, int y, int z) { + if (block instanceof BlockLiquid || block instanceof IFluidBlock) + return world.getBlockMetadata(x, y, z) == 0; + return false; + } + + public static Fluid getFluid(Block block) { + if (block instanceof IFluidBlock) + return ((IFluidBlock) block).getFluid(); + else if (block == Blocks.water || block == Blocks.flowing_water) + return FluidRegistry.WATER; + else if (block == Blocks.lava || block == Blocks.flowing_lava) + return FluidRegistry.LAVA; + return null; + } + +} diff --git a/src/main/java/forestry/core/fluids/Fluids.java b/src/main/java/forestry/core/fluids/Fluids.java new file mode 100644 index 000000000..6599a48ff --- /dev/null +++ b/src/main/java/forestry/core/fluids/Fluids.java @@ -0,0 +1,79 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.fluids; + +import java.util.Locale; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidContainerRegistry; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; + +/** + * + * @author CovertJaguar + */ +public enum Fluids { + + WATER, LAVA, FUEL, BIOFUEL, CREOSOTE, STEAM, BIOETHANOL, COAL, PYROTHEUM; + private final String tag; + + private Fluids() { + tag = name().toLowerCase(Locale.ENGLISH); + } + + public String getTag() { + return tag; + } + + public Fluid get() { + return FluidRegistry.getFluid(tag); + } + + /** + * Gets a FluidStack filled with qty milliBuckets worth of Fluid. + * + * @param qty + * @return + */ + public FluidStack get(int qty) { + return FluidRegistry.getFluidStack(tag, qty); + } + + /** + * Gets a FluidStack filled with n buckets worth of Fluid. + * + * @param n + * @return + */ + public FluidStack getB(int n) { + return FluidRegistry.getFluidStack(tag, n * FluidContainerRegistry.BUCKET_VOLUME); + } + + public boolean is(Fluid fluid) { + return get() == fluid; + } + + public boolean is(FluidStack fluidStack) { + return fluidStack != null && get() == fluidStack.getFluid(); + } + + public boolean isContained(ItemStack containerStack) { + return containerStack != null && FluidHelper.containsFluid(containerStack, get()); + } + + public static boolean areEqual(Fluid fluid, FluidStack fluidStack) { + if (fluidStack != null && fluid == fluidStack.getFluid()) + return true; + return fluid == null && fluidStack == null; + } + +} diff --git a/src/main/java/forestry/core/fluids/TankManager.java b/src/main/java/forestry/core/fluids/TankManager.java new file mode 100644 index 000000000..11fea5a57 --- /dev/null +++ b/src/main/java/forestry/core/fluids/TankManager.java @@ -0,0 +1,371 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.fluids; + +import com.google.common.collect.ForwardingList; +import forestry.core.fluids.tanks.FakeTank; +import forestry.core.fluids.tanks.StandardTank; +import forestry.core.inventory.ITileFilter; +import forestry.core.network.PacketGuiInteger; +import forestry.core.proxy.Proxies; +import forestry.core.utils.NBTUtil; +import forestry.core.utils.NBTUtil.NBTList; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.ICrafting; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; +import net.minecraftforge.fluids.IFluidHandler; +import net.minecraftforge.fluids.IFluidTank; + +/** + * + * @author CovertJaguar + */ +public class TankManager extends ForwardingList implements IFluidHandler, List { + + public static final ITileFilter TANK_FILTER = new ITileFilter() { + @Override + public boolean matches(TileEntity tile) { + return tile instanceof IFluidHandler; + } + + }; + private static final byte NETWORK_DATA = 3; + private final List tanks = new ArrayList(); + private final List prevFluidStacks = new ArrayList(); + private final List prevColor = new ArrayList(); + + public TankManager() { + } + + public TankManager(StandardTank... tanks) { + addAll(Arrays.asList(tanks)); + } + + @Override + protected List delegate() { + return tanks; + } + + @Override + public boolean addAll(Collection collection) { + boolean changed = false; + for (StandardTank tank : collection) + changed |= add(tank); + + return changed; + } + + @Override + public boolean add(StandardTank tank) { + boolean added = tanks.add(tank); + int index = tanks.indexOf(tank); + tank.setTankIndex(index); + prevFluidStacks.add(tank.getFluid() == null ? null : tank.getFluid().copy()); + prevColor.add(tank.getColor()); + return added; + } + + public int maxMessageId() { + return NETWORK_DATA * tanks.size(); + } + + public void writeTanksToNBT(NBTTagCompound data) { + NBTTagList tagList = new NBTTagList(); + for (byte slot = 0; slot < tanks.size(); slot++) { + StandardTank tank = tanks.get(slot); + if (tank.getFluid() != null) { + NBTTagCompound tag = new NBTTagCompound(); + tag.setByte("tank", slot); + tank.writeToNBT(tag); + tagList.appendTag(tag); + } + } + data.setTag("tanks", tagList); + } + + public void readTanksFromNBT(NBTTagCompound data) { + NBTList tagList = NBTUtil.getNBTList(data, "tanks", NBTUtil.EnumNBTType.COMPOUND); + for (NBTTagCompound tag : tagList) { + int slot = tag.getByte("tank"); + if (slot >= 0 && slot < tanks.size()) + tanks.get(slot).readFromNBT(tag); + } + } + + public void writePacketData(DataOutputStream data) throws IOException { + for (int i = 0; i < tanks.size(); i++) + writePacketData(data, i); + } + + public void writePacketData(DataOutputStream data, int tankIndex) throws IOException { + if (tankIndex >= tanks.size()) + return; + StandardTank tank = tanks.get(tankIndex); + FluidStack fluidStack = tank.getFluid(); + if (fluidStack != null) { + data.writeShort(fluidStack.fluidID); + data.writeInt(fluidStack.amount); + data.writeInt(fluidStack.getFluid().getColor(fluidStack)); + } else + data.writeShort(-1); + } + + public void readPacketData(DataInputStream data) throws IOException { + for (int i = 0; i < tanks.size(); i++) + readPacketData(data, i); + } + + public void readPacketData(DataInputStream data, int tankIndex) throws IOException { + if (tankIndex >= tanks.size()) + return; + StandardTank tank = tanks.get(tankIndex); + int fluidId = data.readShort(); + if (fluidId != -1) { + tank.setFluid(new FluidStack(fluidId, data.readInt())); + tank.colorCache = data.readInt(); + } else + tank.setFluid(null); + } + + public void initGuiData(Container container, ICrafting player) { + for (StandardTank tank : tanks) + initGuiData(container, player, tank.getTankIndex()); + } + + public void initGuiData(Container container, ICrafting player, int tankIndex) { + if (tankIndex >= tanks.size()) + return; + FluidStack fluidStack = tanks.get(tankIndex).getFluid(); + int fluidId = -1; + int fluidAmount = 0; + if (fluidStack != null && fluidStack.amount > 0) { + fluidId = fluidStack.getFluid().getID(); + fluidAmount = fluidStack.amount; + } + + player.sendProgressBarUpdate(container, tankIndex * NETWORK_DATA + 0, fluidId); + PacketGuiInteger packet = new PacketGuiInteger(container.windowId, tankIndex * NETWORK_DATA + 1, fluidAmount); + Proxies.net.sendToPlayer(packet, (EntityPlayerMP)player); + } + + public void updateGuiData(Container container, List crafters) { + for (StandardTank tank : tanks) + updateGuiData(container, crafters, tank.getTankIndex()); + } + + public void updateGuiData(Container container, List crafters, int tankIndex) { + StandardTank tank = tanks.get(tankIndex); + FluidStack fluidStack = tank.getFluid(); + FluidStack prev = prevFluidStacks.get(tankIndex); + int color = tank.getColor(); + int pColor = prevColor.get(tankIndex); + + for (Object crafter1 : crafters) { + ICrafting crafter = (ICrafting) crafter1; + EntityPlayerMP player = (EntityPlayerMP) crafter1; + if (fluidStack == null ^ prev == null) { + int fluidId = -1; + int fluidAmount = 0; + if (fluidStack != null) { + fluidId = fluidStack.fluidID; + fluidAmount = fluidStack.amount; + } + crafter.sendProgressBarUpdate(container, tankIndex * NETWORK_DATA + 0, fluidId); + PacketGuiInteger packet = new PacketGuiInteger(container.windowId, tankIndex * NETWORK_DATA + 1, fluidAmount); + Proxies.net.sendToPlayer(packet, player); + } else if (fluidStack != null && prev != null) { + if (fluidStack.getFluid() != prev.getFluid()) + crafter.sendProgressBarUpdate(container, tankIndex * NETWORK_DATA + 0, fluidStack.fluidID); + if (fluidStack.amount != prev.amount) { + PacketGuiInteger packet = new PacketGuiInteger(container.windowId, tankIndex * NETWORK_DATA + 1, fluidStack.amount); + Proxies.net.sendToPlayer(packet, player); + } + if (color != pColor) { + PacketGuiInteger packet = new PacketGuiInteger(container.windowId, tankIndex * NETWORK_DATA + 2, color); + Proxies.net.sendToPlayer(packet, player); + } + } + } + + prevFluidStacks.set(tankIndex, tank.getFluid() == null ? null : tank.getFluid().copy()); + prevColor.set(tankIndex, color); + } + + public void processGuiUpdate(int messageId, int data) { + int tankIndex = messageId / NETWORK_DATA; + + if (tankIndex >= tanks.size()) + return; + StandardTank tank = tanks.get(tankIndex); + FluidStack fluidStack = tank.getFluid(); + if (fluidStack == null) { + fluidStack = new FluidStack(-1, 0); + tank.setFluid(fluidStack); + } + int fluidId = fluidStack.fluidID; + int amount = fluidStack.amount; + int color = tank.colorCache; + boolean newLiquid = false; + switch (messageId % NETWORK_DATA) { + case 0: + fluidId = data; + newLiquid = true; + break; + case 1: + amount = data; + break; + case 2: + color = data; + break; + } + if (newLiquid) { + fluidStack = new FluidStack(fluidId, 0); + tank.setFluid(fluidStack); + } + fluidStack.amount = amount; + tank.colorCache = color; + } + + @Override + public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + for (StandardTank tank : tanks) + if (tankAcceptsFluid(tank, resource)) + return fill(tank.getTankIndex(), resource, doFill); + + return FakeTank.INSTANCE.fill(resource, doFill); + } + + public int fill(int tankIndex, FluidStack resource, boolean doFill) { + if (tankIndex < 0 || tankIndex >= tanks.size() || resource == null) + return 0; + + StandardTank tank = tanks.get(tankIndex); + if (!tank.canBeFilledExternally()) + return 0; + + return tank.fill(resource, doFill); + } + + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + for (StandardTank tank : tanks) + if (tankCanDrain(tank)) + return drain(tank.getTankIndex(), maxDrain, doDrain); + return FakeTank.INSTANCE.drain(maxDrain, doDrain); + } + + public FluidStack drain(int tankIndex, int maxDrain, boolean doDrain) { + if (tankIndex < 0 || tankIndex >= tanks.size()) + return null; + + StandardTank tank = tanks.get(tankIndex); + if (!tank.canBeDrainedExternally()) + return null; + + return tank.drain(maxDrain, doDrain); + } + + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + for (StandardTank tank : tanks) + if (tankCanDrainFluid(tank, resource)) + return tank.drain(resource.amount, doDrain); + return null; + } + + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return true; + } + + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return true; + } + + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection direction) { + FluidTankInfo[] info = new FluidTankInfo[size()]; + for (int i = 0; i < size(); i++) + info[i] = get(i).getInfo(); + return info; + } + + public FluidTankInfo[] getTankInfo() { + return getTankInfo(ForgeDirection.UNKNOWN); + } + + public FluidTankInfo getTankInfo(int tankIndex) { + return get(tankIndex).getInfo(); + } + + public FluidStack getFluid(int tankIndex) { + return get(tankIndex).getFluid(); + } + + @Override + public StandardTank get(int tankIndex) { + return tanks.get(tankIndex); + } + + public void setCapacity(int tankIndex, int capacity) { + StandardTank tank = get(tankIndex); + tank.setCapacity(capacity); + FluidStack fluidStack = tank.getFluid(); + if (fluidStack != null && fluidStack.amount > capacity) + fluidStack.amount = capacity; + } + + public static IFluidHandler getTankFromTile(TileEntity tile) { + IFluidHandler tank = null; + if (tile instanceof IFluidHandler) + tank = (IFluidHandler) tile; + return tank; + } + + private boolean tankAcceptsFluid(StandardTank tank, FluidStack fluidStack) { + if (fluidStack == null) + return false; + if (!tank.canBeFilledExternally()) + return false; + if (tank.fill(fluidStack, false) > 0) + return true; + return false; + } + + private boolean tankCanDrain(StandardTank tank) { + if (!tank.canBeDrainedExternally()) + return false; + FluidStack drained = tank.drain(1, false); + if (drained != null && drained.amount > 0) + return true; + return false; + } + + private boolean tankCanDrainFluid(StandardTank tank, FluidStack fluidStack) { + return fluidStack != null && tankCanDrain(tank); + } + +} diff --git a/src/main/java/forestry/core/fluids/tanks/FakeTank.java b/src/main/java/forestry/core/fluids/tanks/FakeTank.java new file mode 100644 index 000000000..34086cc1e --- /dev/null +++ b/src/main/java/forestry/core/fluids/tanks/FakeTank.java @@ -0,0 +1,40 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.fluids.tanks; + +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; + +/** + * + * @author CovertJaguar + */ +public final class FakeTank extends StandardTank { + + public static final FakeTank INSTANCE = new FakeTank(); + public static final FakeTank[] ARRAY = new FakeTank[]{INSTANCE}; + public static final FluidTankInfo[] INFO = new FluidTankInfo[]{INSTANCE.getInfo()}; + + private FakeTank() { + super(1); + } + + @Override + public int fill(FluidStack resource, boolean doFill) { + return 0; + } + + @Override + public FluidStack drain(int maxDrain, boolean doDrain) { + return null; + } + +} diff --git a/src/main/java/forestry/core/fluids/tanks/FilteredTank.java b/src/main/java/forestry/core/fluids/tanks/FilteredTank.java new file mode 100644 index 000000000..59e973a4d --- /dev/null +++ b/src/main/java/forestry/core/fluids/tanks/FilteredTank.java @@ -0,0 +1,91 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.fluids.tanks; + +import forestry.core.gui.tooltips.ToolTipLine; +import net.minecraft.item.EnumRarity; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; + +/** + * + * @author CovertJaguar + */ +public class FilteredTank extends StandardTank { + + private HashSet filters; + + public FilteredTank(int capacity, Fluid... filters) { + this(capacity, Arrays.asList(filters), null); + } + + public FilteredTank(int capacity, Collection filters) { + this(capacity, filters, null); + } + + public FilteredTank(int capacity, Collection filters, TileEntity tile) { + super(capacity, tile); + this.filters = new HashSet(filters); + } + + public void addFilter(Fluid filter) { + if (!accepts(filter)) + filters.add(filter); + } + + @Override + public int fill(FluidStack resource, boolean doFill) { + if (liquidMatchesFilter(resource)) + return super.fill(resource, doFill); + return 0; + } + + @Override + public boolean accepts(Fluid fluid) { + return filters.contains(fluid); + } + + public boolean liquidMatchesFilter(FluidStack resource) { + if (resource == null || filters == null) + return false; + return filters.contains(resource.getFluid()); + } + + @Override + protected void refreshTooltip() { + if (hasFluid()) { + super.refreshTooltip(); + return; + } + + toolTip.clear(); + int amount = 0; + for (Fluid filter : filters) { + EnumRarity rarity = filter.getRarity(); + if (rarity == null) + rarity = EnumRarity.common; + FluidStack filterFluidStack = FluidRegistry.getFluidStack(filter.getName(), 0); + ToolTipLine name = new ToolTipLine(filter.getLocalizedName(filterFluidStack), rarity.rarityColor); + name.setSpacing(2); + toolTip.add(name); + if (getFluid() != null) + amount = getFluid().amount; + } + + toolTip.add(new ToolTipLine(String.format("%,d", amount) + " / " + String.format("%,d", getCapacity()))); + } + +} diff --git a/src/main/java/forestry/core/fluids/tanks/StandardTank.java b/src/main/java/forestry/core/fluids/tanks/StandardTank.java new file mode 100644 index 000000000..c8f250199 --- /dev/null +++ b/src/main/java/forestry/core/fluids/tanks/StandardTank.java @@ -0,0 +1,172 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.fluids.tanks; + +import forestry.core.gui.tooltips.ToolTip; +import forestry.core.gui.tooltips.ToolTipLine; +import java.util.Locale; +import net.minecraft.item.EnumRarity; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTank; + +/** + * + * @author CovertJaguar + */ +public class StandardTank extends FluidTank { + + // defines how the tank responds to IFluidHandler requests + public enum TankMode { + DEFAULT, OUTPUT, INPUT, INTERNAL + } + + public TankMode tankMode = TankMode.DEFAULT; + public static final int DEFAULT_COLOR = 0xFFFFFF; + public int colorCache = DEFAULT_COLOR; + private int tankIndex; + + public StandardTank(int capacity) { + super(capacity); + } + + public StandardTank(FluidStack fluid, int capacity) { + this(capacity); + setFluid(fluid); + } + + public StandardTank(int capacity, TileEntity tile) { + this(capacity); + this.tile = tile; + } + + public StandardTank(FluidStack fluid, int capacity, TileEntity tile) { + this(capacity); + this.tile = tile; + setFluid(fluid); + } + + public void setTankIndex(int index) { + this.tankIndex = index; + } + + public int getTankIndex() { + return tankIndex; + } + + @Override + public void setFluid(FluidStack fluid) { + super.setFluid(fluid); + colorCache = StandardTank.DEFAULT_COLOR; + } + + public int getColor() { + Fluid f = getFluidType(); + if (f == null) + return DEFAULT_COLOR; + return f.getColor(getFluid()); + } + + public boolean isEmpty() { + return getFluid() == null || getFluid().amount <= 0; + } + + public boolean isFull() { + return getFluid() != null && getFluid().amount == getCapacity(); + } + + public int getRemainingSpace() { + return capacity - getFluidAmount(); + } + + public Fluid getFluidType() { + return getFluid() != null ? getFluid().getFluid() : null; + } + + @Override + public int fill(final FluidStack resource, final boolean doFill) { + if (resource == null) + return 0; + if (resource.amount <= 0) + return 0; + if (!accepts(resource.getFluid())) + return 0; + return super.fill(resource, doFill); + } + + public boolean accepts(Fluid fluid) { + return true; + } + + public boolean canBeFilledExternally() { + switch (tankMode) { + case DEFAULT: + case INPUT: + return true; + } + return false; + } + + public boolean canBeDrainedExternally() { + switch (tankMode) { + case DEFAULT: + case OUTPUT: + return true; + } + return false; + } + + @Override + public FluidStack drain(int maxDrain, boolean doDrain) { + if (maxDrain <= 0) + return null; + return super.drain(maxDrain, doDrain); + } + + @Override + public String toString() { + return String.format("Tank: %s, %d/%d", fluid != null && fluid.getFluid() != null ? fluid.getFluid().getName() : "Empty", getFluidAmount(), getCapacity()); + } + + public ToolTip getToolTip() { + return toolTip; + } + + protected boolean hasFluid() { + FluidStack fluid = getFluid(); + return fluid != null && fluid.amount > 0 && fluid.getFluid() != null; + } + + protected void refreshTooltip() { + toolTip.clear(); + int amount = 0; + if (hasFluid()) { + Fluid fluidType = getFluidType(); + EnumRarity rarity = fluidType.getRarity(); + if (rarity == null) + rarity = EnumRarity.common; + ToolTipLine fluidName = new ToolTipLine(fluidType.getLocalizedName(getFluid()), rarity.rarityColor); + fluidName.setSpacing(2); + toolTip.add(fluidName); + amount = getFluid().amount; + } + toolTip.add(new ToolTipLine(String.format(Locale.ENGLISH, "%,d / %,d", amount, getCapacity()))); + } + + protected final ToolTip toolTip = new ToolTip() { + @Override + public void refresh() { + refreshTooltip(); + } + + }; +} diff --git a/src/main/java/forestry/core/gadgets/BlockBase.java b/src/main/java/forestry/core/gadgets/BlockBase.java index 3ec79d988..dfc1dcd99 100755 --- a/src/main/java/forestry/core/gadgets/BlockBase.java +++ b/src/main/java/forestry/core/gadgets/BlockBase.java @@ -242,7 +242,7 @@ public class BlockBase extends BlockForestry { @Override public IIcon getIcon(int side, int metadata) { if (metadata >= definitions.size() || definitions.get(metadata) == null) - metadata = 0; + return null; return definitions.get(metadata).getBlockTextureFromSideAndMetadata(side, metadata); } diff --git a/src/main/java/forestry/core/gadgets/BlockResource.java b/src/main/java/forestry/core/gadgets/BlockResource.java index ef3897802..66fd7b3ff 100755 --- a/src/main/java/forestry/core/gadgets/BlockResource.java +++ b/src/main/java/forestry/core/gadgets/BlockResource.java @@ -101,8 +101,10 @@ public class BlockResource extends Block { return iconApatite; else if (j == 1) return iconCopper; - else + else if (j == 2) return iconTin; + else + return null; } } diff --git a/src/main/java/forestry/core/gadgets/BlockSoil.java b/src/main/java/forestry/core/gadgets/BlockSoil.java index 3eecb210f..e7cf3721e 100755 --- a/src/main/java/forestry/core/gadgets/BlockSoil.java +++ b/src/main/java/forestry/core/gadgets/BlockSoil.java @@ -14,6 +14,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Random; +import forestry.core.IItemTyped; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; @@ -45,9 +46,13 @@ import forestry.core.render.TextureManager; * @author * */ -public class BlockSoil extends Block { +public class BlockSoil extends Block implements IItemTyped { - private final int degradeDelimiter = 3; + public enum SoilType { + HUMUS, BOG_EARTH, PEAT; + } + + private static final int degradeDelimiter = 3; public BlockSoil() { super(Material.sand); @@ -66,16 +71,15 @@ public class BlockSoil extends Block { public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { ArrayList ret = new ArrayList(); - int type = (metadata & 0x03); - int maturity = metadata >> 2; + SoilType type = getTypeFromMeta(metadata); - if (maturity >= this.degradeDelimiter && type == 1) { + if (type == SoilType.PEAT) { ret.add(ForestryItem.peat.getItemStack()); ret.add(new ItemStack(Blocks.dirt)); - } else if (type == 0) + } else if (type == SoilType.HUMUS) ret.add(new ItemStack(Blocks.dirt)); else - ret.add(new ItemStack(this, 1, type)); + ret.add(new ItemStack(this, 1, SoilType.BOG_EARTH.ordinal())); return ret; } @@ -91,14 +95,13 @@ public class BlockSoil extends Block { return; int meta = world.getBlockMetadata(i, j, k); - int type = (meta & 0x03); - if (type == 0) + SoilType type = getTypeFromMeta(meta); + + if (type == SoilType.HUMUS) updateTickHumus(world, i, j, k, random); - else if (type == 1) + else if (type == SoilType.BOG_EARTH) updateTickBogEarth(world, i, j, k, random); - else - Proxies.log.warning(this.getClass() + " with unknown type " + type + " encountered."); } private void updateTickHumus(World world, int i, int j, int k, Random random) { @@ -155,17 +158,17 @@ public class BlockSoil extends Block { int type = meta & 0x03; int grade = meta >> 2; - // Increment (de)gradation - grade++; + // Increment (de)gradation + grade++; - // Repackage in format TTGG - meta = (grade << 2 | type); + // Repackage in format TTGG + meta = (grade << 2 | type); - if (grade >= this.degradeDelimiter) - world.setBlock(i, j, k, Blocks.sand, 0, Defaults.FLAG_BLOCK_SYNCH); - else - world.setBlockMetadataWithNotify(i, j, k, meta, Defaults.FLAG_BLOCK_SYNCH); - world.markBlockForUpdate(i, j, k); + if (grade >= this.degradeDelimiter) + world.setBlock(i, j, k, Blocks.sand, 0, Defaults.FLAG_BLOCK_SYNCH); + else + world.setBlockMetadataWithNotify(i, j, k, meta, Defaults.FLAG_BLOCK_SYNCH); + world.markBlockForUpdate(i, j, k); } public static boolean isMoistened(World world, int x, int y, int z) { @@ -192,15 +195,15 @@ public class BlockSoil extends Block { int type = meta & 0x03; int maturity = meta >> 2; - if (maturity >= this.degradeDelimiter) - return; + if (maturity >= this.degradeDelimiter) + return; - // Increment (de)gradation - maturity++; + // Increment (de)gradation + maturity++; - meta = (maturity << 2 | type); - world.setBlockMetadataWithNotify(i, j, k, meta, Defaults.FLAG_BLOCK_SYNCH); - world.markBlockForUpdate(i, j, k); + meta = (maturity << 2 | type); + world.setBlockMetadataWithNotify(i, j, k, meta, Defaults.FLAG_BLOCK_SYNCH); + world.markBlockForUpdate(i, j, k); } @Override @@ -210,8 +213,9 @@ public class BlockSoil extends Block { return false; int meta = world.getBlockMetadata(x, y, z); + SoilType type = getTypeFromMeta(meta); - return (meta & 0x03) == 0; + return type == SoilType.HUMUS; } @Override @@ -219,6 +223,19 @@ public class BlockSoil extends Block { return false; } + public SoilType getTypeFromMeta(int meta) { + int type = meta & 0x03; + int maturity = meta >> 2; + + if (type == 1) + if (maturity < degradeDelimiter) + return SoilType.BOG_EARTH; + else + return SoilType.PEAT; + else + return SoilType.HUMUS; + } + // / CREATIVE INVENTORY @SuppressWarnings({ "rawtypes", "unchecked" }) @Override @@ -245,19 +262,16 @@ public class BlockSoil extends Block { @Override @SideOnly(Side.CLIENT) - public IIcon getIcon(int i, int j) { + public IIcon getIcon(int side, int meta) { - int meta = j; - int type = meta & 0x03; - int maturity = meta >> 2; + SoilType type = getTypeFromMeta(meta); - if (type == 1) - if (maturity < this.degradeDelimiter) - return iconBogEarth; - else - return iconPeat; - else - return iconHumus; + switch (type) { + case HUMUS: return iconHumus; + case BOG_EARTH: return iconBogEarth; + case PEAT: return iconPeat; + } + return null; } } diff --git a/src/main/java/forestry/core/gadgets/Engine.java b/src/main/java/forestry/core/gadgets/Engine.java index 23a013a7c..d754cded7 100755 --- a/src/main/java/forestry/core/gadgets/Engine.java +++ b/src/main/java/forestry/core/gadgets/Engine.java @@ -19,7 +19,6 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData; import buildcraft.api.core.Position; import buildcraft.api.power.IPowerEmitter; @@ -35,7 +34,6 @@ import forestry.core.interfaces.IPowerHandler; import forestry.core.network.PacketPayload; import forestry.core.proxy.Proxies; import forestry.core.utils.BlockUtil; -import forestry.core.utils.ForestryTank; import forestry.plugins.PluginBuildCraft; public abstract class Engine extends TileBase implements IPowerHandler, IPipeConnection, IPowerEmitter { @@ -52,7 +50,6 @@ public abstract class Engine extends TileBase implements IPowerHandler, IPipeCon payload.intPayload[2] = heat; payload.floatPayload[0] = pistonSpeedServer; - return payload; } @@ -96,20 +93,7 @@ public abstract class Engine extends TileBase implements IPowerHandler, IPipeCon powerProvider.configure(10, 200, 10, 100000); } - protected ItemStack replenishByContainer(ItemStack inventoryStack, FluidContainerData container, ForestryTank tank) { - if (container == null) - return inventoryStack; - if (tank.fill(container.fluid, false) >= container.fluid.amount) { - tank.fill(container.fluid, true); - if (container.filledContainer != null && container.filledContainer.getItem().hasContainerItem(container.filledContainer)) - inventoryStack = container.emptyContainer.copy(); - else - inventoryStack.stackSize--; - } - - return inventoryStack; - } @Override public void rotateAfterPlacement(World world, int x, int y, int z, EntityLivingBase entityliving, ItemStack itemstack) { diff --git a/src/main/java/forestry/core/gadgets/TileAnalyzer.java b/src/main/java/forestry/core/gadgets/TileAnalyzer.java index 514e82d40..ad9a7066b 100755 --- a/src/main/java/forestry/core/gadgets/TileAnalyzer.java +++ b/src/main/java/forestry/core/gadgets/TileAnalyzer.java @@ -22,15 +22,18 @@ import net.minecraft.nbt.NBTTagList; import net.minecraft.network.Packet; import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; import forestry.api.core.ForestryAPI; import forestry.api.core.ISpecialInventory; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IIndividual; import forestry.core.EnumErrorCode; +import forestry.core.fluids.TankManager; import forestry.core.config.Defaults; import forestry.core.interfaces.ILiquidTankContainer; import forestry.core.network.EntityNetData; @@ -38,11 +41,10 @@ import forestry.core.network.GuiId; import forestry.core.network.PacketIds; import forestry.core.network.PacketInventoryStack; import forestry.core.proxy.Proxies; -import forestry.core.utils.ForestryTank; +import forestry.core.fluids.tanks.FilteredTank; import forestry.core.utils.InventoryAdapter; import forestry.core.utils.LiquidHelper; import forestry.core.utils.StackUtils; -import forestry.core.utils.StringUtil; public class TileAnalyzer extends TileBase implements ISpecialInventory, ISidedInventory, ILiquidTankContainer { @@ -65,18 +67,22 @@ public class TileAnalyzer extends TileBase implements ISpecialInventory, ISidedI private final short inputSlot1 = 2; private final short outputSlot1 = 8; - public FluidStack resource = FluidRegistry.getFluidStack(Defaults.LIQUID_HONEY, HONEY_REQUIRED); @EntityNetData - public ForestryTank resourceTank = new ForestryTank(Defaults.PROCESSOR_TANK_CAPACITY); + public FilteredTank resourceTank; + + private final TankManager tankManager; + private final Stack pendingProducts = new Stack(); /* CONSTRUCTOR */ public TileAnalyzer() { + resourceTank = new FilteredTank(Defaults.PROCESSOR_TANK_CAPACITY, FluidRegistry.getFluid(Defaults.LIQUID_HONEY)); + tankManager = new TankManager(resourceTank); } @Override public String getInventoryName() { - return StringUtil.localize("core.0"); + return getUnlocalizedName(); } /* GUI */ @@ -92,8 +98,7 @@ public class TileAnalyzer extends TileBase implements ISpecialInventory, ISidedI nbttagcompound.setInteger("AnalyzeTime", analyzeTime); - // / Resource tank - resourceTank.writeToNBT(nbttagcompound); + tankManager.writeTanksToNBT(nbttagcompound); // / Pending Products NBTTagList nbttaglist = new NBTTagList(); @@ -117,8 +122,7 @@ public class TileAnalyzer extends TileBase implements ISpecialInventory, ISidedI analyzeTime = nbttagcompound.getInteger("AnalyzeTime"); - // / Resource tank - resourceTank.readFromNBT(nbttagcompound); + tankManager.readTanksFromNBT(nbttagcompound); // / Pending Products NBTTagList nbttaglist = nbttagcompound.getTagList("PendingProducts", 10); @@ -146,7 +150,7 @@ public class TileAnalyzer extends TileBase implements ISpecialInventory, ISidedI // Check if we have suitable items waiting in the can slot if (getStackInSlot(canSlot) != null) { FluidContainerData container = LiquidHelper.getLiquidContainer(getStackInSlot(canSlot)); - if (container != null && resource.isFluidEqual(container.fluid)) { + if (container != null && resourceTank.accepts(container.fluid.getFluid())) { setInventorySlotContents(canSlot, StackUtils.replenishByContainer(this, getStackInSlot(canSlot), container, resourceTank)); if (getStackInSlot(canSlot).stackSize <= 0) @@ -187,7 +191,7 @@ public class TileAnalyzer extends TileBase implements ISpecialInventory, ISidedI return; // We need our liquid honey - if (resourceTank.getFluidAmount() < resource.amount) { + if (resourceTank.getFluidAmount() < HONEY_REQUIRED) { setErrorState(EnumErrorCode.NORESOURCE); return; } @@ -208,7 +212,7 @@ public class TileAnalyzer extends TileBase implements ISpecialInventory, ISidedI setInventorySlotContents(analyzeSlot, getStackInSlot(i)); setInventorySlotContents(i, null); - resourceTank.drain(resource.amount, true); + resourceTank.drain(HONEY_REQUIRED, true); analyzeTime = TIME_TO_ANALYZE; sendNetworkUpdate(); return; @@ -251,6 +255,7 @@ public class TileAnalyzer extends TileBase implements ISpecialInventory, ISidedI /* SMP */ public void getGUINetworkData(int i, int j) { + i -= tankManager.maxMessageId() + 1; switch (i) { case 0: analyzeTime = j; @@ -259,7 +264,8 @@ public class TileAnalyzer extends TileBase implements ISpecialInventory, ISidedI } public void sendGUINetworkData(Container container, ICrafting iCrafting) { - iCrafting.sendProgressBarUpdate(container, 0, analyzeTime); + int i = tankManager.maxMessageId() + 1; + iCrafting.sendProgressBarUpdate(container, i, analyzeTime); } @@ -388,7 +394,7 @@ public class TileAnalyzer extends TileBase implements ISpecialInventory, ISidedI if (!AlleleManager.alleleRegistry.isIndividual(stack)) { FluidContainerData container = LiquidHelper.getLiquidContainer(stack); - if (container == null || !container.fluid.isFluidEqual(resource)) + if (container == null || !resourceTank.accepts(container.fluid.getFluid())) return 0; if (getStackInSlot(canSlot) == null) { @@ -423,33 +429,39 @@ public class TileAnalyzer extends TileBase implements ISpecialInventory, ISidedI } /* ILIQUIDCONTAINER */ + @Override + public TankManager getTankManager() { + return tankManager; + } + @Override public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - - // We only accept what is already in the tank or valid ingredients - if (resourceTank.getFluidAmount() > 0 && !resourceTank.getFluid().isFluidEqual(resource)) - return 0; - else if (!LiquidHelper.isLiquid(Defaults.LIQUID_HONEY, resource)) - return 0; - - int used = resourceTank.fill(resource, doFill); - - if (doFill && used > 0) - sendNetworkUpdate(); - - return used; + return tankManager.fill(from, resource, doFill); } @Override - public ForestryTank[] getTanks() { - return new ForestryTank[] { resourceTank }; + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return tankManager.drain(from, resource, doDrain); } - /* @Override - public ILiquidTank getTank(ForgeDirection direction, LiquidStack type) { - return resourceTank; + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + return tankManager.drain(from, maxDrain, doDrain); + } + + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return tankManager.canFill(from, fluid); + } + + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return tankManager.canDrain(from, fluid); + } + + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return tankManager.getTankInfo(from); } - */ } diff --git a/src/main/java/forestry/core/gadgets/TileBase.java b/src/main/java/forestry/core/gadgets/TileBase.java index 2c169207a..142d83671 100755 --- a/src/main/java/forestry/core/gadgets/TileBase.java +++ b/src/main/java/forestry/core/gadgets/TileBase.java @@ -21,11 +21,6 @@ import forestry.core.utils.Utils; public abstract class TileBase extends TileForestry implements IHintSource { - @Override - public String getInventoryName() { - return null; - } - @Override public boolean isOwnable() { return true; diff --git a/src/main/java/forestry/core/gadgets/TileEscritoire.java b/src/main/java/forestry/core/gadgets/TileEscritoire.java index 735c59cd7..6fdde0480 100755 --- a/src/main/java/forestry/core/gadgets/TileEscritoire.java +++ b/src/main/java/forestry/core/gadgets/TileEscritoire.java @@ -47,7 +47,7 @@ public class TileEscritoire extends TileBase implements ISidedInventory, IRender private final InventoryAdapter inventory; @Override public String getInventoryName() { - return StringUtil.localize("core.1"); + return getUnlocalizedName(); } public TileEscritoire() { diff --git a/src/main/java/forestry/core/gadgets/TileForestry.java b/src/main/java/forestry/core/gadgets/TileForestry.java index 516e81316..38e2fcdc3 100755 --- a/src/main/java/forestry/core/gadgets/TileForestry.java +++ b/src/main/java/forestry/core/gadgets/TileForestry.java @@ -33,6 +33,7 @@ import com.mojang.authlib.GameProfile; import forestry.core.EnumErrorCode; import forestry.core.config.Config; import forestry.core.config.Defaults; +import forestry.core.fluids.tanks.FakeTank; import forestry.core.interfaces.IErrorSource; import forestry.core.interfaces.ILiquidTankContainer; import forestry.core.interfaces.IOwnable; @@ -43,7 +44,7 @@ import forestry.core.network.PacketPayload; import forestry.core.network.PacketTileUpdate; import forestry.core.proxy.Proxies; import forestry.core.utils.EnumAccess; -import forestry.core.utils.ForestryTank; +import forestry.core.fluids.tanks.StandardTank; import forestry.core.utils.InventoryAdapter; import forestry.core.utils.Vect; @@ -263,13 +264,6 @@ public abstract class TileForestry extends TileEntity implements INetworkedEntit return owner; } - public EntityPlayer getOwnerEntity() { - if (owner != null) - return worldObj.func_152378_a(owner.getId()); - else - return null; - } - @Override public void setOwner(EntityPlayer player) { this.owner = player.getGameProfile(); @@ -297,7 +291,14 @@ public abstract class TileForestry extends TileEntity implements INetworkedEntit } /* NAME */ - public abstract String getInventoryName(); + + /** + * Gets the tile's unlocalized name, based on the block at the location of this entity (client-only). + */ + public String getUnlocalizedName() { + String blockUnlocalizedName = getBlockType().getUnlocalizedName().replace("tile.for.",""); + return blockUnlocalizedName + "." + getBlockMetadata() + ".name"; + } public boolean hasCustomInventoryName() { return true; @@ -344,37 +345,4 @@ public abstract class TileForestry extends TileEntity implements INetworkedEntit return getInternalInventory().getSizeInventorySide(side); } - - /* IFLUIDHANDLER BASICS */ - public FluidTankInfo[] getTankInfo(ForgeDirection from) { - if (this instanceof ILiquidTankContainer) { - ForestryTank[] tanks = ((ILiquidTankContainer) this).getTanks(); - FluidTankInfo[] info = new FluidTankInfo[tanks.length]; - for (int i = 0; i < info.length; i++) { - info[i] = tanks[i].getInfo(); - } - return info; - } - return ForestryTank.DUMMY_TANKINFO_ARRAY; - } - - public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - return 0; - } - - public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { - return null; - } - - public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { - return resource != null ? drain(from, resource.amount, doDrain) : null; - } - - public boolean canFill(ForgeDirection from, Fluid fluid) { - return true; - } - - public boolean canDrain(ForgeDirection from, Fluid fluid) { - return true; - } } diff --git a/src/main/java/forestry/core/gadgets/TileMachine.java b/src/main/java/forestry/core/gadgets/TileMachine.java index 3b0fb6e24..2cb47a929 100755 --- a/src/main/java/forestry/core/gadgets/TileMachine.java +++ b/src/main/java/forestry/core/gadgets/TileMachine.java @@ -42,7 +42,7 @@ import forestry.plugins.PluginEnergy; import forestry.plugins.PluginFactory; import forestry.plugins.PluginMail; -public class TileMachine extends TileForestry implements ISpecialInventory, IClimatised, IHintSource { +public abstract class TileMachine extends TileForestry implements ISpecialInventory, IClimatised, IHintSource { public TileMachine() { } @@ -301,7 +301,7 @@ public class TileMachine extends TileForestry implements ISpecialInventory, ICli @Override public String getInventoryName() { - return "[Unknown]"; + return getUnlocalizedName(); } @Override diff --git a/src/main/java/forestry/core/gadgets/TileNaturalistChest.java b/src/main/java/forestry/core/gadgets/TileNaturalistChest.java index ab4b1fe25..152f0fa8c 100755 --- a/src/main/java/forestry/core/gadgets/TileNaturalistChest.java +++ b/src/main/java/forestry/core/gadgets/TileNaturalistChest.java @@ -37,7 +37,7 @@ public abstract class TileNaturalistChest extends TileBase implements IInventory @Override public String getInventoryName() { - return StringUtil.localize("tile.mill.3"); + return getUnlocalizedName(); } @Override diff --git a/src/main/java/forestry/core/gadgets/TilePowered.java b/src/main/java/forestry/core/gadgets/TilePowered.java index 999e3bfbe..3129fd1bf 100755 --- a/src/main/java/forestry/core/gadgets/TilePowered.java +++ b/src/main/java/forestry/core/gadgets/TilePowered.java @@ -29,7 +29,7 @@ import forestry.core.network.IndexInPayload; import forestry.core.network.PacketPayload; import forestry.core.proxy.Proxies; import forestry.core.utils.EnumTankLevel; -import forestry.core.utils.ForestryTank; +import forestry.core.fluids.tanks.StandardTank; public abstract class TilePowered extends TileBase implements IPowerHandler, IRenderableMachine { @@ -179,7 +179,7 @@ public abstract class TilePowered extends TileBase implements IPowerHandler, IRe } */ /* LIQUID CONTAINER HANDLING */ - protected ItemStack bottleIntoContainer(ItemStack canStack, ItemStack outputStack, FluidContainerData container, ForestryTank tank) { + protected ItemStack bottleIntoContainer(ItemStack canStack, ItemStack outputStack, FluidContainerData container, StandardTank tank) { if (tank.getFluidAmount() < container.fluid.amount) return outputStack; if (canStack.stackSize <= 0) diff --git a/src/main/java/forestry/core/gui/ContainerAlyzer.java b/src/main/java/forestry/core/gui/ContainerAlyzer.java new file mode 100644 index 000000000..1b5af9f50 --- /dev/null +++ b/src/main/java/forestry/core/gui/ContainerAlyzer.java @@ -0,0 +1,83 @@ +package forestry.core.gui; + +import forestry.core.gui.slots.SlotCustom; +import forestry.core.proxy.Proxies; +import forestry.core.utils.AlyzerInventory; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; + +public class ContainerAlyzer extends ContainerItemInventory { + + private AlyzerInventory inventory; + + protected ContainerAlyzer(InventoryPlayer inventoryplayer, AlyzerInventory inventory, Object[] acceptedEnergy, Object[] acceptedSpecimens) { + super(inventory, inventoryplayer.player); + + this.inventory = inventory; + + final int xPosLeftSlots = 223; + + // Energy + this.addSlot(new SlotCustom(inventory, inventory.SLOT_ENERGY, xPosLeftSlots, 8, acceptedEnergy)); + + // Bee to analyze + this.addSlot(new SlotCustom(inventory, inventory.SLOT_SPECIMEN, xPosLeftSlots, 26, acceptedSpecimens)); + + // Analyzed bee + this.addSlot(new SlotCustom(inventory, inventory.SLOT_ANALYZE_1, xPosLeftSlots, 57, acceptedSpecimens)); + this.addSlot(new SlotCustom(inventory, inventory.SLOT_ANALYZE_2, xPosLeftSlots, 75, acceptedSpecimens)); + this.addSlot(new SlotCustom(inventory, inventory.SLOT_ANALYZE_3, xPosLeftSlots, 93, acceptedSpecimens)); + this.addSlot(new SlotCustom(inventory, inventory.SLOT_ANALYZE_4, xPosLeftSlots, 111, acceptedSpecimens)); + this.addSlot(new SlotCustom(inventory, inventory.SLOT_ANALYZE_5, xPosLeftSlots, 129, acceptedSpecimens)); + + final int xPosPlayerInv = 43; + final int xSpacePlayerInv = 18; + final int yPosPlayerInv= 156; + final int ySpacePlayerInv = 18; + + // Player inventory + for (int i1 = 0; i1 < 3; i1++) { + for (int l1 = 0; l1 < 9; l1++) { + int slot = l1 + i1 * 9 + 9; + int x = xPosPlayerInv + (l1 * xSpacePlayerInv); + int y = yPosPlayerInv + (i1 * ySpacePlayerInv); + addSecuredSlot(inventoryplayer, slot, x, y); + } + } + // Player hotbar + for (int j1 = 0; j1 < 9; j1++) { + int x = xPosPlayerInv + (j1 * xSpacePlayerInv); + addSecuredSlot(inventoryplayer, j1, x, 214); + } + + } + + @Override + public void onContainerClosed(EntityPlayer entityplayer) { + + if (!Proxies.common.isSimulating(entityplayer.worldObj)) + return; + + // Last slot is the energy slot, so we don't save that one. + for (int i = 0; i < inventory.getSizeInventory(); i++) { + if (i == inventory.SLOT_ENERGY) + continue; + ItemStack stack = inventory.getStackInSlot(i); + if (stack == null) + continue; + + Proxies.common.dropItemPlayer(entityplayer, stack); + inventory.setInventorySlotContents(i, null); + } + + inventory.onGuiSaved(entityplayer); + } + + @Override + protected boolean isAcceptedItem(EntityPlayer player, ItemStack stack) { + return true; + } + +} diff --git a/src/main/java/forestry/core/gui/ContainerAnalyzer.java b/src/main/java/forestry/core/gui/ContainerAnalyzer.java index ce98716cb..231aa18a0 100755 --- a/src/main/java/forestry/core/gui/ContainerAnalyzer.java +++ b/src/main/java/forestry/core/gui/ContainerAnalyzer.java @@ -54,17 +54,4 @@ public class ContainerAnalyzer extends ContainerLiquidTanks { } - @Override - public void updateProgressBar(int i, int j) { - tile.getGUINetworkData(i, j); - } - - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); - - for (int i = 0; i < crafters.size(); i++) - tile.sendGUINetworkData(this, (ICrafting) crafters.get(i)); - } - } diff --git a/src/main/java/forestry/core/gui/ContainerForestry.java b/src/main/java/forestry/core/gui/ContainerForestry.java index 39c6e65b0..31fd7293d 100755 --- a/src/main/java/forestry/core/gui/ContainerForestry.java +++ b/src/main/java/forestry/core/gui/ContainerForestry.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.gui; +import forestry.core.fluids.tanks.FakeTank; +import forestry.core.fluids.tanks.StandardTank; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; @@ -19,8 +21,8 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import forestry.core.gui.slots.SlotForestry; -import forestry.core.utils.ForestryTank; import forestry.core.utils.StackUtils; +import net.minecraftforge.fluids.IFluidTank; public class ContainerForestry extends Container { @@ -204,11 +206,4 @@ public class ContainerForestry extends Container { public boolean canInteractWith(EntityPlayer entityplayer) { return inventory.isUseableByPlayer(entityplayer); } - - public void onTankUpdate(NBTTagCompound nbt) { - } - - public ForestryTank getTank(int slot) { - return ForestryTank.FAKETANK; - } } diff --git a/src/main/java/forestry/core/gui/ContainerLiquidTanks.java b/src/main/java/forestry/core/gui/ContainerLiquidTanks.java index 47a3f7273..688d1dcfa 100755 --- a/src/main/java/forestry/core/gui/ContainerLiquidTanks.java +++ b/src/main/java/forestry/core/gui/ContainerLiquidTanks.java @@ -10,35 +10,29 @@ ******************************************************************************/ package forestry.core.gui; -import java.util.HashMap; -import java.util.Map; - import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.inventory.ICrafting; import net.minecraft.inventory.IInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.IFluidTank; import forestry.api.core.IToolPipette; +import forestry.core.fluids.tanks.StandardTank; import forestry.core.interfaces.ILiquidTankContainer; import forestry.core.network.PacketIds; import forestry.core.network.PacketPayload; -import forestry.core.network.PacketTankUpdate; import forestry.core.network.PacketUpdate; import forestry.core.proxy.Proxies; -import forestry.core.utils.ForestryTank; public class ContainerLiquidTanks extends ContainerForestry { - private ILiquidTankContainer tanks; + private ILiquidTankContainer tile; - public ContainerLiquidTanks(IInventory inventory, ILiquidTankContainer tanks) { + public ContainerLiquidTanks(IInventory inventory, ILiquidTankContainer tile) { super(inventory); - this.tanks = tanks; + this.tile = tile; } public void handlePipetteClick(int slot, EntityPlayer player) { @@ -52,74 +46,52 @@ public class ContainerLiquidTanks extends ContainerForestry { return; if (!Proxies.common.isSimulating(player.worldObj)) { - PacketPayload payload = new PacketPayload(1, 0, 0); payload.intPayload[0] = slot; Proxies.net.sendToServer(new PacketUpdate(PacketIds.PIPETTE_CLICK, payload)); return; - } IToolPipette pipette = (IToolPipette) held; - int liquidAmount = tanks.getTanks()[slot].getFluid().amount; + StandardTank tank = tile.getTankManager().get(slot); + int liquidAmount = tank.getFluid().amount; + if (pipette.canPipette(itemstack) && liquidAmount > 0) { - if (liquidAmount > 0) { - int filled = pipette.fill(itemstack, tanks.getTanks()[slot].drain(1000, false), - true); - tanks.getTanks()[slot].drain(filled, true); + FluidStack fillAmount = tank.drain(1000, false); + int filled = pipette.fill(itemstack, fillAmount, true); + tank.drain(filled, true); } - } else { - - IFluidTank tank = tanks.getTanks()[slot]; FluidStack potential = pipette.drain(itemstack, pipette.getCapacity(itemstack), false); if (potential != null) pipette.drain(itemstack, tank.fill(potential, true), true); - } } - private Map syncedFluids = new HashMap(); + + @Override + public void updateProgressBar(int messageId, int data) { + super.updateProgressBar(messageId, data); + + tile.getTankManager().processGuiUpdate(messageId, data); + tile.getGUINetworkData(messageId, data); + } @Override public void detectAndSendChanges() { super.detectAndSendChanges(); - - for (int i = 0; i < tanks.getTanks().length; i++) { - ForestryTank tank = tanks.getTanks()[i]; - - // If null has been synced - if (tank.getFluid() == null && getTank(i).getFluidAmount() <= 0) - continue; - // If fluid has been synced - if (tank.getFluid() != null && tank.getFluid().isFluidStackIdentical(getTank(i).getFluid())) - continue; - - for (int j = 0; j < this.crafters.size(); ++j) { - if (this.crafters.get(j) instanceof EntityPlayerMP) { - EntityPlayerMP player = (EntityPlayerMP) this.crafters.get(j); - Proxies.net.sendToPlayer(new PacketTankUpdate(i, tank), player); - } - } - - syncedFluids.put(i, new ForestryTank(tank.getFluid() == null ? null : tank.getFluid().copy(), tank.getCapacity())); - - } + tile.getTankManager().updateGuiData(this, crafters); + for (int i = 0; i < crafters.size(); i++) + tile.sendGUINetworkData(this, (ICrafting) crafters.get(i)); } @Override - public void onTankUpdate(NBTTagCompound nbt) { - int tankID = nbt.getByte("tank"); - int capacity = nbt.getShort("capacity"); - tanks.getTanks()[tankID].readFromNBT(nbt); - - ForestryTank tank = new ForestryTank(capacity); - tank.readFromNBT(nbt); - syncedFluids.put(tankID, tank); + public void addCraftingToCrafters(ICrafting icrafting) { + super.addCraftingToCrafters(icrafting); + tile.getTankManager().initGuiData(this, icrafting); } - @Override - public ForestryTank getTank(int slot) { - return syncedFluids.get(slot) == null ? ForestryTank.FAKETANK : syncedFluids.get(slot); + public StandardTank getTank(int slot) { + return tile.getTankManager().get(slot); } } diff --git a/src/main/java/forestry/core/gui/GuiAlyzer.java b/src/main/java/forestry/core/gui/GuiAlyzer.java index c828d1537..da6a4261d 100755 --- a/src/main/java/forestry/core/gui/GuiAlyzer.java +++ b/src/main/java/forestry/core/gui/GuiAlyzer.java @@ -21,6 +21,7 @@ import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.util.StatCollector; +import org.apache.commons.lang3.StringUtils; import org.lwjgl.opengl.GL11; import forestry.api.apiculture.EnumBeeChromosome; @@ -43,17 +44,22 @@ import forestry.core.utils.StringUtil; public abstract class GuiAlyzer extends GuiForestry { protected static final int COLUMN_0 = 12; - protected static final int COLUMN_1 = 52; - protected static final int COLUMN_2 = 108; + protected static final int COLUMN_1 = 85; + protected static final int COLUMN_2 = 150; protected IInventory inventory; protected ISpeciesRoot speciesRoot; protected IBreedingTracker breedingTracker; + protected String guiName; + protected HashMap iconStacks = new HashMap(); public GuiAlyzer(ISpeciesRoot speciesRoot, EntityPlayer player, ContainerForestry container, IInventory inventory, int pageMax, int pageSize) { - super(Defaults.TEXTURE_PATH_GUI + "/beealyzer.png", container); + super(Defaults.TEXTURE_PATH_GUI + "/beealyzer2.png", container); + + xSize = 246; + ySize = 238; this.inventory = inventory; this.speciesRoot = speciesRoot; @@ -94,8 +100,8 @@ public abstract class GuiAlyzer extends GuiForestry { int columnwidth = column2 - column1 - 16; RenderHelper.enableStandardItemLighting(); - drawItemStack(iconStacks.get(primary.getUID()), adjustToFactor(guiLeft + column1 + columnwidth + 2), adjustToFactor(guiTop + getLineY())); - drawItemStack(iconStacks.get(secondary.getUID()), adjustToFactor(guiLeft + column2 + columnwidth + 4), adjustToFactor(guiTop + getLineY())); + drawItemStack(iconStacks.get(primary.getUID()), adjustToFactor(guiLeft + column1 + columnwidth - 4), adjustToFactor(guiTop + getLineY())); + drawItemStack(iconStacks.get(secondary.getUID()), adjustToFactor(guiLeft + column2 + columnwidth - 2), adjustToFactor(guiTop + getLineY())); RenderHelper.disableStandardItemLighting(); String primaryName; @@ -124,6 +130,50 @@ public abstract class GuiAlyzer extends GuiForestry { } } + @Override + protected void drawGuiContainerBackgroundLayer(float f, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(f, mouseX, mouseY); + widgetManager.clear(); + } + + protected void drawAnalyticsOverview() { + + startPage(); + + newLine(); + String title = StringUtil.localize(guiName).toUpperCase(); + drawCenteredLine(title, 8, 208); + newLine(); + + fontRendererObj.drawSplitString(StringUtil.localize(guiName + ".help"), (int) ((guiLeft + COLUMN_0 + 4) * (1 / factor)), + (int) ((guiTop + 42) * (1 / factor)), (int) (195 * (1 / factor)), fontColor.get("gui.screen")); + newLine(); + newLine(); + newLine(); + newLine(); + + drawLine(StringUtil.localize("gui.alyzer.overview") + ":", COLUMN_0 + 4); + newLine(); + drawLine("I : " + StringUtil.localize("gui.general"), COLUMN_0 + 4); + newLine(); + drawLine("II : " + StringUtil.localize("gui.environment"), COLUMN_0 + 4); + newLine(); + drawLine("III: " + StringUtil.localize("gui.produce"), COLUMN_0 + 4); + newLine(); + drawLine("IV : " + StringUtil.localize("gui.evolution"), COLUMN_0 + 4); + + newLine(); + + String mode = breedingTracker.getModeName(); + if (mode != null && !mode.isEmpty()) { + newLine(); + String rules = StringUtil.localize(guiName + ".behaviour") + ": " + StringUtil.capitalize(mode); + drawCenteredLine(rules, 8, 208, fontColor.get(guiName + ".binomial")); + } + + endPage(); + } + protected final void drawAnalyticsPageClassification(IIndividual individual) { startPage(); @@ -151,9 +201,9 @@ public abstract class GuiAlyzer extends GuiForestry { continue; drawLine(group.getScientific(), x, group.getLevel().getColour()); - drawLine(group.getLevel().name(), 130, group.getLevel().getColour()); + drawLine(group.getLevel().name(), 155, group.getLevel().getColour()); newLine(); - x += 8; + x += 10; } // Add the species name @@ -162,26 +212,26 @@ public abstract class GuiAlyzer extends GuiForestry { binomial = group.getScientific().substring(0, 1) + ". " + binomial.toLowerCase(Locale.ENGLISH); drawLine(binomial, x, 0xebae85); - drawLine("SPECIES", 130, 0xebae85); + drawLine("SPECIES", 155, 0xebae85); newLine(); newLine(); drawLine(StringUtil.localize("gui.alyzer.authority") + ": " + individual.getGenome().getPrimary().getAuthority(), 12); if (AlleleManager.alleleRegistry.isBlacklisted(individual.getIdent())) { String extinct = ">> " + StringUtil.localize("gui.alyzer.extinct").toUpperCase() + " <<"; - fontRendererObj.drawStringWithShadow(extinct, adjustToFactor(guiLeft + 160) - fontRendererObj.getStringWidth(extinct), + fontRendererObj.drawStringWithShadow(extinct, adjustToFactor(guiLeft + 208) - fontRendererObj.getStringWidth(extinct), adjustToFactor(guiTop + getLineY()), fontColor.get("gui.beealyzer.dominant")); } newLine(); String description = individual.getGenome().getPrimary().getDescription(); - if (description == null || description.isEmpty()) - drawSplitLine(StringUtil.localize("gui.alyzer.nodescription"), 12, 156, 0x666666); + if (StringUtils.isBlank(description) || description.startsWith("for.description.")) + drawSplitLine(StringUtil.localize("gui.alyzer.nodescription"), 12, 208, 0x666666); else { String tokens[] = description.split("\\|"); - drawSplitLine(tokens[0], 12, 152, 0x666666); + drawSplitLine(tokens[0], 12, 208, 0x666666); if (tokens.length > 1) - fontRendererObj.drawStringWithShadow("- " + tokens[1], adjustToFactor(guiLeft + 160) - fontRendererObj.getStringWidth("- " + tokens[1]), + fontRendererObj.drawStringWithShadow("- " + tokens[1], adjustToFactor(guiLeft + 208) - fontRendererObj.getStringWidth("- " + tokens[1]), adjustToFactor(guiTop + 145 - 14), 0x99cc32); } @@ -191,10 +241,12 @@ public abstract class GuiAlyzer extends GuiForestry { protected void drawAnalyticsPage4(IIndividual individual) { + float factor = this.factor; + this.setFactor(1.0f); + startPage(COLUMN_0, COLUMN_1, COLUMN_2); drawLine(StringUtil.localize("gui.beealyzer.mutations") + ":", COLUMN_0); newLine(); - newLine(); RenderHelper.enableGUIStandardItemLighting(); @@ -222,7 +274,7 @@ public abstract class GuiAlyzer extends GuiForestry { } x += columnWidth; - if (x > 150) { + if (x >= columnWidth * 4) { x = 0; newLine(); newLine(); @@ -230,100 +282,64 @@ public abstract class GuiAlyzer extends GuiForestry { } endPage(); + + this.setFactor(factor); } protected void drawMutationInfo(IMutation combination, IAllele species, int x) { - drawItemStack(iconStacks.get(combination.getPartner(species).getUID()), - adjustToFactor(guiLeft) + x, adjustToFactor(guiTop) + getLineY()); - /* - itemRenderer.renderItemIntoGUI(fontRendererObj, mc.renderEngine, iconStacks.get(combination.getPartner(species).getUID()), adjustToFactor(guiLeft) + x, - adjustToFactor(guiTop) + getLineY()); - itemRenderer.renderItemOverlayIntoGUI(fontRendererObj, mc.renderEngine, iconStacks.get(combination.getPartner(species).getUID()), adjustToFactor(guiLeft) - + x, adjustToFactor(guiTop) + getLineY()); - */ + ItemStack partnerBee = iconStacks.get(combination.getPartner(species).getUID()); + widgetManager.add(new ItemStackWidget(x, getLineY(), partnerBee)); + + drawProbabilityArrow(combination.getBaseChance(), adjustToFactor(guiLeft) + x + 18, adjustToFactor(guiTop) + getLineY() + 4); IAllele result = combination.getTemplate()[EnumBeeChromosome.SPECIES.ordinal()]; - - drawItemStack(iconStacks.get(result.getUID()), - adjustToFactor(guiLeft) + x + 33, adjustToFactor(guiTop) + getLineY()); - /* - itemRenderer.renderItemIntoGUI(fontRendererObj, mc.renderEngine, iconStacks.get(result.getUID()), adjustToFactor(guiLeft) + x + 33, adjustToFactor(guiTop) - + getLineY()); - itemRenderer.renderItemOverlayIntoGUI(fontRendererObj, mc.renderEngine, iconStacks.get(result.getUID()), adjustToFactor(guiLeft) + x + 33, - adjustToFactor(guiTop) + getLineY()); - */ - - int line = 0; - int column = 196; - - switch (EnumMutateChance.rateChance(combination.getBaseChance())) { - case HIGHEST: - column = 226; - line = 9; - break; - case HIGHER: - column = 211; - line = 9; - break; - case HIGH: - line = 9; - break; - case NORMAL: - column = 226; - break; - case LOW: - column = 211; - break; - case LOWEST: - default: - break; - } - - Proxies.common.bindTexture(textureFile); - drawTexturedModalRect(adjustToFactor(guiLeft) + x + 18, adjustToFactor(guiTop) + getLineY() + 4, column, line, 15, 9); - + ItemStack resultBee = iconStacks.get(result.getUID()); + widgetManager.add(new ItemStackWidget(x + 33, getLineY(), resultBee)); } protected void drawUnknownMutation(IMutation combination, IAllele species, int x) { - // Question marks + drawQuestionMark(adjustToFactor(guiLeft) + x, adjustToFactor(guiTop) + getLineY()); + + drawProbabilityArrow(combination.getBaseChance(), adjustToFactor(guiLeft) + x + 18, adjustToFactor(guiTop) + getLineY() + 4); + + drawQuestionMark(adjustToFactor(guiLeft) + x + 32, adjustToFactor(guiTop) + getLineY()); + } + + protected void drawQuestionMark(int x, int y) { Proxies.common.bindTexture(textureFile); - drawTexturedModalRect(adjustToFactor(guiLeft) + x, adjustToFactor(guiTop) + getLineY(), 196, 18, 16, 16); + drawTexturedModalRect(x, y, 78, 240, 16, 16); + } - Proxies.common.bindTexture(textureFile); - drawTexturedModalRect(adjustToFactor(guiLeft) + x + 32, adjustToFactor(guiTop) + getLineY(), 196, 18, 16, 16); - - int line = 0; - int column = 196; - - switch (EnumMutateChance.rateChance(combination.getBaseChance())) { - case HIGHEST: - column = 226; - line = 9; - break; - case HIGHER: - column = 211; - line = 9; - break; - case HIGH: - line = 9; - break; - case NORMAL: - column = 226; - break; - case LOW: - column = 211; - break; - case LOWEST: - default: - break; + protected void drawProbabilityArrow(float chance, int x, int y) { + int line = 247; + int column = 100; + switch (EnumMutateChance.rateChance(chance)) { + case HIGHEST: + column = 100; + break; + case HIGHER: + column = 100 + 15; + break; + case HIGH: + column = 100 + 15 * 2; + break; + case NORMAL: + column = 100 + 15 * 3; + break; + case LOW: + column = 100 + 15 * 4; + break; + case LOWEST: + column = 100 + 15 * 5; + default: + break; } // Probability arrow Proxies.common.bindTexture(textureFile); - drawTexturedModalRect(adjustToFactor(guiLeft) + x + 18, adjustToFactor(guiTop) + getLineY() + 4, column, line, 15, 9); - + drawTexturedModalRect(x, y, column, line, 15, 9); } protected void drawToleranceInfo(EnumTolerance tolerance, int x, int textColor) { @@ -367,22 +383,22 @@ public abstract class GuiAlyzer extends GuiForestry { private void drawDownSymbol(int x, int y) { Proxies.common.bindTexture(textureFile); - drawTexturedModalRect((int) ((guiLeft + x) * (1 / factor)), (int) ((guiTop + getLineY()) * (1 / factor)), 196, 34, 15, 9); + drawTexturedModalRect((int) ((guiLeft + x) * (1 / factor)), (int) ((guiTop + getLineY()) * (1 / factor)), 0, 247, 15, 9); } private void drawUpSymbol(int x, int y) { Proxies.common.bindTexture(textureFile); - drawTexturedModalRect((int) ((guiLeft + x) * (1 / factor)), (int) ((guiTop + getLineY()) * (1 / factor)), 211, 34, 15, 9); + drawTexturedModalRect((int) ((guiLeft + x) * (1 / factor)), (int) ((guiTop + getLineY()) * (1 / factor)), 15, 247, 15, 9); } private void drawBothSymbol(int x, int y) { Proxies.common.bindTexture(textureFile); - drawTexturedModalRect((int) ((guiLeft + x) * (1 / factor)), (int) ((guiTop + getLineY()) * (1 / factor)), 226, 34, 15, 9); + drawTexturedModalRect((int) ((guiLeft + x) * (1 / factor)), (int) ((guiTop + getLineY()) * (1 / factor)), 30, 247, 15, 9); } private void drawNoneSymbol(int x, int y) { Proxies.common.bindTexture(textureFile); - drawTexturedModalRect((int) ((guiLeft + x) * (1 / factor)), (int) ((guiTop + getLineY()) * (1 / factor)), 241, 34, 15, 9); + drawTexturedModalRect((int) ((guiLeft + x) * (1 / factor)), (int) ((guiTop + getLineY()) * (1 / factor)), 45, 247, 15, 9); } protected void drawFertilityInfo(int fertility, int x, int textColor, int texOffset) { @@ -390,7 +406,7 @@ public abstract class GuiAlyzer extends GuiForestry { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); Proxies.common.bindTexture(textureFile); - drawTexturedModalRect((int) ((guiLeft + x + 19) * (1 / factor)), (int) ((guiTop + getLineY()) * (1 / factor)), 196, 43 + texOffset, 12, 9); + drawTexturedModalRect((int) ((guiLeft + x + 14) * (1 / factor)), (int) ((guiTop + getLineY()) * (1 / factor)), 60, 240 + texOffset, 12, 8); drawLine(Integer.toString(fertility) + " x", x, textColor); } diff --git a/src/main/java/forestry/core/gui/GuiAnalyzer.java b/src/main/java/forestry/core/gui/GuiAnalyzer.java index 8c3775b5c..f03f2b9d4 100755 --- a/src/main/java/forestry/core/gui/GuiAnalyzer.java +++ b/src/main/java/forestry/core/gui/GuiAnalyzer.java @@ -16,10 +16,9 @@ import forestry.core.config.Defaults; import forestry.core.gadgets.TileAnalyzer; import forestry.core.gui.widgets.TankWidget; import forestry.core.utils.EnumTankLevel; -import forestry.core.utils.StringUtil; import forestry.core.utils.Utils; -public class GuiAnalyzer extends GuiForestry { +public class GuiAnalyzer extends GuiForestryTitled { public GuiAnalyzer(InventoryPlayer inventory, TileAnalyzer tile) { super(Defaults.TEXTURE_PATH_GUI + "/alyzer.png", new ContainerAnalyzer(inventory, tile), tile); @@ -27,13 +26,6 @@ public class GuiAnalyzer extends GuiForestry { widgetManager.add(new TankWidget(this.widgetManager, 95, 24, 0)); } - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - super.drawGuiContainerForegroundLayer(mouseX, mouseY); - String title = StringUtil.localize("tile.for." + tile.getInventoryName()); - this.fontRendererObj.drawString(title, getCenteredOffset(title), 6, fontColor.get("gui.title")); - } - @Override protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); diff --git a/src/main/java/forestry/core/gui/GuiForestry.java b/src/main/java/forestry/core/gui/GuiForestry.java index 2cbc6a857..c1af240dd 100755 --- a/src/main/java/forestry/core/gui/GuiForestry.java +++ b/src/main/java/forestry/core/gui/GuiForestry.java @@ -10,9 +10,14 @@ ******************************************************************************/ package forestry.core.gui; +import java.awt.Color; import java.util.Collection; import java.util.List; +import codechicken.nei.VisiblityData; +import codechicken.nei.api.INEIGuiHandler; +import codechicken.nei.api.TaggedInventoryArea; + import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.renderer.OpenGlHelper; @@ -35,6 +40,7 @@ import forestry.core.gui.slots.SlotForestry; import forestry.core.gui.tooltips.IToolTipProvider; import forestry.core.gui.tooltips.ToolTip; import forestry.core.gui.tooltips.ToolTipLine; +import forestry.core.gui.widgets.Widget; import forestry.core.interfaces.IClimatised; import forestry.core.interfaces.IErrorSource; import forestry.core.interfaces.IHintSource; @@ -43,7 +49,7 @@ import forestry.core.interfaces.IPowerHandler; import forestry.core.proxy.Proxies; import forestry.core.utils.FontColour; -public abstract class GuiForestry extends GuiContainer { +public abstract class GuiForestry extends GuiContainer implements INEIGuiHandler { /* WIDGETS */ protected WidgetManager widgetManager; @@ -53,10 +59,6 @@ public abstract class GuiForestry extends GuiContainer { public ResourceLocation textureFile; protected FontColour fontColor; - public GuiForestry(ContainerForestry container) { - this("", container); - } - public GuiForestry(String texture, ContainerForestry container) { this(new ResourceLocation("forestry", texture), container, null); } @@ -323,38 +325,40 @@ public abstract class GuiForestry extends GuiContainer { int left = this.guiLeft; int top = this.guiTop; - int lenght = 0; + int length = 0; + int height = 0; int x; int y; for (ToolTipLine tip : toolTips) { y = this.fontRendererObj.getStringWidth(tip.text); - if (y > lenght) - lenght = y; + height += 10 + tip.getSpacing(); + if (y > length) + length = y; } x = mouseX - left + 12; y = mouseY - top - 12; - int var14 = 8; - - if (toolTips.size() > 1) - var14 += 2 + (toolTips.size() - 1) * 10; this.zLevel = 300.0F; itemRender.zLevel = 300.0F; - int var15 = -267386864; - this.drawGradientRect(x - 3, y - 4, x + lenght + 3, y - 3, var15, var15); - this.drawGradientRect(x - 3, y + var14 + 3, x + lenght + 3, y + var14 + 4, var15, var15); - this.drawGradientRect(x - 3, y - 3, x + lenght + 3, y + var14 + 3, var15, var15); - this.drawGradientRect(x - 4, y - 3, x - 3, y + var14 + 3, var15, var15); - this.drawGradientRect(x + lenght + 3, y - 3, x + lenght + 4, y + var14 + 3, var15, var15); - int var16 = 1347420415; - int var17 = (var16 & 16711422) >> 1 | var16 & -16777216; - this.drawGradientRect(x - 3, y - 3 + 1, x - 3 + 1, y + var14 + 3 - 1, var16, var17); - this.drawGradientRect(x + lenght + 2, y - 3 + 1, x + lenght + 3, y + var14 + 3 - 1, var16, var17); - this.drawGradientRect(x - 3, y - 3, x + lenght + 3, y - 3 + 1, var16, var16); - this.drawGradientRect(x - 3, y + var14 + 2, x + lenght + 3, y + var14 + 3, var17, var17); + Color backgroundColor = new Color(16, 0, 16, 240); + int backgroundColorInt = backgroundColor.getRGB(); + this.drawGradientRect(x - 3, y - 4, x + length + 2, y - 3, backgroundColorInt, backgroundColorInt); + this.drawGradientRect(x - 3, y + height + 1, x + length + 2, y + height + 2, backgroundColorInt, backgroundColorInt); + this.drawGradientRect(x - 3, y - 3, x + length + 2, y + height + 1, backgroundColorInt, backgroundColorInt); + this.drawGradientRect(x - 4, y - 3, x - 3, y + height + 1, backgroundColorInt, backgroundColorInt); + this.drawGradientRect(x + length + 2, y - 3, x + length + 3, y + height + 1, backgroundColorInt, backgroundColorInt); + + Color borderColorTop = new Color(80, 0, 255, 80); + int borderColorTopInt = borderColorTop.getRGB(); + Color borderColorBottom = new Color((borderColorTopInt & 0xfefefe) >> 1 | borderColorTopInt & -0x1000000, true); + int borderColorBottomInt = borderColorBottom.getRGB(); + this.drawGradientRect(x - 3, y - 3 + 1, x - 3 + 1, y + height, borderColorTopInt, borderColorBottomInt); + this.drawGradientRect(x + length + 1, y - 3 + 1, x + length + 2, y + height, borderColorTopInt, borderColorBottomInt); + this.drawGradientRect(x - 3, y - 3, x + length + 2, y - 3 + 1, borderColorTopInt, borderColorTopInt); + this.drawGradientRect(x - 3, y + height, x + length + 2, y + height + 1, borderColorBottomInt, borderColorBottomInt); for (ToolTipLine tip : toolTips) { String line = tip.text; @@ -545,4 +549,49 @@ public abstract class GuiForestry extends GuiContainer { this.zLevel = 0.0F; itemRender.zLevel = 0.0F; } + + protected class ItemStackWidget extends Widget { + ItemStack itemStack; + + public ItemStackWidget(int xPos, int yPos, ItemStack itemStack) { + super(widgetManager, xPos, yPos); + + IIcon icon = itemStack.getItem().getIcon(itemStack, 0); + + this.width = icon.getIconWidth(); + this.height = icon.getIconHeight(); + this.itemStack = itemStack; + } + + @Override + public void draw(int startX, int startY) { + itemRender.renderItemAndEffectIntoGUI(fontRendererObj, mc.renderEngine, itemStack, xPos + startX, yPos + startY); + itemRender.renderItemOverlayIntoGUI(fontRendererObj, mc.renderEngine, itemStack, xPos + startX, yPos + startY); + } + + @Override + public ToolTip getToolTip() { + ToolTip tip = new ToolTip(); + tip.add(itemStack.getDisplayName()); + return tip; + } + } + + /* NEI */ + @Override + public VisiblityData modifyVisiblity(GuiContainer gui, VisiblityData currentVisibility) { return null; } + @Override + public Iterable getItemSpawnSlots(GuiContainer gui, ItemStack item) { return null; } + @Override + public List getInventoryAreas(GuiContainer gui) { return null; } + @Override + public boolean handleDragNDrop(GuiContainer gui, int mousex, int mousey, ItemStack draggedStack, int button) { return false; } + + @Override + public boolean hideItemPanelSlot(GuiContainer gui, int x, int y, int w, int h) { + if (gui instanceof GuiForestry) + return ((GuiForestry)gui).ledgerManager.ledgerOverlaps(x, y, w, h); + else + return false; + } } diff --git a/src/main/java/forestry/core/gui/GuiForestryTitled.java b/src/main/java/forestry/core/gui/GuiForestryTitled.java new file mode 100644 index 000000000..d09b4ec30 --- /dev/null +++ b/src/main/java/forestry/core/gui/GuiForestryTitled.java @@ -0,0 +1,34 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.gui; + +import net.minecraft.util.ResourceLocation; + +import forestry.core.gadgets.TileForestry; +import forestry.core.utils.StringUtil; + +public abstract class GuiForestryTitled extends GuiForestry { + + public GuiForestryTitled(String texture, ContainerForestry container, Object inventory) { + super(texture, container, inventory); + } + + public GuiForestryTitled(ResourceLocation texture, ContainerForestry container, Object inventory) { + super(texture, container, inventory); + } + + @Override + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + String name = StringUtil.localizeTile(tile.getUnlocalizedName()); + this.fontRendererObj.drawString(name, getCenteredOffset(name), 6, fontColor.get("gui.title")); + super.drawGuiContainerForegroundLayer(mouseX, mouseY); + } +} diff --git a/src/main/java/forestry/core/gui/LedgerManager.java b/src/main/java/forestry/core/gui/LedgerManager.java index 1e9353e8a..57f1934df 100755 --- a/src/main/java/forestry/core/gui/LedgerManager.java +++ b/src/main/java/forestry/core/gui/LedgerManager.java @@ -117,4 +117,8 @@ public class LedgerManager { } + public boolean ledgerOverlaps(int x, int y, int width, int height) { + return getAtPosition(x + width, y + height) != null || getAtPosition(x + width, y) != null || getAtPosition(x, y + height) != null || getAtPosition(x, y) != null; + } + } diff --git a/src/main/java/forestry/core/gui/slots/SlotCustom.java b/src/main/java/forestry/core/gui/slots/SlotCustom.java index d0881973a..e7624ccd1 100755 --- a/src/main/java/forestry/core/gui/slots/SlotCustom.java +++ b/src/main/java/forestry/core/gui/slots/SlotCustom.java @@ -42,8 +42,8 @@ public class SlotCustom extends SlotForestry { private ICrafter crafter; private String blockedTexture = "slots/blocked"; - public SlotCustom(IInventory iinventory, int i, int j, int k, boolean exclusion) { - super(iinventory, i, j, k); + public SlotCustom(IInventory iinventory, int slotIndex, int xPos, int yPos, boolean exclusion) { + super(iinventory, slotIndex, xPos, yPos); items = new Object[0]; this.exclusion = exclusion; } @@ -52,17 +52,17 @@ public class SlotCustom extends SlotForestry { this(iinventory, i, j, k, items.toArray()); }*/ - public SlotCustom(IInventory iinventory, Collection items, int i, int j, int k) { - this(iinventory, i, j, k, items.toArray()); + public SlotCustom(IInventory iinventory, Collection items, int slotIndex, int xPos, int yPos) { + this(iinventory, slotIndex, xPos, yPos, items.toArray()); } - public SlotCustom(IInventory iinventory, int i, int j, int k, boolean exclusion, Object... items) { - this(iinventory, i, j, k, items); + public SlotCustom(IInventory iinventory, int slotIndex, int xPos, int yPos, boolean exclusion, Object... items) { + this(iinventory, slotIndex, xPos, yPos, items); this.exclusion = exclusion; } - public SlotCustom(IInventory iinventory, int i, int j, int k, Object... items) { - super(iinventory, i, j, k); + public SlotCustom(IInventory iinventory, int slotIndex, int xPos, int yPos, Object... items) { + super(iinventory, slotIndex, xPos, yPos); this.items = items; } diff --git a/src/main/java/forestry/core/gui/widgets/TankWidget.java b/src/main/java/forestry/core/gui/widgets/TankWidget.java index 3d987bf2d..99eecc761 100755 --- a/src/main/java/forestry/core/gui/widgets/TankWidget.java +++ b/src/main/java/forestry/core/gui/widgets/TankWidget.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.gui.widgets; +import forestry.farming.gui.ContainerFarm; +import net.minecraft.inventory.Container; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; @@ -19,13 +21,13 @@ import net.minecraftforge.fluids.FluidStack; import org.lwjgl.opengl.GL11; import forestry.api.core.IToolPipette; +import forestry.core.fluids.tanks.StandardTank; import forestry.core.gui.ContainerForestry; import forestry.core.gui.ContainerLiquidTanks; import forestry.core.gui.WidgetManager; import forestry.core.gui.tooltips.ToolTip; import forestry.core.proxy.Proxies; import forestry.core.render.SpriteSheet; -import forestry.core.utils.ForestryTank; /** * Slot for liquid tanks @@ -48,8 +50,13 @@ public class TankWidget extends Widget { return this; } - public ForestryTank getTank() { - return ((ContainerForestry) manager.gui.inventorySlots).getTank(slot); + public StandardTank getTank() { + Container container = manager.gui.inventorySlots; + if (container instanceof ContainerLiquidTanks) + return ((ContainerLiquidTanks) container).getTank(slot); + else if (container instanceof ContainerFarm) + return ((ContainerFarm) container).getTank(slot); + return null; } @Override @@ -96,7 +103,7 @@ public class TankWidget extends Widget { @Override public ToolTip getToolTip() { - ForestryTank tank = getTank(); + StandardTank tank = getTank(); if (tank == null) return null; return tank.getToolTip(); diff --git a/src/main/java/forestry/core/interfaces/ILiquidTankContainer.java b/src/main/java/forestry/core/interfaces/ILiquidTankContainer.java index dc5c7601e..f3b410ba7 100755 --- a/src/main/java/forestry/core/interfaces/ILiquidTankContainer.java +++ b/src/main/java/forestry/core/interfaces/ILiquidTankContainer.java @@ -10,12 +10,16 @@ ******************************************************************************/ package forestry.core.interfaces; +import forestry.core.fluids.TankManager; +import forestry.core.fluids.tanks.StandardTank; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.ICrafting; import net.minecraftforge.fluids.IFluidHandler; -import forestry.core.utils.ForestryTank; - public interface ILiquidTankContainer extends IFluidHandler { - ForestryTank[] getTanks(); - + TankManager getTankManager(); + void getGUINetworkData(int messageId, int data); + void sendGUINetworkData(Container container, ICrafting iCrafting); + } diff --git a/src/main/java/forestry/core/items/ItemCrated.java b/src/main/java/forestry/core/items/ItemCrated.java index d244a7935..1a20d8510 100755 --- a/src/main/java/forestry/core/items/ItemCrated.java +++ b/src/main/java/forestry/core/items/ItemCrated.java @@ -81,13 +81,13 @@ public class ItemCrated extends Item implements IGenericCrate { return itemstack; } -// @Override -// public String getItemStackDisplayName(ItemStack itemstack) { -// if (contained != null) -// return StringUtil.localize("item.crated.adj") + " " + Proxies.common.getDisplayName(contained); -// else -// return StringUtil.localize("item.crated.unknown"); -// } + @Override + public String getItemStackDisplayName(ItemStack itemstack) { + if (contained != null) + return StringUtil.localize("item.crated.adj") + " " + Proxies.common.getDisplayName(contained); + else + return StringUtil.localize("item.crated.unknown"); + } @SideOnly(Side.CLIENT) @Override diff --git a/src/main/java/forestry/core/items/ItemForestryBlock.java b/src/main/java/forestry/core/items/ItemForestryBlock.java index 1a003bf76..9aba23515 100755 --- a/src/main/java/forestry/core/items/ItemForestryBlock.java +++ b/src/main/java/forestry/core/items/ItemForestryBlock.java @@ -10,9 +10,12 @@ ******************************************************************************/ package forestry.core.items; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; public class ItemForestryBlock extends ItemBlock { @@ -31,6 +34,12 @@ public class ItemForestryBlock extends ItemBlock { return field_150939_a; } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIconFromDamage(int meta) { + return this.getBlock().getIcon(1, meta); + } + @Override public String getUnlocalizedName(ItemStack itemstack) { return getBlock().getUnlocalizedName() + "." + itemstack.getItemDamage(); diff --git a/src/main/java/forestry/core/items/ItemForestryFood.java b/src/main/java/forestry/core/items/ItemForestryFood.java index d55d353ab..d490402ac 100755 --- a/src/main/java/forestry/core/items/ItemForestryFood.java +++ b/src/main/java/forestry/core/items/ItemForestryFood.java @@ -10,55 +10,31 @@ ******************************************************************************/ package forestry.core.items; -import net.minecraft.entity.player.EntityPlayer; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.core.render.TextureManager; +import forestry.core.utils.StringUtil; +import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.item.EnumAction; +import net.minecraft.item.ItemFood; import net.minecraft.item.ItemStack; -import net.minecraft.potion.PotionEffect; -import net.minecraft.world.World; import forestry.core.CreativeTabForestry; -public class ItemForestryFood extends ItemForestry { +public class ItemForestryFood extends ItemFood { - private boolean isAlwaysEdible = false; private boolean isDrink = false; - private int healAmount = 0; - private final float saturationModifier; - - private int potionId; - private int potionDuration; - private int potionAmplifier; - private float potionEffectProbability; - public ItemForestryFood(int heal) { this(heal, 0.6f); } public ItemForestryFood(int heal, float saturation) { - super(); - healAmount = heal; - saturationModifier = saturation; + super(heal, saturation, false); setCreativeTab(CreativeTabForestry.tabForestry); } - @Override - public ItemStack onEaten(ItemStack itemstack, World world, EntityPlayer entityplayer) { - itemstack.stackSize--; - entityplayer.getFoodStats().addStats(healAmount, saturationModifier); - world.playSoundAtEntity(entityplayer, "random.burp", 0.5F, world.rand.nextFloat() * 0.1F + 0.9F); - if (!world.isRemote && potionId > 0 && world.rand.nextFloat() < potionEffectProbability) - entityplayer.addPotionEffect(new PotionEffect(potionId, potionDuration * 20, potionAmplifier)); - - return itemstack; - } - - @Override - public int getMaxItemUseDuration(ItemStack itemstack) { - return 32; - } - @Override public EnumAction getItemUseAction(ItemStack itemstack) { if (isDrink) @@ -67,29 +43,15 @@ public class ItemForestryFood extends ItemForestry { return EnumAction.eat; } - @Override - public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { - if (entityplayer.canEat(isAlwaysEdible)) - entityplayer.setItemInUse(itemstack, getMaxItemUseDuration(itemstack)); - return itemstack; - } - public ItemForestryFood setIsDrink() { isDrink = true; return this; } - public ItemForestryFood setPotionEffect(int i, int j, int k, float f) { - potionId = i; - potionDuration = j; - potionAmplifier = k; - potionEffectProbability = f; - return this; - } - - public ItemForestryFood setAlwaysEdible() { - isAlwaysEdible = true; - return this; + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(IIconRegister register) { + itemIcon = TextureManager.getInstance().registerTex(register, StringUtil.cleanItemName(this)); } } diff --git a/src/main/java/forestry/core/items/ItemTypedBlock.java b/src/main/java/forestry/core/items/ItemTypedBlock.java new file mode 100644 index 000000000..556ee28b5 --- /dev/null +++ b/src/main/java/forestry/core/items/ItemTypedBlock.java @@ -0,0 +1,30 @@ +package forestry.core.items; + +import forestry.core.IItemTyped; +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; + +/** + * For blocks whose type depends on metadata. + * This allows control over which localized name maps to which meta value. + */ +public class ItemTypedBlock extends ItemForestryBlock { + + public ItemTypedBlock(Block block) { + super(block); + } + + @Override + public String getUnlocalizedName(ItemStack itemstack) { + Block block = getBlock(); + if (block instanceof IItemTyped) { + IItemTyped blockTyped = (IItemTyped)block; + Enum type = blockTyped.getTypeFromMeta(itemstack.getItemDamage()); + if (type != null) + return getBlock().getUnlocalizedName() + "." + type.ordinal(); + else + return null; + } + return super.getUnlocalizedName(itemstack); + } +} diff --git a/src/main/java/forestry/core/network/ClassMap.java b/src/main/java/forestry/core/network/ClassMap.java index bac3e53c8..d22e4b926 100755 --- a/src/main/java/forestry/core/network/ClassMap.java +++ b/src/main/java/forestry/core/network/ClassMap.java @@ -76,10 +76,13 @@ public class ClassMap { } for (Field member : gameProfileMember) { GameProfile profile = (GameProfile) member.get(obj); - intPayload[index.intIndex] = (int) (profile.getId().getMostSignificantBits() >>> 32); - intPayload[index.intIndex + 1] = (int) profile.getId().getMostSignificantBits(); - intPayload[index.intIndex + 2] = (int) (profile.getId().getLeastSignificantBits() >>> 32); - intPayload[index.intIndex + 3] = (int) profile.getId().getLeastSignificantBits(); + UUID profileID = profile.getId(); + if (profileID == null) + profileID = new UUID(0,0); + intPayload[index.intIndex] = (int) profileID.getMostSignificantBits() >>> 32; + intPayload[index.intIndex + 1] = (int) profileID.getMostSignificantBits(); + intPayload[index.intIndex + 2] = (int) profileID.getLeastSignificantBits() >>> 32; + intPayload[index.intIndex + 3] = (int) profileID.getLeastSignificantBits(); index.intIndex += 4; stringPayload[index.stringIndex] = profile.getName(); index.stringIndex++; diff --git a/src/main/java/forestry/core/network/PacketGuiInteger.java b/src/main/java/forestry/core/network/PacketGuiInteger.java new file mode 100644 index 000000000..7b7ff9eb7 --- /dev/null +++ b/src/main/java/forestry/core/network/PacketGuiInteger.java @@ -0,0 +1,63 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network; + +import cpw.mods.fml.client.FMLClientHandler; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; + +import net.minecraft.client.entity.EntityClientPlayerMP; + +/** + * + * @author CovertJaguar + */ + +public class PacketGuiInteger extends ForestryPacket { + + private int windowId, dataId, value; + + public PacketGuiInteger() { + super(); + } + + public PacketGuiInteger(int windowId, int dataId, int value) { + this.windowId = windowId; + this.dataId = dataId; + this.value = value; + } + + @Override + public void writeData(DataOutputStream data) throws IOException { + data.writeByte(windowId); + data.writeByte(dataId); + data.writeInt(value); + } + + @Override + public void readData(DataInputStream data) throws IOException { + windowId = data.readByte(); + dataId = data.readByte(); + value = data.readInt(); + + EntityClientPlayerMP player = FMLClientHandler.instance().getClient().thePlayer; + + if (player.openContainer != null && player.openContainer.windowId == windowId) + player.openContainer.updateProgressBar(dataId, value); + } + + @Override + public int getID() { + return PacketIds.GUI_INTEGER; + } + +} diff --git a/src/main/java/forestry/core/network/PacketHandler.java b/src/main/java/forestry/core/network/PacketHandler.java index 18decd213..0a796444e 100755 --- a/src/main/java/forestry/core/network/PacketHandler.java +++ b/src/main/java/forestry/core/network/PacketHandler.java @@ -141,10 +141,9 @@ public class PacketHandler { packetTR.readData(data); onGenomeTrackerUpdate(packetTR); break; - case PacketIds.TANK_UPDATE: - PacketTankUpdate packetAB = new PacketTankUpdate(); - packetAB.readData(data); - onTankUpdate(packetAB); + case PacketIds.GUI_INTEGER: + PacketGuiInteger packet = new PacketGuiInteger(); + packet.readData(data); break; default: for (forestry.core.interfaces.IPacketHandler handler : PluginManager.packetHandlers) @@ -168,17 +167,6 @@ public class PacketHandler { channel.sendTo(packet, player); } - - private void onTankUpdate(PacketTankUpdate packetAB) { - assert FMLCommonHandler.instance().getEffectiveSide().isClient(); - - EntityPlayer player = Proxies.common.getPlayer(); - - if (player.openContainer instanceof ContainerForestry) { - ((ContainerForestry)player.openContainer).onTankUpdate(packetAB.nbttagcompound); - } - } - private void onGenomeTrackerUpdate(PacketNBT packet) { assert FMLCommonHandler.instance().getEffectiveSide().isClient(); diff --git a/src/main/java/forestry/core/network/PacketIds.java b/src/main/java/forestry/core/network/PacketIds.java index 5139f513a..b35aa1d58 100755 --- a/src/main/java/forestry/core/network/PacketIds.java +++ b/src/main/java/forestry/core/network/PacketIds.java @@ -42,13 +42,13 @@ public class PacketIds { public static final int LETTER_RECIPIENT = 80; public static final int LETTER_TEXT = 81; public static final int TRADING_ADDRESS_SET = 82; - public static final int TRADING_INFO = 83; + public static final int LETTER_INFO = 83; public static final int POBOX_INFO = 85; public static final int POBOX_INFO_REQUEST = 86; public static final int LEAF_UPDATE = 90; - public static final int TANK_UPDATE = 91; + public static final int GUI_INTEGER = 92; // Propolis pipe public static final int PROP_SEND_FILTER_SET = 100; diff --git a/src/main/java/forestry/core/network/PacketTankUpdate.java b/src/main/java/forestry/core/network/PacketTankUpdate.java deleted file mode 100755 index bec6e939d..000000000 --- a/src/main/java/forestry/core/network/PacketTankUpdate.java +++ /dev/null @@ -1,31 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network; - -import net.minecraft.nbt.NBTTagCompound; - -import forestry.core.utils.ForestryTank; - -public class PacketTankUpdate extends PacketNBT { - - public PacketTankUpdate(int tankSlot, ForestryTank tank) { - super(PacketIds.TANK_UPDATE); - NBTTagCompound nbt = new NBTTagCompound(); - nbt.setByte("tank", (byte) tankSlot); - nbt.setShort("capacity", (short) tank.getCapacity()); - tank.writeToNBT(nbt); - this.nbttagcompound = nbt; - } - - public PacketTankUpdate() { - } - -} diff --git a/src/main/java/forestry/core/proxy/ClientProxyCommon.java b/src/main/java/forestry/core/proxy/ClientProxyCommon.java index 7dbe1a2f6..bab31f684 100755 --- a/src/main/java/forestry/core/proxy/ClientProxyCommon.java +++ b/src/main/java/forestry/core/proxy/ClientProxyCommon.java @@ -12,6 +12,8 @@ package forestry.core.proxy; import java.io.File; +import com.mojang.authlib.GameProfile; + import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; @@ -23,6 +25,9 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; +import net.minecraft.world.WorldServer; + +import net.minecraftforge.common.util.FakePlayerFactory; import org.lwjgl.input.Keyboard; @@ -90,6 +95,17 @@ public class ClientProxyCommon extends ProxyCommon { return true; } + @Override + public EntityPlayer getPlayer(World world, GameProfile profile) { + EntityPlayer player = world.getPlayerEntityByName(profile.getName()); + if (player != null) + return player; + else if (world instanceof WorldServer) + return FakePlayerFactory.get((WorldServer) world, profile); + else + return null; + } + @Override public double getBlockReachDistance(EntityPlayer entityplayer) { if (entityplayer instanceof EntityPlayerSP) diff --git a/src/main/java/forestry/core/proxy/ProxyCommon.java b/src/main/java/forestry/core/proxy/ProxyCommon.java index 6a762abf9..61ee87411 100755 --- a/src/main/java/forestry/core/proxy/ProxyCommon.java +++ b/src/main/java/forestry/core/proxy/ProxyCommon.java @@ -12,6 +12,8 @@ package forestry.core.proxy; import java.io.File; +import com.mojang.authlib.GameProfile; + import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.IResourceManager; @@ -31,7 +33,14 @@ import cpw.mods.fml.client.FMLClientHandler; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.registry.GameRegistry; +import cpw.mods.fml.common.ModContainer; +import cpw.mods.fml.common.versioning.ArtifactVersion; +import cpw.mods.fml.common.versioning.DefaultArtifactVersion; +import cpw.mods.fml.common.versioning.VersionParser; +import cpw.mods.fml.common.versioning.VersionRange; +import net.minecraft.world.WorldServer; +import net.minecraftforge.common.util.FakePlayerFactory; import net.minecraftforge.oredict.ShapedOreRecipe; import net.minecraftforge.oredict.ShapelessOreRecipe; @@ -148,6 +157,19 @@ public class ProxyCommon { return server.getConfigurationManager().func_152596_g(player.getGameProfile()); } + /** + * Get a player for a given World and GameProfile. + * If they are not in the World, returns a FakePlayer. + * Do not store references to the return value, to prevent worlds staying in memory. + */ + public EntityPlayer getPlayer(World world, GameProfile profile) { + EntityPlayer player = world.getPlayerEntityByName(profile.getName()); + if (player != null) + return player; + else + return FakePlayerFactory.get((WorldServer)world, profile); + } + public double getBlockReachDistance(EntityPlayer entityplayer) { return 4f; } @@ -237,9 +259,31 @@ public class ProxyCommon { return Loader.isModLoaded(modname); } - public Object instantiateIfModLoaded(String modname, String className) { + public boolean isModLoaded(String modname, String versionRangeString) { + if (!isModLoaded(modname)) + return false; - if (isModLoaded(modname)) + if (versionRangeString != null) { + ModContainer mod = Loader.instance().getIndexedModList().get(modname); + ArtifactVersion modVersion = mod.getProcessedVersion(); + + VersionRange versionRange = VersionParser.parseRange(versionRangeString); + DefaultArtifactVersion requiredVersion = new DefaultArtifactVersion(modname, versionRange); + + if (!requiredVersion.containsVersion(modVersion)) + return false; + } + + return true; + } + + public Object instantiateIfModLoaded(String modname, String className) { + return instantiateIfModLoaded(modname, null, className); + } + + public Object instantiateIfModLoaded(String modname, String versionRangeString, String className) { + + if (isModLoaded(modname, versionRangeString)) try { Class clas = Class.forName(className, true, Loader.instance().getModClassLoader()); return clas.newInstance(); diff --git a/src/main/java/forestry/core/proxy/ProxyNetwork.java b/src/main/java/forestry/core/proxy/ProxyNetwork.java index f13fd1e63..516c76eaa 100755 --- a/src/main/java/forestry/core/proxy/ProxyNetwork.java +++ b/src/main/java/forestry/core/proxy/ProxyNetwork.java @@ -15,6 +15,7 @@ import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.world.World; import net.minecraftforge.common.DimensionManager; +import net.minecraftforge.common.util.FakePlayer; import forestry.Forestry; import forestry.core.config.Defaults; @@ -38,7 +39,7 @@ public class ProxyNetwork { } public void sendToPlayer(ForestryPacket packet, EntityPlayer entityplayer) { - if (!(entityplayer instanceof EntityPlayerMP)) + if (!(entityplayer instanceof EntityPlayerMP) || (entityplayer instanceof FakePlayer)) return; EntityPlayerMP player = (EntityPlayerMP) entityplayer; diff --git a/src/main/java/forestry/core/utils/AlyzerInventory.java b/src/main/java/forestry/core/utils/AlyzerInventory.java new file mode 100644 index 000000000..398ab4764 --- /dev/null +++ b/src/main/java/forestry/core/utils/AlyzerInventory.java @@ -0,0 +1,45 @@ +package forestry.core.utils; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; + +public class AlyzerInventory extends ItemInventory { + + public static final int SLOT_SPECIMEN = 0; + public static final int SLOT_ANALYZE_1 = 1; + public static final int SLOT_ANALYZE_2 = 2; + public static final int SLOT_ANALYZE_3 = 3; + public static final int SLOT_ANALYZE_4 = 4; + public static final int SLOT_ANALYZE_5 = 6; + public static final int SLOT_ENERGY = 5; + + protected EntityPlayer player; + + public AlyzerInventory(Class itemClass, int slots) { + super(itemClass, slots); + } + + public AlyzerInventory(Class itemClass, int size, ItemStack itemstack) { + super(itemClass, size, itemstack); + } + + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + + NBTTagList nbttaglist = new NBTTagList(); + for (int i = SLOT_ENERGY; i < SLOT_ENERGY + 1; i++) { + if (inventoryStacks[i] != null) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + nbttagcompound1.setByte("Slot", (byte) i); + inventoryStacks[i].writeToNBT(nbttagcompound1); + nbttaglist.appendTag(nbttagcompound1); + } + } + nbttagcompound.setTag("Items", nbttaglist); + + } + +} diff --git a/src/main/java/forestry/core/utils/ForestryTank.java b/src/main/java/forestry/core/utils/ForestryTank.java deleted file mode 100755 index a80d3ae57..000000000 --- a/src/main/java/forestry/core/utils/ForestryTank.java +++ /dev/null @@ -1,86 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.utils; - -import java.util.Locale; - -import net.minecraft.item.EnumRarity; - -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTank; -import net.minecraftforge.fluids.FluidTankInfo; - -import forestry.core.config.Config; -import forestry.core.gui.tooltips.ToolTip; -import forestry.core.gui.tooltips.ToolTipLine; - -public class ForestryTank extends FluidTank { - - public static final ForestryTank FAKETANK = new ForestryTank(0); - public static final ForestryTank[] FAKETANK_ARRAY = new ForestryTank[] { FAKETANK }; - public static final FluidTankInfo DUMMY_TANK_INFO = new FluidTankInfo(FAKETANK); - public static final FluidTankInfo[] DUMMY_TANKINFO_ARRAY = new FluidTankInfo[] { DUMMY_TANK_INFO }; - - public ForestryTank(FluidStack stack, int capacity) { - super(stack, capacity); - } - - public ForestryTank(int capacity) { - super(capacity); - } - - public ForestryTank(Fluid fluid, int amount, int capacity) { - super(fluid, amount, capacity); - } - - public boolean isEmpty() { - return getFluid() == null || getFluid().amount <= 0; - } - - public boolean isFull() { - return getFluid() != null && getFluid().amount == getCapacity(); - } - - public Fluid getFluidType() { - return getFluid() != null ? getFluid().getFluid() : null; - } - - @Override - public String toString() { - return String.format("Tank: %s, %d/%d", fluid != null && fluid.getFluid() != null ? fluid.getFluid().getName() : "Empty", getFluidAmount(), getCapacity()); - } - - public ToolTip getToolTip() { - return toolTip; - } - protected final ToolTip toolTip = new ToolTip() { - @Override - public void refresh() { - toolTip.clear(); - int amount = 0; - if (getFluid() != null && getFluid().amount > 0 && getFluid().getFluid() != null) { - Fluid fluidType = getFluidType(); - EnumRarity rarity = fluidType.getRarity(); - if (rarity == null) - rarity = EnumRarity.common; - ToolTipLine fluidName = new ToolTipLine(fluidType.getLocalizedName(getFluid()), rarity.rarityColor); - fluidName.setSpacing(2); - toolTip.add(fluidName); - amount = getFluid().amount; - } else { - toolTip.add(new ToolTipLine(StringUtil.localize("gui.empty"))); - } - if (Config.tooltipLiquidAmount) - toolTip.add(new ToolTipLine(String.format(Locale.ENGLISH, "%,d / %,d", amount, getCapacity()))); - } - }; -} diff --git a/src/main/java/forestry/core/utils/InventoryAdapter.java b/src/main/java/forestry/core/utils/InventoryAdapter.java index e037d953f..084586f21 100755 --- a/src/main/java/forestry/core/utils/InventoryAdapter.java +++ b/src/main/java/forestry/core/utils/InventoryAdapter.java @@ -76,17 +76,20 @@ public class InventoryAdapter implements IInventory, INBTTagable { } public boolean tryAddStacksCopy(ItemStack[] stacks, boolean all) { + return tryAddStacksCopy(stacks, 0, this.getSizeInventory(), all); + } + + public boolean tryAddStacksCopy(ItemStack[] stacks, int startSlot, int slots, boolean all) { - boolean addedAll = true; for (ItemStack stack : stacks) { if (stack == null) continue; - if (!tryAddStack(stack.copy(), all)) - addedAll = false; + if (!tryAddStack(stack.copy(), startSlot, slots, all)) + return false; } - return addedAll; + return true; } public boolean tryAddStacks(ItemStack[] stacks, boolean all) { @@ -121,7 +124,11 @@ public class InventoryAdapter implements IInventory, INBTTagable { } public boolean tryAddStack(ItemStack stack, int startSlot, int slots, boolean all, boolean doAdd) { - return addStack(stack, startSlot, slots, all, doAdd) > 0; + int added = addStack(stack, startSlot, slots, all, doAdd); + if (all) + return added == stack.stackSize; + else + return added > 0; } public int addStack(ItemStack stack, boolean all, boolean doAdd) { @@ -184,68 +191,60 @@ public class InventoryAdapter implements IInventory, INBTTagable { /* CONTAINS */ public boolean contains(ItemStack[] query, int startSlot, int slots) { - for (ItemStack queried : query) { - - int itemCount = 0; - for (int i = startSlot; i < startSlot + slots; i++) { - ItemStack stack = inventory.getStackInSlot(i); - - if (stack == null) - continue; - - if (StackUtils.equals(Blocks.air, queried)) { - itemCount += stack.stackSize; - continue; - } - if (queried.getItemDamage() < 0) { - - if (stack.getItem() == queried.getItem()) - itemCount += stack.stackSize; - continue; - } - - if (stack.isItemEqual(queried) && ItemStack.areItemStackTagsEqual(stack, queried)) - itemCount += stack.stackSize; - } - - if (itemCount < queried.stackSize) - return false; - - } - - return true; + ItemStack[] stock = getStacks(startSlot, slots); + return StackUtils.containsSets(query, stock) > 0; } /* REMOVAL */ - public void removeResources(ItemStack[] query, int startSlot, int slots) { - for (ItemStack queried : query) { + /** + * Removes a set of items from an inventory. + * Removes the exact items first if they exist, and then removes crafting equivalents. + * If the inventory doesn't have all the required items, returns false without removing anything. + * If stowContainer is true, items with containers will have their container stowed. + */ + public boolean removeSets(int count, ItemStack[] set, int firstSlotIndex, int slotCount, EntityPlayer player, boolean stowContainer, boolean oreDictionary, boolean craftingTools) { - ItemStack remain = queried.copy(); + ItemStack[] condensedSet = StackUtils.condenseStacks(set, -1, false); - for (int i = startSlot; i < startSlot + slots; i++) { - ItemStack stack = inventory.getStackInSlot(i); + ItemStack[] stock = getStacks(firstSlotIndex, slotCount); + if (StackUtils.containsSets(condensedSet, stock, oreDictionary, craftingTools) < count) + return false; - if (stack == null) - continue; + for (ItemStack stackToRemove : condensedSet) { + stackToRemove.stackSize *= count; - if (queried.getItemDamage() < 0) { - - if (stack.getItem() == queried.getItem()) { - ItemStack removed = decrStackSize(i, remain.stackSize); - remain.stackSize -= removed.stackSize; - } - - } else if (stack.isItemEqual(remain) && ItemStack.areItemStackTagsEqual(stack, remain)) { - ItemStack removed = decrStackSize(i, remain.stackSize); - remain.stackSize -= removed.stackSize; - } - - if (remain.stackSize <= 0) - break; - } + // try to remove the exact stack first + removeStack(stackToRemove, firstSlotIndex, slotCount, player, stowContainer, false, false); + // remove crafting equivalents next + if (stackToRemove.stackSize > 0) + removeStack(stackToRemove, firstSlotIndex, slotCount, player, stowContainer, oreDictionary, craftingTools); } + return true; + } + /** + * Private Helper for removeSetsFromInventory. Assumes removal is possible. + */ + private void removeStack(ItemStack stackToRemove, int firstSlotIndex, int slotCount, EntityPlayer player, boolean stowContainer, boolean oreDictionary, boolean craftingTools) { + for (int j = firstSlotIndex; j < firstSlotIndex + slotCount; j++) { + ItemStack stackInSlot = getStackInSlot(j); + if (stackInSlot == null) + continue; + + if (!StackUtils.isCraftingEquivalent(stackToRemove, stackInSlot, oreDictionary, craftingTools)) + continue; + + + ItemStack removed = decrStackSize(j, stackToRemove.stackSize); + stackToRemove.stackSize -= removed.stackSize; + + if (stowContainer && stackToRemove.getItem().hasContainerItem(stackToRemove)) + StackUtils.stowContainerItem(removed, this, j, player); + + if (stackToRemove.stackSize == 0) + return; + } } /* IINVENTORY */ diff --git a/src/main/java/forestry/core/utils/ItemInventory.java b/src/main/java/forestry/core/utils/ItemInventory.java index da4da269e..e7fcb75ff 100755 --- a/src/main/java/forestry/core/utils/ItemInventory.java +++ b/src/main/java/forestry/core/utils/ItemInventory.java @@ -42,7 +42,7 @@ public class ItemInventory implements IInventory, INBTTagable { isItemInventory = true; // Set an uid to identify the itemstack on SMP - setUID(true); + setUID(false); readFromNBT(itemstack.getTagCompound()); } diff --git a/src/main/java/forestry/core/utils/NBTUtil.java b/src/main/java/forestry/core/utils/NBTUtil.java new file mode 100644 index 000000000..03ee22182 --- /dev/null +++ b/src/main/java/forestry/core/utils/NBTUtil.java @@ -0,0 +1,77 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.utils; + +import com.google.common.collect.ForwardingList; +import cpw.mods.fml.common.ObfuscationReflectionHelper; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.nbt.*; + +/** + * + * @author CovertJaguar + */ +public class NBTUtil { + + public enum EnumNBTType { + + END(NBTTagEnd.class), + BYTE(NBTTagByte.class), + SHORT(NBTTagShort.class), + INT(NBTTagInt.class), + LONG(NBTTagLong.class), + FLOAT(NBTTagFloat.class), + DOUBLE(NBTTagDouble.class), + BYTE_ARRAY(NBTTagByteArray.class), + STRING(NBTTagString.class), + LIST(NBTTagList.class), + COMPOUND(NBTTagCompound.class), + INT_ARRAY(NBTTagIntArray.class); + public static final EnumNBTType[] VALUES = values(); + public final Class classObject; + + private EnumNBTType(Class c) { + this.classObject = c; + } + + public static EnumNBTType fromClass(Class c) { + for (EnumNBTType type : VALUES) { + if (type.classObject == c) + return type; + } + return null; + } + + } + + public static NBTList getNBTList(NBTTagCompound nbt, String tag, EnumNBTType type) { + NBTTagList nbtList = nbt.getTagList(tag, type.ordinal()); + return new NBTList(nbtList); + } + + public static class NBTList extends ForwardingList { + + private final ArrayList backingList; + private final NBTTagList nbtList; + + public NBTList(NBTTagList nbtList) { + this.nbtList = nbtList; + backingList = ObfuscationReflectionHelper.getPrivateValue(NBTTagList.class, nbtList, 0); + } + + @Override + protected List delegate() { + return backingList; + } + + } +} diff --git a/src/main/java/forestry/core/utils/StackMap.java b/src/main/java/forestry/core/utils/StackMap.java index 184fee1f0..3e4bbbc66 100755 --- a/src/main/java/forestry/core/utils/StackMap.java +++ b/src/main/java/forestry/core/utils/StackMap.java @@ -21,10 +21,10 @@ import java.util.Map; * @param The thing this map maps onto * @param

The stack class (i.e. ItemStack, FluidStack) used for lookups */ -public abstract class StackMap extends HashMap{ +public abstract class StackMap extends HashMap{ @Override - public final T put(Object key, T value) { + public final T put(P key, T value) { if(isValidKey(key) && key != null && value != null) return super.put(key, value); return null; @@ -36,7 +36,7 @@ public abstract class StackMap extends HashMap{ public final boolean containsKey(Object key) { P stack = getStack(key); if(stack == null) return false; - for (Map.Entry entry : this.entrySet()) + for (Map.Entry entry : this.entrySet()) if (areEqual(stack, entry.getKey())) return true; return super.containsKey(key); @@ -46,7 +46,7 @@ public abstract class StackMap extends HashMap{ public final T get(Object key) { P stack = getStack(key); if(stack == null) return null; - for (Map.Entry entry : this.entrySet()) + for (Map.Entry entry : this.entrySet()) if (areEqual(stack, entry.getKey())) return entry.getValue(); return super.get(key); diff --git a/src/main/java/forestry/core/utils/StackUtils.java b/src/main/java/forestry/core/utils/StackUtils.java index a46e2a1dc..fda13c15c 100755 --- a/src/main/java/forestry/core/utils/StackUtils.java +++ b/src/main/java/forestry/core/utils/StackUtils.java @@ -29,6 +29,7 @@ import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData; import net.minecraftforge.oredict.OreDictionary; import forestry.core.config.Defaults; +import forestry.core.fluids.tanks.StandardTank; import forestry.core.gadgets.TileForestry; public class StackUtils { @@ -193,7 +194,7 @@ public class StackUtils { * without decreasing the source stack. * * @param stack - * @param i + * @param amount * @return */ public static ItemStack createSplitStack(ItemStack stack, int amount) { @@ -254,7 +255,7 @@ public class StackUtils { * @return */ public static int containsSets(ItemStack[] set, ItemStack[] stock) { - return containsSets(set, stock, null, false, false); + return containsSets(set, stock, false, false); } /** @@ -264,10 +265,10 @@ public class StackUtils { * @param stock * @return */ - public static int containsSets(ItemStack[] set, ItemStack[] stock, ItemStack exclude, boolean oreDictionary, boolean craftingTools) { + public static int containsSets(ItemStack[] set, ItemStack[] stock, boolean oreDictionary, boolean craftingTools) { int count = 0; - ItemStack[] condensedRequired = StackUtils.condenseStacks(set); + ItemStack[] condensedRequired = StackUtils.condenseStacks(set, -1, oreDictionary); ItemStack[] condensedOffered = StackUtils.condenseStacks(stock, -1, oreDictionary); for (ItemStack req : condensedRequired) { @@ -275,9 +276,6 @@ public class StackUtils { boolean matched = false; for (ItemStack offer : condensedOffered) { - if (exclude != null && isIdenticalItem(offer, exclude)) - continue; - if (isCraftingEquivalent(req, offer, oreDictionary, craftingTools)) { matched = true; @@ -297,6 +295,27 @@ public class StackUtils { return count; } + /** + * Compare two item stacks for crafting equivalency without oreDictionary or craftingTools + */ + public static boolean isCraftingEquivalent(ItemStack base, ItemStack comparison) { + if (base == null || comparison == null) + return false; + + if (base.getItem() != comparison.getItem()) + return false; + + if (base.getItemDamage() != Defaults.WILDCARD) + if (base.getItemDamage() != comparison.getItemDamage()) + return false; + + // When the base stackTagCompound is null or empty, treat it as a wildcard for crafting + if (base.stackTagCompound == null || base.stackTagCompound.hasNoTags()) + return true; + else + return ItemStack.areItemStackTagsEqual(base, comparison); + } + /** * Compare two item stacks for crafting equivalency. * @@ -306,9 +325,12 @@ public class StackUtils { * @return */ public static boolean isCraftingEquivalent(ItemStack base, ItemStack comparison, boolean oreDictionary, boolean craftingTools) { - if (isIdenticalItem(base, comparison)) + if (isCraftingEquivalent(base, comparison)) return true; + if (base == null || comparison == null) + return false; + if (oreDictionary) { int[] idsBase = OreDictionary.getOreIDs(base); for (int idBase : idsBase) { @@ -376,12 +398,12 @@ public class StackUtils { } - public static void replenishByContainer(TileForestry tile, ItemStack inventoryStack, ForestryTank tank) { + public static void replenishByContainer(TileForestry tile, ItemStack inventoryStack, StandardTank tank) { FluidContainerData container = LiquidHelper.getLiquidContainer(inventoryStack); replenishByContainer(tile, inventoryStack, container, tank); } - public static ItemStack replenishByContainer(TileForestry tile, ItemStack inventoryStack, FluidContainerData container, ForestryTank tank) { + public static ItemStack replenishByContainer(TileForestry tile, ItemStack inventoryStack, FluidContainerData container, StandardTank tank) { if (container == null) return inventoryStack; diff --git a/src/main/java/forestry/core/utils/StringUtil.java b/src/main/java/forestry/core/utils/StringUtil.java index f459b8af0..f8b44e465 100755 --- a/src/main/java/forestry/core/utils/StringUtil.java +++ b/src/main/java/forestry/core/utils/StringUtil.java @@ -22,14 +22,12 @@ public class StringUtil { return StatCollector.translateToLocal("for." + key).replace("\\n", "\n").replace("@", "%").replace("\\%", "@"); } - public static String localizeAndFormat(String key, Object... args) { - String text = StringUtil.localize(key); + public static String localizeTile(String key) { + return StatCollector.translateToLocal("tile.for." + key).replace("\\n", "\n").replace("@", "%").replace("\\%", "@"); + } - try { - return String.format(text, args); - } catch (IllegalFormatException ex) { - return "Format error: " + text; - } + public static String localizeAndFormat(String key, Object... args) { + return localizeAndFormatRaw("for." + key, args); } /** diff --git a/src/main/java/forestry/core/utils/Utils.java b/src/main/java/forestry/core/utils/Utils.java index 7aa851825..69344aaa5 100755 --- a/src/main/java/forestry/core/utils/Utils.java +++ b/src/main/java/forestry/core/utils/Utils.java @@ -60,42 +60,6 @@ import forestry.plugins.PluginArboriculture; public class Utils { - private static EntityPlayer modPlayer; - - public static GameProfile getForestryPlayerProfile() { - return new GameProfile(UUID.nameUUIDFromBytes(Config.fakeUserLogin.getBytes(Charsets.UTF_8)), - Config.fakeUserLogin); - } - - public static EntityPlayer getForestryPlayer(World world, int x, int y, int z) { - if (modPlayer == null) { - modPlayer = new EntityPlayer(world, getForestryPlayerProfile()) { - @Override - public boolean canCommandSenderUseCommand(int var1, String var2) { - return false; - } - - @Override - public ChunkCoordinates getPlayerCoordinates() { - return null; - } - - @Override - public void addChatMessage(IChatComponent var1) { - } - }; - modPlayer.posX = x; - modPlayer.posY = y; - modPlayer.posZ = z; - Proxies.log.info("Created player '%s' for Forestry.", modPlayer.getGameProfile().getId()); - if (Config.fakeUserAutoop) { - MinecraftServer.getServer().getConfigurationManager().func_152605_a(modPlayer.getGameProfile()); - Proxies.log.info("Opped player '%s'.", modPlayer.getGameProfile().getId()); - } - } - - return modPlayer; - } private static Random rand; public static int getUID() { @@ -320,7 +284,7 @@ public class Utils { public static int addRGBComponents(int colour, int r, int g, int b) { r = ((colour & 0xff0000) >> 16) + r; - g = ((colour & 0xff00) >> 8) + b; + g = ((colour & 0xff00) >> 8) + g; b = ((colour & 0xff)) + b; r = r <= 255 ? r : 255; diff --git a/src/main/java/forestry/core/utils/Vect.java b/src/main/java/forestry/core/utils/Vect.java index 3c93fbab0..256b8c2d0 100755 --- a/src/main/java/forestry/core/utils/Vect.java +++ b/src/main/java/forestry/core/utils/Vect.java @@ -51,7 +51,7 @@ public class Vect { @Override public String toString() { - return String.format("%sx%sx%s;", x, y, z); + return String.format("%sx%sx%s", x, y, z); } @Override diff --git a/src/main/java/forestry/energy/circuits/CircuitElectricBoost.java b/src/main/java/forestry/energy/circuits/CircuitElectricBoost.java index 649b6c698..acdad1149 100755 --- a/src/main/java/forestry/energy/circuits/CircuitElectricBoost.java +++ b/src/main/java/forestry/energy/circuits/CircuitElectricBoost.java @@ -12,8 +12,8 @@ package forestry.energy.circuits; public class CircuitElectricBoost extends CircuitElectricChange { - public CircuitElectricBoost(String uid, int limit, int eu, int mj, String name, String[] description) { - super(uid, false, name, description); + public CircuitElectricBoost(String uid, int limit, int eu, int mj) { + super(uid, false); this.setLimit(limit); this.configureChange(eu, mj); } diff --git a/src/main/java/forestry/energy/circuits/CircuitElectricChange.java b/src/main/java/forestry/energy/circuits/CircuitElectricChange.java index 4440fc70e..a438271e0 100755 --- a/src/main/java/forestry/energy/circuits/CircuitElectricChange.java +++ b/src/main/java/forestry/energy/circuits/CircuitElectricChange.java @@ -20,8 +20,8 @@ public abstract class CircuitElectricChange extends Circuit { int euChange = 7; int mjChange = 2; - public CircuitElectricChange(String uid, boolean requiresDiscovery, String name, String[] descriptions) { - super(uid, requiresDiscovery, name, descriptions); + public CircuitElectricChange(String uid, boolean requiresDiscovery) { + super(uid, requiresDiscovery); } protected void configureChange(int euChange, int mjChange) { diff --git a/src/main/java/forestry/energy/circuits/CircuitElectricChoke.java b/src/main/java/forestry/energy/circuits/CircuitElectricChoke.java index b68eca792..e385e9032 100755 --- a/src/main/java/forestry/energy/circuits/CircuitElectricChoke.java +++ b/src/main/java/forestry/energy/circuits/CircuitElectricChoke.java @@ -13,7 +13,7 @@ package forestry.energy.circuits; public class CircuitElectricChoke extends CircuitElectricChange { public CircuitElectricChoke(String uid) { - super(uid, false, "electric.choke.1", new String[] { "Reduces ouput by 1 MJ/t", "Reduces intake by 2 EU/t" }); + super(uid, false); this.configureChange(-2, -1); this.setLimit(1); } diff --git a/src/main/java/forestry/energy/circuits/CircuitElectricEfficiency.java b/src/main/java/forestry/energy/circuits/CircuitElectricEfficiency.java index 3ebc2ce94..29b10cb49 100755 --- a/src/main/java/forestry/energy/circuits/CircuitElectricEfficiency.java +++ b/src/main/java/forestry/energy/circuits/CircuitElectricEfficiency.java @@ -13,7 +13,7 @@ package forestry.energy.circuits; public class CircuitElectricEfficiency extends CircuitElectricChange { public CircuitElectricEfficiency(String uid) { - super(uid, false, "electric.efficiency.1", new String[] { "Reduces intake by 1 EU/t" }); + super(uid, false); this.setLimit(1); this.configureChange(-1, 0); } diff --git a/src/main/java/forestry/energy/circuits/CircuitFireDampener.java b/src/main/java/forestry/energy/circuits/CircuitFireDampener.java index ee78160d6..f8fe35a4e 100755 --- a/src/main/java/forestry/energy/circuits/CircuitFireDampener.java +++ b/src/main/java/forestry/energy/circuits/CircuitFireDampener.java @@ -18,7 +18,7 @@ import forestry.energy.gadgets.EngineCopper; public class CircuitFireDampener extends Circuit { public CircuitFireDampener(String uid) { - super(uid, false, "dampener.1", new String[] { "Reduces maximum output to 1 MJ/t", "Preserves fuel output" }); + super(uid, false); } @Override diff --git a/src/main/java/forestry/energy/gadgets/EngineBronze.java b/src/main/java/forestry/energy/gadgets/EngineBronze.java index c8cdf1801..ebc286a13 100755 --- a/src/main/java/forestry/energy/gadgets/EngineBronze.java +++ b/src/main/java/forestry/energy/gadgets/EngineBronze.java @@ -21,6 +21,7 @@ import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; import forestry.api.core.ForestryAPI; import forestry.api.core.ISpecialInventory; @@ -29,12 +30,14 @@ import forestry.api.fuels.FuelManager; import forestry.core.EnumErrorCode; import forestry.core.config.Config; import forestry.core.config.Defaults; +import forestry.core.fluids.TankManager; +import forestry.core.fluids.tanks.StandardTank; +import forestry.core.fluids.tanks.FilteredTank; import forestry.core.gadgets.Engine; import forestry.core.gadgets.TileBase; import forestry.core.interfaces.ILiquidTankContainer; import forestry.core.network.GuiId; import forestry.core.network.PacketPayload; -import forestry.core.utils.ForestryTank; import forestry.core.utils.LiquidHelper; import forestry.core.utils.TileInventoryAdapter; @@ -65,8 +68,9 @@ public class EngineBronze extends Engine implements ISpecialInventory, ILiquidTa else shutdown = false; } - public ForestryTank fuelTank = new ForestryTank(Defaults.ENGINE_TANK_CAPACITY); - public ForestryTank heatingTank = new ForestryTank(Defaults.ENGINE_TANK_CAPACITY); + public FilteredTank fuelTank; + public FilteredTank heatingTank; + private final TankManager tankManager; private final TileInventoryAdapter inventory; public int burnTime; public int totalTime; @@ -81,6 +85,16 @@ public class EngineBronze extends Engine implements ISpecialInventory, ILiquidTa setHints(Config.hints.get("engine.bronze")); inventory = new TileInventoryAdapter(this, 1, "Items"); + + fuelTank = new FilteredTank(Defaults.ENGINE_TANK_CAPACITY, FuelManager.bronzeEngineFuel.keySet()); + fuelTank.tankMode = StandardTank.TankMode.INPUT; + heatingTank = new FilteredTank(Defaults.ENGINE_TANK_CAPACITY, FluidRegistry.LAVA); + heatingTank.tankMode = StandardTank.TankMode.INPUT; + this.tankManager = new TankManager(fuelTank, heatingTank); + } + + public TankManager getTankManager() { + return tankManager; } @Override @@ -99,11 +113,11 @@ public class EngineBronze extends Engine implements ISpecialInventory, ILiquidTa FluidContainerData container = LiquidHelper.getLiquidContainer(inventory.getStackInSlot(SLOT_CAN)); if (container != null) { - ForestryTank tank = null; + StandardTank tank = null; - if (container.fluid.isFluidEqual(LiquidHelper.getLiquid(Defaults.LIQUID_LAVA, 1))) + if (heatingTank.accepts(container.fluid.getFluid())) tank = heatingTank; - else if (FuelManager.bronzeEngineFuel.containsKey(container.fluid)) + else if (fuelTank.accepts(container.fluid.getFluid())) tank = fuelTank; if (tank != null) { @@ -219,7 +233,7 @@ public class EngineBronze extends Engine implements ISpecialInventory, ILiquidTa * Returns the fuel value (power per cycle) an item of the passed ItemStack * provides * - * @param item + * @param fluid * @return */ private int determineFuelValue(Fluid fluid) { @@ -231,16 +245,31 @@ public class EngineBronze extends Engine implements ISpecialInventory, ILiquidTa /** * - * @param fuelid + * @param fluid * @return Duration of burn cycle of one bucket */ - private int determineBurnTime(Fluid item) { - if (FuelManager.bronzeEngineFuel.containsKey(item)) - return FuelManager.bronzeEngineFuel.get(item).burnDuration; + private int determineBurnTime(Fluid fluid) { + if (FuelManager.bronzeEngineFuel.containsKey(fluid)) + return FuelManager.bronzeEngineFuel.get(fluid).burnDuration; else return 0; } + protected ItemStack replenishByContainer(ItemStack inventoryStack, FluidContainerData container, StandardTank tank) { + if (container == null) + return inventoryStack; + + if (tank.fill(container.fluid, false) >= container.fluid.amount) { + tank.fill(container.fluid, true); + if (container.filledContainer != null && container.filledContainer.getItem().hasContainerItem(container.filledContainer)) + inventoryStack = container.emptyContainer.copy(); + else + inventoryStack.stackSize--; + } + + return inventoryStack; + } + // / STATE INFORMATION @Override public boolean isBurning() { @@ -284,13 +313,7 @@ public class EngineBronze extends Engine implements ISpecialInventory, ILiquidTa currentFluidId = fluid.getID(); } - fuelTank = new ForestryTank(Defaults.ENGINE_TANK_CAPACITY); - heatingTank = new ForestryTank(Defaults.ENGINE_TANK_CAPACITY); - if (nbt.hasKey("FuelSlot")) { - fuelTank.readFromNBT(nbt.getCompoundTag("FuelSlot")); - heatingTank.readFromNBT(nbt.getCompoundTag("HeatingSlot")); - } - + tankManager.readTanksFromNBT(nbt); inventory.readFromNBT(nbt); } @@ -310,21 +333,14 @@ public class EngineBronze extends Engine implements ISpecialInventory, ILiquidTa if (fluid != null) nbt.setString("currentFluid", fluid.getName()); - NBTTagCompound nbtFuelSlot = new NBTTagCompound(); - NBTTagCompound nbtHeatingSlot = new NBTTagCompound(); - - fuelTank.writeToNBT(nbtFuelSlot); - heatingTank.writeToNBT(nbtHeatingSlot); - - nbt.setTag("FuelSlot", nbtFuelSlot); - nbt.setTag("HeatingSlot", nbtHeatingSlot); - + tankManager.writeTanksToNBT(nbt); inventory.writeToNBT(nbt); } /* GUI */ @Override public void getGUINetworkData(int id, int data) { + id -= tankManager.maxMessageId() + 1; switch (id) { case 0: @@ -350,12 +366,13 @@ public class EngineBronze extends Engine implements ISpecialInventory, ILiquidTa @Override public void sendGUINetworkData(Container containerEngine, ICrafting iCrafting) { - iCrafting.sendProgressBarUpdate(containerEngine, 0, burnTime); - iCrafting.sendProgressBarUpdate(containerEngine, 1, totalTime); - iCrafting.sendProgressBarUpdate(containerEngine, 2, currentOutput); - iCrafting.sendProgressBarUpdate(containerEngine, 3, (int) storedEnergy); - iCrafting.sendProgressBarUpdate(containerEngine, 4, heat); - iCrafting.sendProgressBarUpdate(containerEngine, 5, currentFluidId); + int i = tankManager.maxMessageId() + 1; + iCrafting.sendProgressBarUpdate(containerEngine, i, burnTime); + iCrafting.sendProgressBarUpdate(containerEngine, i + 1, totalTime); + iCrafting.sendProgressBarUpdate(containerEngine, i + 2, currentOutput); + iCrafting.sendProgressBarUpdate(containerEngine, i + 3, (int) storedEnergy); + iCrafting.sendProgressBarUpdate(containerEngine, i + 4, heat); + iCrafting.sendProgressBarUpdate(containerEngine, i + 5, currentFluidId); } /* IINVENTORY */ @@ -405,12 +422,9 @@ public class EngineBronze extends Engine implements ISpecialInventory, ILiquidTa return super.isUseableByPlayer(player); } - /** - * TODO: just a specialsource workaround - */ @Override public String getInventoryName() { - return super.getInventoryName(); + return getUnlocalizedName(); } /** @@ -426,6 +440,13 @@ public class EngineBronze extends Engine implements ISpecialInventory, ILiquidTa */ @Override public boolean isItemValidForSlot(int slotIndex, ItemStack itemstack) { + if (slotIndex == SLOT_CAN) { + FluidStack fluid = LiquidHelper.getFluidStackInContainer(itemstack); + if (fluid == null || fluid.amount <= 0) + return false; + return fuelTank.accepts(fluid.getFluid()) || heatingTank.accepts(fluid.getFluid()); + } + return super.isItemValidForSlot(slotIndex, itemstack); } @@ -444,23 +465,36 @@ public class EngineBronze extends Engine implements ISpecialInventory, ILiquidTa return null; } - // / ITANKCONTAINER + // IFluidHandler + @Override public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - // We only accept biomass and water as fuel - int used = 0; - - if (FuelManager.bronzeEngineFuel.containsKey(resource)) - used = fuelTank.fill(resource, doFill); - - if (LiquidHelper.isLiquid(Defaults.LIQUID_LAVA, resource)) - used = heatingTank.fill(resource, doFill); - - return used; + return tankManager.fill(from, resource, doFill); } @Override - public ForestryTank[] getTanks() { - return new ForestryTank[] { fuelTank, heatingTank }; + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return tankManager.drain(from, resource, doDrain); } + + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + return tankManager.drain(from, maxDrain, doDrain); + } + + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return tankManager.canFill(from, fluid); + } + + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return tankManager.canDrain(from, fluid); + } + + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return tankManager.getTankInfo(from); + } + } diff --git a/src/main/java/forestry/energy/gadgets/EngineCopper.java b/src/main/java/forestry/energy/gadgets/EngineCopper.java index 7a0e74f6c..3a3203e1e 100755 --- a/src/main/java/forestry/energy/gadgets/EngineCopper.java +++ b/src/main/java/forestry/energy/gadgets/EngineCopper.java @@ -204,7 +204,7 @@ public class EngineCopper extends Engine implements ISpecialInventory, ISidedInv /** * Returns the fuel value (power per cycle) an item of the passed ItemStack provides * - * @param item + * @param fuel * @return */ private int determineFuelValue(ItemStack fuel) { @@ -217,7 +217,7 @@ public class EngineCopper extends Engine implements ISpecialInventory, ISidedInv /** * Returns the fuel value (power per cycle) an item of the passed ItemStack provides * - * @param item + * @param fuel * @return */ private int determineBurnDuration(ItemStack fuel) { @@ -397,12 +397,9 @@ public class EngineCopper extends Engine implements ISpecialInventory, ISidedInv return super.isUseableByPlayer(player); } - /** - * TODO: just a specialsource workaround - */ @Override public String getInventoryName() { - return super.getInventoryName(); + return getUnlocalizedName(); } /** diff --git a/src/main/java/forestry/energy/gadgets/EngineTin.java b/src/main/java/forestry/energy/gadgets/EngineTin.java index a1f74ec75..b138b889f 100755 --- a/src/main/java/forestry/energy/gadgets/EngineTin.java +++ b/src/main/java/forestry/energy/gadgets/EngineTin.java @@ -311,12 +311,9 @@ public class EngineTin extends Engine implements ISocketable, IInventory { return super.isUseableByPlayer(player); } - /** - * TODO: just a specialsource workaround - */ @Override public String getInventoryName() { - return super.getInventoryName(); + return getUnlocalizedName(); } /** diff --git a/src/main/java/forestry/energy/gadgets/MachineGenerator.java b/src/main/java/forestry/energy/gadgets/MachineGenerator.java index 77444dba4..8527de339 100755 --- a/src/main/java/forestry/energy/gadgets/MachineGenerator.java +++ b/src/main/java/forestry/energy/gadgets/MachineGenerator.java @@ -17,6 +17,7 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData; import net.minecraftforge.fluids.FluidStack; @@ -24,23 +25,27 @@ import ic2.api.energy.prefab.BasicSource; import forestry.api.core.ForestryAPI; import forestry.api.core.ISpecialInventory; +import forestry.api.fuels.FuelManager; import forestry.api.fuels.GeneratorFuel; import forestry.core.EnumErrorCode; import forestry.core.config.Config; import forestry.core.config.Defaults; +import forestry.core.fluids.tanks.StandardTank; +import forestry.core.fluids.tanks.FilteredTank; +import forestry.core.fluids.TankManager; import forestry.core.gadgets.TileBase; import forestry.core.interfaces.ILiquidTankContainer; import forestry.core.interfaces.IRenderableMachine; import forestry.core.network.EntityNetData; import forestry.core.network.GuiId; import forestry.core.utils.EnumTankLevel; -import forestry.core.utils.ForestryTank; import forestry.core.utils.InventoryAdapter; import forestry.core.utils.LiquidHelper; import forestry.core.utils.StackUtils; -import forestry.core.utils.StringUtil; import forestry.core.utils.Utils; import forestry.plugins.PluginIC2; +import net.minecraftforge.fluids.FluidTankInfo; +import net.minecraftforge.fluids.IFluidHandler; public class MachineGenerator extends TileBase implements ISpecialInventory, ILiquidTankContainer, IRenderableMachine { @@ -49,7 +54,8 @@ public class MachineGenerator extends TileBase implements ISpecialInventory, ILi public static final int maxEnergy = 30000; @EntityNetData - public ForestryTank resourceTank = new ForestryTank(Defaults.PROCESSOR_TANK_CAPACITY); + public FilteredTank resourceTank; + private final TankManager tankManager; private int tickCount = 0; InventoryAdapter inventory = new InventoryAdapter(1, "Items"); @@ -58,6 +64,9 @@ public class MachineGenerator extends TileBase implements ISpecialInventory, ILi public MachineGenerator() { setHints(Config.hints.get("generator")); + resourceTank = new FilteredTank(Defaults.PROCESSOR_TANK_CAPACITY, FuelManager.generatorFuel.keySet()); + tankManager = new TankManager(resourceTank); + if (PluginIC2.instance.isAvailable()) { ic2EnergySource = new BasicSource(this, maxEnergy, 1); } @@ -65,7 +74,7 @@ public class MachineGenerator extends TileBase implements ISpecialInventory, ILi @Override public String getInventoryName() { - return StringUtil.localize("engine.3"); + return getUnlocalizedName(); } @Override @@ -79,10 +88,7 @@ public class MachineGenerator extends TileBase implements ISpecialInventory, ILi if (ic2EnergySource != null) ic2EnergySource.writeToNBT(nbttagcompound); - NBTTagCompound NBTresourceSlot = new NBTTagCompound(); - resourceTank.writeToNBT(NBTresourceSlot); - nbttagcompound.setTag("ResourceTank", NBTresourceSlot); - + tankManager.writeTanksToNBT(nbttagcompound); inventory.writeToNBT(nbttagcompound); } @@ -92,10 +98,7 @@ public class MachineGenerator extends TileBase implements ISpecialInventory, ILi if (ic2EnergySource != null) ic2EnergySource.readFromNBT(nbttagcompound); - resourceTank = new ForestryTank(Defaults.PROCESSOR_TANK_CAPACITY); - if (nbttagcompound.hasKey("ResourceTank")) - resourceTank.readFromNBT(nbttagcompound.getCompoundTag("ResourceTank")); - + tankManager.readTanksFromNBT(nbttagcompound); inventory.readFromNBT(nbttagcompound); } @@ -120,7 +123,8 @@ public class MachineGenerator extends TileBase implements ISpecialInventory, ILi if (inventory.getStackInSlot(SLOT_CAN) != null) { FluidContainerData container = LiquidHelper.getLiquidContainer(inventory.getStackInSlot(SLOT_CAN)); if (container != null) - if (GeneratorFuel.fuels.containsKey(container.fluid.fluidID)) { + + if (resourceTank.accepts(container.fluid.getFluid())) { inventory.setInventorySlotContents(SLOT_CAN, StackUtils.replenishByContainer(this, inventory.getStackInSlot(SLOT_CAN), container, resourceTank)); if (inventory.getStackInSlot(SLOT_CAN).stackSize <= 0) inventory.setInventorySlotContents(SLOT_CAN, null); @@ -135,9 +139,8 @@ public class MachineGenerator extends TileBase implements ISpecialInventory, ILi ic2EnergySource.updateEntity(); - if (resourceTank.getFluidAmount() > 0 && - GeneratorFuel.fuels.containsKey(resourceTank.getFluid().fluidID)) { - GeneratorFuel fuel = GeneratorFuel.fuels.get(resourceTank.getFluid().fluidID); + if (resourceTank.getFluidAmount() > 0) { + GeneratorFuel fuel = FuelManager.generatorFuel.get(resourceTank.getFluid()); if (resourceTank.getFluidAmount() >= fuel.fuelConsumed.amount && ic2EnergySource.getFreeCapacity() >= fuel.eu) { @@ -184,17 +187,16 @@ public class MachineGenerator extends TileBase implements ISpecialInventory, ILi /* SMP GUI */ public void getGUINetworkData(int i, int j) { - - switch (i) { - case 0: + int firstMessageId = tankManager.maxMessageId() + 1; + if (i == firstMessageId) { if (ic2EnergySource != null) ic2EnergySource.setEnergyStored(j); - break; } } public void sendGUINetworkData(Container container, ICrafting iCrafting) { + int firstMessageId = tankManager.maxMessageId() + 1; if (ic2EnergySource != null) { - iCrafting.sendProgressBarUpdate(container, 0, (short) ic2EnergySource.getEnergyStored()); + iCrafting.sendProgressBarUpdate(container, firstMessageId, (short) ic2EnergySource.getEnergyStored()); } } @@ -240,7 +242,7 @@ public class MachineGenerator extends TileBase implements ISpecialInventory, ILi if (container == null) return 0; - if (!GeneratorFuel.fuels.containsKey(container.fluid.fluidID)) + if (!FuelManager.generatorFuel.containsKey(container.fluid)) return 0; if (inventory.getStackInSlot(SLOT_CAN) == null) { @@ -269,24 +271,39 @@ public class MachineGenerator extends TileBase implements ISpecialInventory, ILi return null; } - /* ILIQUIDCONTAINER IMPLEMENTATION */ + /* ILiquidTankContainer */ @Override public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - // We only accept water - if (!GeneratorFuel.fuels.containsKey(resource.fluidID)) - return 0; - - int used = resourceTank.fill(resource, doFill); - - if (doFill && used > 0) - // TODO: Slow down updates - sendNetworkUpdate(); - - return used; + return tankManager.fill(from, resource, doFill); } @Override - public ForestryTank[] getTanks() { - return new ForestryTank[] { resourceTank }; + public TankManager getTankManager() { + return tankManager; } + + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return tankManager.drain(from, resource, doDrain); + } + + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + return tankManager.drain(from, maxDrain, doDrain); + } + + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return tankManager.canFill(from, fluid); + } + + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return tankManager.canDrain(from, fluid); + } + + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return tankManager.getTankInfo(from); + } + } diff --git a/src/main/java/forestry/energy/gui/ContainerEngineBronze.java b/src/main/java/forestry/energy/gui/ContainerEngineBronze.java index 1f8433f3d..a7fdf5c87 100755 --- a/src/main/java/forestry/energy/gui/ContainerEngineBronze.java +++ b/src/main/java/forestry/energy/gui/ContainerEngineBronze.java @@ -43,17 +43,4 @@ public class ContainerEngineBronze extends ContainerLiquidTanks { return engine.isUseableByPlayer(entityplayer); } - @Override - public void updateProgressBar(int i, int j) { - engine.getGUINetworkData(i, j); - } - - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); - - for (int i = 0; i < crafters.size(); i++) - engine.sendGUINetworkData(this, (ICrafting) crafters.get(i)); - } - } diff --git a/src/main/java/forestry/energy/gui/ContainerGenerator.java b/src/main/java/forestry/energy/gui/ContainerGenerator.java index 45581741c..8f4f75d35 100755 --- a/src/main/java/forestry/energy/gui/ContainerGenerator.java +++ b/src/main/java/forestry/energy/gui/ContainerGenerator.java @@ -37,19 +37,6 @@ public class ContainerGenerator extends ContainerLiquidTanks { this.addSlot(new Slot(player, i, 8 + i * 18, 142)); } - @Override - public void updateProgressBar(int i, int j) { - tile.getGUINetworkData(i, j); - } - - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); - - for (int i = 0; i < crafters.size(); i++) - tile.sendGUINetworkData(this, (ICrafting) crafters.get(i)); - } - @Override public boolean canInteractWith(EntityPlayer entityplayer) { return tile.isUseableByPlayer(entityplayer); diff --git a/src/main/java/forestry/energy/gui/GuiEngine.java b/src/main/java/forestry/energy/gui/GuiEngine.java index 60e8dd175..5646a44a3 100755 --- a/src/main/java/forestry/energy/gui/GuiEngine.java +++ b/src/main/java/forestry/energy/gui/GuiEngine.java @@ -15,12 +15,12 @@ package forestry.energy.gui; import forestry.core.gadgets.Engine; import forestry.core.gui.ContainerForestry; -import forestry.core.gui.GuiForestry; +import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.Ledger; import forestry.core.render.TextureManager; import forestry.core.utils.StringUtil; -public abstract class GuiEngine extends GuiForestry { +public abstract class GuiEngine extends GuiForestryTitled { protected class EngineLedger extends Ledger { diff --git a/src/main/java/forestry/energy/gui/GuiEngineBronze.java b/src/main/java/forestry/energy/gui/GuiEngineBronze.java index 5b0374c0a..c73d78556 100755 --- a/src/main/java/forestry/energy/gui/GuiEngineBronze.java +++ b/src/main/java/forestry/energy/gui/GuiEngineBronze.java @@ -103,19 +103,15 @@ public class GuiEngineBronze extends GuiEngine { widgetManager.add(new BiogasSlot(this.widgetManager, 30, 47, tile)); } - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - super.drawGuiContainerForegroundLayer(mouseX, mouseY); - String name = StringUtil.localize("tile.for.engine.2"); - this.fontRendererObj.drawString(name, getCenteredOffset(name), 6, fontColor.get("gui.title")); + protected EngineBronze getEngine() { + return (EngineBronze)tile; } @Override protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - EngineBronze engine = (EngineBronze) tile; - int temp = engine.getOperatingTemperatureScaled(16); + int temp = getEngine().getOperatingTemperatureScaled(16); if (temp > 16) temp = 16; if (temp > 0) diff --git a/src/main/java/forestry/energy/gui/GuiEngineCopper.java b/src/main/java/forestry/energy/gui/GuiEngineCopper.java index bea21fa42..df8193097 100755 --- a/src/main/java/forestry/energy/gui/GuiEngineCopper.java +++ b/src/main/java/forestry/energy/gui/GuiEngineCopper.java @@ -22,19 +22,15 @@ public class GuiEngineCopper extends GuiEngine { super(Defaults.TEXTURE_PATH_GUI + "/peatengine.png", new ContainerEngineCopper(inventory, tile), tile); } - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - super.drawGuiContainerForegroundLayer(mouseX, mouseY); - String name = StringUtil.localize("tile.for.engine.1"); - this.fontRendererObj.drawString(name, getCenteredOffset(name), 6, fontColor.get("gui.title")); - this.fontRendererObj.drawString("Inventory", 8, this.ySize - 96 + 2, fontColor.get("gui.title")); + protected EngineCopper getEngine() { + return (EngineCopper)tile; } @Override protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - EngineCopper engine = (EngineCopper) tile; + EngineCopper engine = getEngine(); int progress; if (engine.isBurning()) { progress = engine.getBurnTimeRemainingScaled(12); diff --git a/src/main/java/forestry/energy/gui/GuiEngineTin.java b/src/main/java/forestry/energy/gui/GuiEngineTin.java index 0a6d2035c..f1942c073 100755 --- a/src/main/java/forestry/energy/gui/GuiEngineTin.java +++ b/src/main/java/forestry/energy/gui/GuiEngineTin.java @@ -25,19 +25,20 @@ public class GuiEngineTin extends GuiEngine { widgetManager.add(new SocketWidget(this.widgetManager, 30, 40, tile, 0)); } - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - super.drawGuiContainerForegroundLayer(mouseX, mouseY); - String name = StringUtil.localize("tile.for.engine.0"); - this.fontRendererObj.drawString(name, getCenteredOffset(name), 6, fontColor.get("gui.title")); + protected EngineTin getEngine() { + return (EngineTin)tile; } @Override protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - EngineTin engine = (EngineTin) tile; - drawHealthMeter(guiLeft + 74, guiTop + 25, engine.getStorageScaled(46), engine.rateLevel(engine.getStorageScaled(100))); + EngineTin engine = getEngine(); + int storageHeight = engine.getStorageScaled(46); + int storageMaxHeight = engine.getStorageScaled(100); + EnumTankLevel rated = engine.rateLevel(storageMaxHeight); + + drawHealthMeter(guiLeft + 74, guiTop + 25, storageHeight, rated); } private void drawHealthMeter(int x, int y, int height, EnumTankLevel rated) { diff --git a/src/main/java/forestry/energy/gui/GuiGenerator.java b/src/main/java/forestry/energy/gui/GuiGenerator.java index c2a4f01f4..673f10fd4 100755 --- a/src/main/java/forestry/energy/gui/GuiGenerator.java +++ b/src/main/java/forestry/energy/gui/GuiGenerator.java @@ -13,25 +13,17 @@ package forestry.energy.gui; import net.minecraft.entity.player.InventoryPlayer; import forestry.core.config.Defaults; -import forestry.core.gui.GuiForestry; +import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.widgets.TankWidget; -import forestry.core.utils.StringUtil; import forestry.energy.gadgets.MachineGenerator; -public class GuiGenerator extends GuiForestry { +public class GuiGenerator extends GuiForestryTitled { public GuiGenerator(InventoryPlayer inventory, MachineGenerator tile) { super(Defaults.TEXTURE_PATH_GUI + "/generator.png", new ContainerGenerator(inventory, tile), tile); widgetManager.add(new TankWidget(this.widgetManager, 49, 17, 0)); } - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - super.drawGuiContainerForegroundLayer(mouseX, mouseY); - String title = StringUtil.localize("tile.for." + tile.getInventoryName()); - this.fontRendererObj.drawString(title, getCenteredOffset(title), 6, fontColor.get("gui.title")); - } - @Override protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); diff --git a/src/main/java/forestry/factory/gadgets/MachineBottler.java b/src/main/java/forestry/factory/gadgets/MachineBottler.java index 2b9c0a6e3..3fd4ebb7e 100755 --- a/src/main/java/forestry/factory/gadgets/MachineBottler.java +++ b/src/main/java/forestry/factory/gadgets/MachineBottler.java @@ -12,10 +12,12 @@ package forestry.factory.gadgets; import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Stack; +import forestry.core.fluids.tanks.FilteredTank; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.ICrafting; @@ -25,20 +27,22 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidContainerRegistry; import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData; -import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; import buildcraft.api.gates.ITrigger; import buildcraft.api.power.PowerHandler; import forestry.api.core.ForestryAPI; import forestry.api.recipes.IBottlerManager; -import forestry.api.recipes.RecipeManagers; import forestry.core.EnumErrorCode; import forestry.core.config.Config; import forestry.core.config.Defaults; +import forestry.core.fluids.tanks.StandardTank; +import forestry.core.fluids.TankManager; import forestry.core.gadgets.TileBase; import forestry.core.gadgets.TilePowered; import forestry.core.interfaces.ILiquidTankContainer; @@ -46,7 +50,6 @@ import forestry.core.network.EntityNetData; import forestry.core.network.GuiId; import forestry.core.triggers.ForestryTrigger; import forestry.core.utils.EnumTankLevel; -import forestry.core.utils.ForestryTank; import forestry.core.utils.InventoryAdapter; import forestry.core.utils.LiquidHelper; import forestry.core.utils.StackUtils; @@ -86,10 +89,13 @@ public class MachineBottler extends TilePowered implements ISidedInventory, ILiq public static class RecipeManager implements IBottlerManager { public static ArrayList recipes = new ArrayList(); + public static HashSet recipeFluids = new HashSet(); @Override public void addRecipe(int cyclesPerUnit, FluidStack input, ItemStack can, ItemStack bottled) { recipes.add(new MachineBottler.Recipe(cyclesPerUnit, input, can, bottled)); + if (input != null) + recipeFluids.add(input.getFluid()); } /** @@ -113,8 +119,8 @@ public class MachineBottler extends TilePowered implements ISidedInventory, ILiq if(FluidContainerRegistry.isEmptyContainer(empty)) { ItemStack filled = FluidContainerRegistry.fillFluidContainer(res, empty); if(filled != null) { - RecipeManagers.bottlerManager.addRecipe(CYCLES_FILLING_DEFAULT, FluidContainerRegistry.getFluidForFilledItem(filled), empty, filled); - return findMatchingRecipe(res, empty); + FluidStack fluidStack = FluidContainerRegistry.getFluidForFilledItem(filled); + return findMatchingRecipe(fluidStack, empty); } } @@ -127,14 +133,7 @@ public class MachineBottler extends TilePowered implements ISidedInventory, ILiq * @return true if any recipe has a matching input */ public static boolean isInput(FluidStack res) { - for (int i = 0; i < recipes.size(); i++) { - Recipe recipe = recipes.get(i); - if (recipe.hasInput(res)) - return true; - } - - return FluidRegistry.isFluidRegistered(res.getFluid()); - + return recipeFluids.contains(res.getFluid()); } @Override @@ -149,7 +148,8 @@ public class MachineBottler extends TilePowered implements ISidedInventory, ILiq } @EntityNetData - public ForestryTank resourceTank = new ForestryTank(Defaults.PROCESSOR_TANK_CAPACITY); + public FilteredTank resourceTank; + private final TankManager tankManager; private final InventoryAdapter inventory = new InventoryAdapter(3, "Items"); @@ -162,11 +162,13 @@ public class MachineBottler extends TilePowered implements ISidedInventory, ILiq public MachineBottler() { setHints(Config.hints.get("bottler")); + resourceTank = new FilteredTank(Defaults.PROCESSOR_TANK_CAPACITY, RecipeManager.recipeFluids); + tankManager = new TankManager(resourceTank); } @Override public String getInventoryName() { - return "factory.0"; + return getUnlocalizedName(); } @Override @@ -189,10 +191,7 @@ public class MachineBottler extends TilePowered implements ISidedInventory, ILiq nbttagcompound.setInteger("FillingTotalTime", fillingTotalTime); nbttagcompound.setBoolean("ProductPending", productPending); - NBTTagCompound NBTresourceSlot = new NBTTagCompound(); - resourceTank.writeToNBT(NBTresourceSlot); - nbttagcompound.setTag("ResourceTank", NBTresourceSlot); - + tankManager.writeTanksToNBT(nbttagcompound); inventory.writeToNBT(nbttagcompound); NBTTagList nbttaglist = new NBTTagList(); @@ -215,9 +214,7 @@ public class MachineBottler extends TilePowered implements ISidedInventory, ILiq fillingTotalTime = nbttagcompound.getInteger("FillingTotalTime"); productPending = nbttagcompound.getBoolean("ProductPending"); - resourceTank = new ForestryTank(Defaults.PROCESSOR_TANK_CAPACITY); - if (nbttagcompound.hasKey("ResourceTank")) - resourceTank.readFromNBT(nbttagcompound.getCompoundTag("ResourceTank")); + tankManager.readTanksFromNBT(nbttagcompound); inventory.readFromNBT(nbttagcompound); @@ -371,7 +368,7 @@ public class MachineBottler extends TilePowered implements ISidedInventory, ILiq /* SMP GUI */ public void getGUINetworkData(int i, int j) { - + i -= tankManager.maxMessageId() + 1; switch (i) { case 0: fillingTime = j; @@ -383,8 +380,9 @@ public class MachineBottler extends TilePowered implements ISidedInventory, ILiq } public void sendGUINetworkData(Container container, ICrafting iCrafting) { - iCrafting.sendProgressBarUpdate(container, 0, fillingTime); - iCrafting.sendProgressBarUpdate(container, 1, fillingTotalTime); + int i = tankManager.maxMessageId() + 1; + iCrafting.sendProgressBarUpdate(container, i, fillingTime); + iCrafting.sendProgressBarUpdate(container, i + 1, fillingTotalTime); } /* IINVENTORY */ @@ -479,23 +477,37 @@ public class MachineBottler extends TilePowered implements ISidedInventory, ILiq /* ILIQUIDCONTAINER */ @Override - public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - - if (!RecipeManager.isInput(resource)) - return 0; - - int used = resourceTank.fill(resource, doFill); - - if (doFill && used > 0) - // TODO: Slow down updates - sendNetworkUpdate(); - - return used; + public TankManager getTankManager() { + return tankManager; } @Override - public ForestryTank[] getTanks() { - return new ForestryTank[] { resourceTank }; + public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + return tankManager.fill(from, resource, doFill); + } + + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return tankManager.drain(from, resource, doDrain); + } + + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + return tankManager.drain(from, maxDrain, doDrain); + } + + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return tankManager.canFill(from, fluid); + } + + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return tankManager.canDrain(from, fluid); + } + + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return tankManager.getTankInfo(from); } // ITRIGGERPROVIDER diff --git a/src/main/java/forestry/factory/gadgets/MachineCarpenter.java b/src/main/java/forestry/factory/gadgets/MachineCarpenter.java index 5e30b7f43..d9bafbc3a 100755 --- a/src/main/java/forestry/factory/gadgets/MachineCarpenter.java +++ b/src/main/java/forestry/factory/gadgets/MachineCarpenter.java @@ -12,6 +12,7 @@ package forestry.factory.gadgets; import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedList; import java.util.Map; @@ -27,9 +28,11 @@ import net.minecraft.nbt.NBTTagList; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidContainerRegistry; import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData; import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; import buildcraft.api.gates.ITrigger; import buildcraft.api.power.PowerHandler; @@ -40,6 +43,9 @@ import forestry.core.EnumErrorCode; import forestry.core.config.Config; import forestry.core.config.Defaults; import forestry.core.config.ForestryItem; +import forestry.core.proxy.Proxies; +import forestry.core.fluids.tanks.FilteredTank; +import forestry.core.fluids.TankManager; import forestry.core.gadgets.TileBase; import forestry.core.gadgets.TilePowered; import forestry.core.interfaces.ILiquidTankContainer; @@ -47,7 +53,6 @@ import forestry.core.network.EntityNetData; import forestry.core.network.GuiId; import forestry.core.triggers.ForestryTrigger; import forestry.core.utils.EnumTankLevel; -import forestry.core.utils.ForestryTank; import forestry.core.utils.InventoryAdapter; import forestry.core.utils.LiquidHelper; import forestry.core.utils.ShapedRecipeCustom; @@ -141,6 +146,7 @@ public class MachineCarpenter extends TilePowered implements ISidedInventory, IL public static class RecipeManager implements ICarpenterManager { public static ArrayList recipes = new ArrayList(); + public static HashSet recipeFluids = new HashSet(); @Override public void addCrating(ItemStack itemStack) { @@ -170,6 +176,8 @@ public class MachineCarpenter extends TilePowered implements ISidedInventory, IL @Override public void addRecipe(int packagingTime, FluidStack liquid, ItemStack box, ItemStack product, Object materials[]) { recipes.add(new Recipe(packagingTime, liquid, box, ShapedRecipeCustom.createShapedRecipe(product, materials))); + if (liquid != null) + recipeFluids.add(liquid.getFluid()); } public static Recipe findMatchingRecipe(FluidStack liquid, ItemStack item, InventoryCrafting inventorycrafting, World world) { @@ -182,12 +190,7 @@ public class MachineCarpenter extends TilePowered implements ISidedInventory, IL } public static boolean isResourceLiquid(FluidStack liquid) { - for (Recipe recipe : recipes) { - if (recipe.hasLiquid(liquid)) - return true; - } - - return false; + return recipeFluids.contains(liquid.getFluid()); } public static boolean isBox(ItemStack resource) { @@ -214,7 +217,8 @@ public class MachineCarpenter extends TilePowered implements ISidedInventory, IL /* MEMBER */ @EntityNetData - public ForestryTank resourceTank = new ForestryTank(Defaults.PROCESSOR_TANK_CAPACITY); + public FilteredTank resourceTank; + private final TankManager tankManager; private final TileInventoryAdapter craftingInventory; private final TileInventoryAdapter accessibleInventory; public MachineCarpenter.Recipe currentRecipe; @@ -231,13 +235,16 @@ public class MachineCarpenter extends TilePowered implements ISidedInventory, IL public MachineCarpenter() { setHints(Config.hints.get("carpenter")); + resourceTank = new FilteredTank(Defaults.PROCESSOR_TANK_CAPACITY, RecipeManager.recipeFluids); craftingInventory = new TileInventoryAdapter(this, 10, "CraftItems"); accessibleInventory = (TileInventoryAdapter) new TileInventoryAdapter(this, 30, "Items").configureSided(Defaults.FACINGS, SLOT_BOX, 20); + + tankManager = new TankManager(resourceTank); } @Override public String getInventoryName() { - return "factory.1"; + return getUnlocalizedName(); } @Override @@ -258,10 +265,7 @@ public class MachineCarpenter extends TilePowered implements ISidedInventory, IL nbttagcompound.setInteger("PackageTime", packageTime); nbttagcompound.setInteger("PackageTotalTime", totalTime); - NBTTagCompound NBTresourceSlot = new NBTTagCompound(); - - resourceTank.writeToNBT(NBTresourceSlot); - nbttagcompound.setTag("ResourceTank", NBTresourceSlot); + tankManager.writeTanksToNBT(nbttagcompound); craftingInventory.writeToNBT(nbttagcompound); accessibleInventory.writeToNBT(nbttagcompound); @@ -287,9 +291,7 @@ public class MachineCarpenter extends TilePowered implements ISidedInventory, IL packageTime = nbttagcompound.getInteger("PackageTime"); totalTime = nbttagcompound.getInteger("PackageTotalTime"); - resourceTank = new ForestryTank(Defaults.PROCESSOR_TANK_CAPACITY); - if (nbttagcompound.hasKey("ResourceTank")) - resourceTank.readFromNBT(nbttagcompound.getCompoundTag("ResourceTank")); + tankManager.readTanksFromNBT(nbttagcompound); if (nbttagcompound.hasKey("CraftItems")) craftingInventory.readFromNBT(nbttagcompound); @@ -384,7 +386,8 @@ public class MachineCarpenter extends TilePowered implements ISidedInventory, IL totalTime = 0; // Remove resources - removeResources(currentRecipe); + if (!removeResources(currentRecipe)) + return false; // Update product display if (activeContainer != null) @@ -429,40 +432,34 @@ public class MachineCarpenter extends TilePowered implements ISidedInventory, IL return false; // Need at least one matched set - return StackUtils.containsSets(craftingInventory.getStacks(SLOT_CRAFTING_1, 9), accessibleInventory.getStacks(SLOT_INVENTORY_1, SLOT_INVENTORY_COUNT), null, true, false) > 0; + ItemStack[] set = craftingInventory.getStacks(SLOT_CRAFTING_1, 9); + ItemStack[] stock = accessibleInventory.getStacks(SLOT_INVENTORY_1, SLOT_INVENTORY_COUNT); + return StackUtils.containsSets(set, stock, true, false) > 0; } - private void removeResources(Recipe recipe) { + private boolean removeResources(Recipe recipe) { // Remove resources - if (recipe.liquid != null) - resourceTank.drain(recipe.liquid.amount, true); + if (recipe.liquid != null) { + FluidStack amountDrained = resourceTank.drain(recipe.liquid.amount, false); + if (amountDrained != null && amountDrained.amount == recipe.liquid.amount) + resourceTank.drain(recipe.liquid.amount, true); + else + return false; + } // Remove boxes - if (recipe.box != null) - accessibleInventory.decrStackSize(SLOT_BOX, 1); - - removeSets(1, craftingInventory.getStacks(SLOT_CRAFTING_1, 9)); - - } - - private void removeSets(int count, ItemStack[] set) { - - for (int i = 0; i < count; i++) { - ItemStack[] condensedSet = StackUtils.condenseStacks(set); - for (ItemStack req : condensedSet) { - for (int j = SLOT_INVENTORY_1; j < SLOT_INVENTORY_1 + SLOT_INVENTORY_COUNT; j++) { - ItemStack pol = accessibleInventory.getStackInSlot(j); - if (pol == null) - continue; - if (!StackUtils.isCraftingEquivalent(pol, req, true, false)) - continue; - - ItemStack removed = accessibleInventory.decrStackSize(j, req.stackSize); - req.stackSize -= removed.stackSize; - } - } + if (recipe.box != null) { + ItemStack removed = accessibleInventory.decrStackSize(SLOT_BOX, 1); + if (removed == null || removed.stackSize == 0) + return false; } + return removeSets(1, craftingInventory.getStacks(SLOT_CRAFTING_1, 9)); + } + + private boolean removeSets(int count, ItemStack[] set) { + EntityPlayer player = Proxies.common.getPlayer(worldObj, owner); + return accessibleInventory.removeSets(count, set, SLOT_INVENTORY_1, SLOT_INVENTORY_COUNT, player, true, true, true); } private boolean tryAddPending() { @@ -609,7 +606,7 @@ public class MachineCarpenter extends TilePowered implements ISidedInventory, IL /* SMP GUI */ public void getGUINetworkData(int i, int j) { - + i -= tankManager.maxMessageId() + 1; switch (i) { case 0: packageTime = j; @@ -621,8 +618,9 @@ public class MachineCarpenter extends TilePowered implements ISidedInventory, IL } public void sendGUINetworkData(Container container, ICrafting iCrafting) { - iCrafting.sendProgressBarUpdate(container, 0, packageTime); - iCrafting.sendProgressBarUpdate(container, 1, totalTime); + int i = tankManager.maxMessageId() + 1; + iCrafting.sendProgressBarUpdate(container, i, packageTime); + iCrafting.sendProgressBarUpdate(container, i + 1, totalTime); } /* ISIDEDINVENTORY */ @@ -677,18 +675,40 @@ public class MachineCarpenter extends TilePowered implements ISidedInventory, IL // ILIQUIDCONTAINER IMPLEMENTATION @Override public int fill(ForgeDirection direction, FluidStack resource, boolean doFill) { - int used = resourceTank.fill(resource, doFill); - - if (doFill && used > 0) - // TODO: Slow down updates - sendNetworkUpdate(); - - return used; + return tankManager.fill(direction, resource, doFill); } @Override - public ForestryTank[] getTanks() { - return new ForestryTank[] { resourceTank }; + public TankManager getTankManager() { + return tankManager; + } + + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return tankManager.drain(from, resource, doDrain); + } + + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + return tankManager.drain(from, maxDrain, doDrain); + } + + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return tankManager.canFill(from, fluid); + } + + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return tankManager.canDrain(from, fluid); + } + + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return tankManager.getTankInfo(from); + } + + public void resetProductDisplay(InventoryCrafting craftMatrix) { + setCurrentRecipe(RecipeManager.findMatchingRecipe(resourceTank.getFluid(), getBoxStack(), craftMatrix, getWorldObj())); } // ITRIGGERPROVIDER diff --git a/src/main/java/forestry/factory/gadgets/MachineCentrifuge.java b/src/main/java/forestry/factory/gadgets/MachineCentrifuge.java index 294d09bf3..7f1a308ce 100755 --- a/src/main/java/forestry/factory/gadgets/MachineCentrifuge.java +++ b/src/main/java/forestry/factory/gadgets/MachineCentrifuge.java @@ -148,7 +148,7 @@ public class MachineCentrifuge extends TilePowered implements ISidedInventory, I @Override public String getInventoryName() { - return "factory.2"; + return getUnlocalizedName(); } @Override diff --git a/src/main/java/forestry/factory/gadgets/MachineFabricator.java b/src/main/java/forestry/factory/gadgets/MachineFabricator.java index 989e27820..042f87da1 100755 --- a/src/main/java/forestry/factory/gadgets/MachineFabricator.java +++ b/src/main/java/forestry/factory/gadgets/MachineFabricator.java @@ -23,6 +23,8 @@ import net.minecraft.item.crafting.IRecipe; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import buildcraft.api.power.PowerHandler; @@ -37,10 +39,14 @@ import forestry.core.interfaces.ICrafter; import forestry.core.interfaces.ICraftingPlan; import forestry.core.interfaces.ILiquidTankContainer; import forestry.core.network.GuiId; -import forestry.core.utils.ForestryTank; +import forestry.core.proxy.Proxies; +import forestry.core.fluids.tanks.StandardTank; +import forestry.core.fluids.TankManager; +import forestry.core.fluids.tanks.FilteredTank; import forestry.core.utils.InventoryAdapter; import forestry.core.utils.ShapedRecipeCustom; import forestry.core.utils.StackUtils; +import net.minecraftforge.fluids.FluidTankInfo; public class MachineFabricator extends TilePowered implements ICrafter, ISpecialInventory, ILiquidTankContainer { @@ -229,14 +235,21 @@ public class MachineFabricator extends TilePowered implements ICrafter, ISpecial public static final short SLOT_INVENTORY_COUNT = 18; /* MEMBER */ + private final TankManager tankManager; + private FilteredTank moltenTank; private final InventoryAdapter inventory = new InventoryAdapter(30, "Items"); - private ForestryTank moltenTank = new ForestryTank(2 * Defaults.BUCKET_VOLUME); + private final int moltenTankIndex; private int heat = 0; private int guiMeltingPoint = 0; private FluidStack pendingSmelt; public MachineFabricator() { + Fluid liquidGlass = FluidRegistry.getFluid(Defaults.LIQUID_GLASS); + moltenTank = new FilteredTank(2 * Defaults.BUCKET_VOLUME, liquidGlass); + moltenTank.tankMode = StandardTank.TankMode.INTERNAL; + tankManager = new TankManager(moltenTank); + moltenTankIndex = moltenTank.getTankIndex(); } @Override @@ -246,7 +259,7 @@ public class MachineFabricator extends TilePowered implements ICrafter, ISpecial @Override public String getInventoryName() { - return "factory2.0"; + return getUnlocalizedName(); } @Override @@ -262,9 +275,7 @@ public class MachineFabricator extends TilePowered implements ICrafter, ISpecial nbttagcompound.setInteger("Heat", heat); // Tank - NBTTagCompound nbtMoltenTank = new NBTTagCompound(); - moltenTank.writeToNBT(nbtMoltenTank); - nbttagcompound.setTag("MoltenTank", nbtMoltenTank); + tankManager.writeTanksToNBT(nbttagcompound); // Pending Smelt if (pendingSmelt != null) { @@ -284,9 +295,7 @@ public class MachineFabricator extends TilePowered implements ICrafter, ISpecial heat = nbttagcompound.getInteger("Heat"); // Tank - moltenTank = new ForestryTank(Defaults.BUCKET_VOLUME * 2); - if (nbttagcompound.hasKey("MoltenTank")) - moltenTank.readFromNBT(nbttagcompound.getCompoundTag("MoltenTank")); + tankManager.readTanksFromNBT(nbttagcompound); // Pending Smelt if (nbttagcompound.hasKey("PendingSmelt")) { @@ -303,13 +312,6 @@ public class MachineFabricator extends TilePowered implements ICrafter, ISpecial @Override public void updateServerSide() { - // Remove smelt if we have gone below metling point - if (moltenTank.getFluidAmount() > 0) { - Smelting smelt = RecipeManager.findMatchingSmelting(moltenTank.getFluid()); - if (smelt != null && heat < smelt.meltingPoint) - moltenTank.drain(5, true); - } - // Add pending smelt if (pendingSmelt != null) { @@ -319,16 +321,19 @@ public class MachineFabricator extends TilePowered implements ICrafter, ISpecial if (pendingSmelt.amount <= 0) pendingSmelt = null; // Smelt if necessary and possible - } else if (moltenTank.getFluidAmount() < moltenTank.getCapacity()) - if (inventory.getStackInSlot(SLOT_METAL) != null) { + } else if (moltenTank.getFluidAmount() < moltenTank.getCapacity() && inventory.getStackInSlot(SLOT_METAL) != null) { + Smelting smelt = RecipeManager.findMatchingSmelting(inventory.getStackInSlot(SLOT_METAL)); + if (smelt != null && smelt.meltingPoint <= heat) { - Smelting smelt = RecipeManager.findMatchingSmelting(inventory.getStackInSlot(SLOT_METAL)); - if (smelt != null && smelt.meltingPoint <= heat) { - - this.decrStackSize(SLOT_METAL, 1); - pendingSmelt = smelt.product.copy(); - } + this.decrStackSize(SLOT_METAL, 1); + pendingSmelt = smelt.product.copy(); } + } else if (moltenTank.getFluidAmount() > 0) { + // Remove smelt if we have gone below melting point + Smelting smelt = RecipeManager.findMatchingSmelting(moltenTank.getFluid()); + if (smelt != null && heat < smelt.meltingPoint) + moltenTank.drain(5, true); + } this.dissipateHeat(); } @@ -397,8 +402,8 @@ public class MachineFabricator extends TilePowered implements ICrafter, ISpecial FluidStack liquid = myRecipe.molten; // Remove resources - if (removeFromInventory(1, inventory.getStacks(SLOT_CRAFTING_1, 9), false)) { - removeFromInventory(1, inventory.getStacks(SLOT_CRAFTING_1, 9), true); + if (removeFromInventory(1, inventory.getStacks(SLOT_CRAFTING_1, 9), player, false)) { + removeFromInventory(1, inventory.getStacks(SLOT_CRAFTING_1, 9), player, true); moltenTank.drain(liquid.amount, true); } else if (consumeRecipe) { removeFromCraftMatrix(myRecipe); @@ -428,39 +433,13 @@ public class MachineFabricator extends TilePowered implements ICrafter, ISpecial } - private boolean removeFromInventory(int count, ItemStack[] set, boolean doRemove) { - - boolean hasRemoved = true; - for (int i = 0; i < count; i++) { - ItemStack[] condensedSet = StackUtils.condenseStacks(set, 1, true); - for (ItemStack req : condensedSet) - for (int j = SLOT_INVENTORY_1; j < SLOT_INVENTORY_1 + SLOT_INVENTORY_COUNT; j++) { - ItemStack pol = inventory.getStackInSlot(j); - if (pol == null) - continue; - if (!StackUtils.isCraftingEquivalent(pol, req, true, false)) - continue; - - int available = pol.stackSize; - if (doRemove) { - inventory.decrStackSize(j, req.stackSize); - } - req.stackSize -= available; - - if(req.stackSize <= 0) - break; - } - - boolean hasLeft = false; - for (ItemStack req : condensedSet) - if (req != null && req.stackSize > 0) - hasLeft = true; - if (hasLeft) - hasRemoved = false; - + private boolean removeFromInventory(int count, ItemStack[] set, EntityPlayer player, boolean doRemove) { + if (doRemove) { + return inventory.removeSets(count, set, SLOT_INVENTORY_1, SLOT_INVENTORY_COUNT, player, true, true, true); + } else { + ItemStack[] stock = inventory.getStacks(SLOT_INVENTORY_1, SLOT_INVENTORY_COUNT); + return StackUtils.containsSets(set, stock) >= count; } - - return hasRemoved; } @Override @@ -501,19 +480,18 @@ public class MachineFabricator extends TilePowered implements ICrafter, ISpecial /* SMP */ public void getGUINetworkData(int i, int j) { - switch (i) { - case 0: + int messageId = tankManager.maxMessageId() + 1; + + if (i == messageId) heat = j; - break; - case 1: + else if (i == messageId + 1) guiMeltingPoint = j; - break; - } } public void sendGUINetworkData(Container container, ICrafting iCrafting) { - iCrafting.sendProgressBarUpdate(container, 0, heat); - iCrafting.sendProgressBarUpdate(container, 1, getMeltingPoint()); + int messageId = tankManager.maxMessageId() + 1; + iCrafting.sendProgressBarUpdate(container, messageId, heat); + iCrafting.sendProgressBarUpdate(container, messageId + 1, getMeltingPoint()); } // / ISPECIALINVENTORY @@ -527,10 +505,12 @@ public class MachineFabricator extends TilePowered implements ICrafter, ISpecial @Override public ItemStack[] extractItem(boolean doRemove, ForgeDirection from, int maxItemCount) { ItemStack taken; - if (doRemove) - taken = this.takenFromSlot(SLOT_RESULT, false, null); - else + if (doRemove) { + EntityPlayer player = Proxies.common.getPlayer(worldObj, owner); + taken = this.takenFromSlot(SLOT_RESULT, false, player); + } else { taken = this.getResult(); + } if (taken != null) return new ItemStack[] { taken }; @@ -603,7 +583,38 @@ public class MachineFabricator extends TilePowered implements ICrafter, ISpecial /* ILIQUIDCONTAINER */ @Override - public ForestryTank[] getTanks() { - return new ForestryTank[] { moltenTank }; + public TankManager getTankManager() { + return tankManager; } + + @Override + public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + return tankManager.fill(from, resource, doFill); + } + + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return tankManager.drain(from, resource, doDrain); + } + + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + return tankManager.drain(from, maxDrain, doDrain); + } + + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return tankManager.canFill(from, fluid); + } + + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return tankManager.canDrain(from, fluid); + } + + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return tankManager.getTankInfo(from); + } + } diff --git a/src/main/java/forestry/factory/gadgets/MachineFermenter.java b/src/main/java/forestry/factory/gadgets/MachineFermenter.java index fc0ec9bbd..47bf39e6c 100755 --- a/src/main/java/forestry/factory/gadgets/MachineFermenter.java +++ b/src/main/java/forestry/factory/gadgets/MachineFermenter.java @@ -12,9 +12,11 @@ package forestry.factory.gadgets; import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedList; import java.util.Map; +import forestry.core.fluids.tanks.FilteredTank; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.ICrafting; @@ -23,6 +25,7 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData; import net.minecraftforge.fluids.FluidStack; @@ -43,11 +46,13 @@ import forestry.core.network.EntityNetData; import forestry.core.network.GuiId; import forestry.core.triggers.ForestryTrigger; import forestry.core.utils.EnumTankLevel; -import forestry.core.utils.ForestryTank; +import forestry.core.fluids.tanks.StandardTank; +import forestry.core.fluids.TankManager; import forestry.core.utils.InventoryAdapter; import forestry.core.utils.LiquidHelper; import forestry.core.utils.StackUtils; import forestry.core.utils.Utils; +import net.minecraftforge.fluids.FluidTankInfo; public class MachineFermenter extends TilePowered implements ISidedInventory, ILiquidTankContainer { @@ -117,10 +122,16 @@ public class MachineFermenter extends TilePowered implements ISidedInventory, IL public static class RecipeManager implements IFermenterManager { public static ArrayList recipes = new ArrayList(); + public static HashSet recipeFluidInputs = new HashSet(); + public static HashSet recipeFluidOutputs = new HashSet(); @Override public void addRecipe(ItemStack resource, int fermentationValue, float modifier, FluidStack output, FluidStack liquid) { recipes.add(new Recipe(resource, fermentationValue, modifier, output, liquid)); + if (liquid != null) + recipeFluidInputs.add(liquid.getFluid()); + if (output != null) + recipeFluidOutputs.add(output.getFluid()); } @Override @@ -151,21 +162,11 @@ public class MachineFermenter extends TilePowered implements ISidedInventory, IL } public static boolean isLiquidResource(FluidStack liquid) { - for (int i = 0; i < recipes.size(); i++) { - Recipe recipe = recipes.get(i); - if (recipe.liquid.isFluidEqual(liquid)) - return true; - } - return false; + return recipeFluidInputs.contains(liquid.getFluid()); } public static boolean isLiquidProduct(FluidStack liquid) { - for (int i = 0; i < recipes.size(); i++) { - Recipe recipe = recipes.get(i); - if (recipe.output.isFluidEqual(liquid)) - return true; - } - return false; + return recipeFluidOutputs.contains(liquid.getFluid()); } @Override @@ -180,9 +181,12 @@ public class MachineFermenter extends TilePowered implements ISidedInventory, IL } } @EntityNetData - public ForestryTank resourceTank = new ForestryTank(Defaults.PROCESSOR_TANK_CAPACITY); + public FilteredTank resourceTank; @EntityNetData - public ForestryTank productTank = new ForestryTank(Defaults.PROCESSOR_TANK_CAPACITY); + public FilteredTank productTank; + + private final TankManager tankManager; + private final InventoryAdapter inventory = new InventoryAdapter(5, "Items"); private Recipe currentRecipe; private float currentResourceModifier; @@ -194,11 +198,16 @@ public class MachineFermenter extends TilePowered implements ISidedInventory, IL public MachineFermenter() { setHints(Config.hints.get("fermenter")); + resourceTank = new FilteredTank(Defaults.PROCESSOR_TANK_CAPACITY, RecipeManager.recipeFluidInputs); + resourceTank.tankMode = StandardTank.TankMode.INPUT; + productTank = new FilteredTank(Defaults.PROCESSOR_TANK_CAPACITY, RecipeManager.recipeFluidOutputs); + productTank.tankMode = StandardTank.TankMode.OUTPUT; + tankManager = new TankManager(resourceTank, productTank); } @Override public String getInventoryName() { - return "factory.3"; + return getUnlocalizedName(); } @Override @@ -221,15 +230,7 @@ public class MachineFermenter extends TilePowered implements ISidedInventory, IL nbttagcompound.setInteger("FuelTotalTime", fuelTotalTime); nbttagcompound.setInteger("FuelCurrentFerment", fuelCurrentFerment); - NBTTagCompound NBTresourceSlot = new NBTTagCompound(); - NBTTagCompound NBTproductSlot = new NBTTagCompound(); - - resourceTank.writeToNBT(NBTresourceSlot); - productTank.writeToNBT(NBTproductSlot); - - nbttagcompound.setTag("ResourceTank", NBTresourceSlot); - nbttagcompound.setTag("ProductTank", NBTproductSlot); - + tankManager.writeTanksToNBT(nbttagcompound); inventory.writeToNBT(nbttagcompound); } @@ -244,13 +245,7 @@ public class MachineFermenter extends TilePowered implements ISidedInventory, IL fuelTotalTime = nbttagcompound.getInteger("FuelTotalTime"); fuelCurrentFerment = nbttagcompound.getInteger("FuelCurrentFerment"); - resourceTank = new ForestryTank(Defaults.PROCESSOR_TANK_CAPACITY); - productTank = new ForestryTank(Defaults.PROCESSOR_TANK_CAPACITY); - if (nbttagcompound.hasKey("ResourceTank")) { - resourceTank.readFromNBT(nbttagcompound.getCompoundTag("ResourceTank")); - productTank.readFromNBT(nbttagcompound.getCompoundTag("ProductTank")); - } - + tankManager.readTanksFromNBT(nbttagcompound); inventory.readFromNBT(nbttagcompound); } @@ -511,28 +506,25 @@ public class MachineFermenter extends TilePowered implements ISidedInventory, IL /* SMP GUI */ public void getGUINetworkData(int i, int j) { + int firstMessageId = tankManager.maxMessageId() + 1; - switch (i) { - case 0: + if (i == firstMessageId) fuelBurnTime = j; - break; - case 1: + else if (i == firstMessageId + 1) fuelTotalTime = j; - break; - case 2: + else if (i == firstMessageId + 2) fermentationTime = j; - break; - case 3: + else if (i == firstMessageId + 3) fermentationTotalTime = j; - break; - } } public void sendGUINetworkData(Container container, ICrafting iCrafting) { - iCrafting.sendProgressBarUpdate(container, 0, fuelBurnTime); - iCrafting.sendProgressBarUpdate(container, 1, fuelTotalTime); - iCrafting.sendProgressBarUpdate(container, 2, fermentationTime); - iCrafting.sendProgressBarUpdate(container, 3, fermentationTotalTime); + int firstMessageId = tankManager.maxMessageId() + 1; + + iCrafting.sendProgressBarUpdate(container, firstMessageId, fuelBurnTime); + iCrafting.sendProgressBarUpdate(container, firstMessageId + 1, fuelTotalTime); + iCrafting.sendProgressBarUpdate(container, firstMessageId + 2, fermentationTime); + iCrafting.sendProgressBarUpdate(container, firstMessageId + 3, fermentationTotalTime); } /* INVENTORY */ @@ -663,20 +655,15 @@ public class MachineFermenter extends TilePowered implements ISidedInventory, IL return super.getAccessibleSlotsFromSide(side); } - // ILIQUIDCONTAINER IMPLEMENTATION + /* ILiquidTankContainer */ @Override public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + return resourceTank.fill(resource, doFill); + } - if (!RecipeManager.isLiquidResource(resource)) - return 0; - - int used = resourceTank.fill(resource, doFill); - - if (doFill && used > 0) - // updateNetworkTime.markTime(worldObj); - sendNetworkUpdate(); - - return used; + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return tankManager.drain(from, resource, doDrain); } @Override @@ -685,8 +672,22 @@ public class MachineFermenter extends TilePowered implements ISidedInventory, IL } @Override - public ForestryTank[] getTanks() { - return new ForestryTank[] { resourceTank, productTank }; + public boolean canFill(ForgeDirection from, Fluid fluid) { + return tankManager.canFill(from, fluid); + } + + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return tankManager.canDrain(from, fluid); + } + + @Override + public TankManager getTankManager() { + return tankManager; + } + + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return tankManager.getTankInfo(from); } // ITRIGGERPROVIDER diff --git a/src/main/java/forestry/factory/gadgets/MachineMoistener.java b/src/main/java/forestry/factory/gadgets/MachineMoistener.java index 6ef2d0c4a..dcb0bff73 100755 --- a/src/main/java/forestry/factory/gadgets/MachineMoistener.java +++ b/src/main/java/forestry/factory/gadgets/MachineMoistener.java @@ -23,7 +23,9 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData; +import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import buildcraft.api.gates.ITrigger; @@ -43,11 +45,13 @@ import forestry.core.network.EntityNetData; import forestry.core.network.GuiId; import forestry.core.triggers.ForestryTrigger; import forestry.core.utils.EnumTankLevel; -import forestry.core.utils.ForestryTank; +import forestry.core.fluids.tanks.FilteredTank; +import forestry.core.fluids.TankManager; import forestry.core.utils.InventoryAdapter; import forestry.core.utils.LiquidHelper; import forestry.core.utils.StackUtils; import forestry.core.utils.Utils; +import net.minecraftforge.fluids.FluidTankInfo; public class MachineMoistener extends TilePowered implements ISpecialInventory, ISidedInventory, ILiquidTankContainer { @@ -127,7 +131,8 @@ public class MachineMoistener extends TilePowered implements ISpecialInventory, } @EntityNetData - public ForestryTank resourceTank = new ForestryTank(Defaults.PROCESSOR_TANK_CAPACITY); + public FilteredTank resourceTank; + private final TankManager tankManager; private final InventoryAdapter inventory = new InventoryAdapter(12, "Items"); //private ItemStack[] inventoryStacks = new ItemStack[12]; public MachineMoistener.Recipe currentRecipe; @@ -141,11 +146,13 @@ public class MachineMoistener extends TilePowered implements ISpecialInventory, public MachineMoistener() { setHints(Config.hints.get("moistener")); + resourceTank = new FilteredTank(Defaults.PROCESSOR_TANK_CAPACITY, FluidRegistry.WATER); + tankManager = new TankManager(resourceTank); } @Override public String getInventoryName() { - return "factory.4"; + return getUnlocalizedName(); } @Override @@ -162,11 +169,7 @@ public class MachineMoistener extends TilePowered implements ISpecialInventory, nbttagcompound.setInteger("TotalTime", totalTime); nbttagcompound.setInteger("ProductionTime", productionTime); - NBTTagCompound NBTresourceSlot = new NBTTagCompound(); - - resourceTank.writeToNBT(NBTresourceSlot); - nbttagcompound.setTag("ResourceTank", NBTresourceSlot); - + tankManager.writeTanksToNBT(nbttagcompound); inventory.writeToNBT(nbttagcompound); // Write pending product @@ -190,10 +193,7 @@ public class MachineMoistener extends TilePowered implements ISpecialInventory, totalTime = nbttagcompound.getInteger("TotalTime"); productionTime = nbttagcompound.getInteger("ProductionTime"); - resourceTank = new ForestryTank(Defaults.PROCESSOR_TANK_CAPACITY); - if (nbttagcompound.hasKey("ResourceTank")) - resourceTank.readFromNBT(nbttagcompound.getCompoundTag("ResourceTank")); - + tankManager.readTanksFromNBT(nbttagcompound); inventory.readFromNBT(nbttagcompound); // Load pending product @@ -215,7 +215,7 @@ public class MachineMoistener extends TilePowered implements ISpecialInventory, // Check if we have suitable water container waiting in the item slot if (inventory.getStackInSlot(SLOT_PRODUCT) != null) { FluidContainerData container = LiquidHelper.getLiquidContainer(inventory.getStackInSlot(SLOT_PRODUCT)); - if (container != null && container.fluid.isFluidEqual(STACK_WATER)) { + if (container != null && resourceTank.accepts(container.fluid.getFluid())) { inventory.setInventorySlotContents(SLOT_PRODUCT, StackUtils.replenishByContainer(this, inventory.getStackInSlot(SLOT_PRODUCT), container, resourceTank)); if (inventory.getStackInSlot(SLOT_PRODUCT).stackSize <= 0) @@ -633,7 +633,7 @@ public class MachineMoistener extends TilePowered implements ISpecialInventory, public int addItem(ItemStack stack, boolean doAdd, ForgeDirection from) { FluidContainerData container = LiquidHelper.getLiquidContainer(stack); - if (container != null && container.fluid.isFluidEqual(STACK_WATER)) { + if (container != null && resourceTank.accepts(container.fluid.getFluid())) { return inventory.addStack(stack, SLOT_PRODUCT, 1, false, doAdd); } @@ -675,24 +675,44 @@ public class MachineMoistener extends TilePowered implements ISpecialInventory, return StackUtils.EMPTY_STACK_ARRAY; } - /* ILIQUIDCONTAINER */ + /* ILiquidTankContainer */ @Override public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - int used = resourceTank.fill(resource, doFill); - - if (doFill && used > 0) - sendNetworkUpdate(); - - return used; + return tankManager.fill(from, resource, doFill); } @Override - public ForestryTank[] getTanks() { - return new ForestryTank[] { resourceTank }; + public TankManager getTankManager() { + return tankManager; + } + + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return tankManager.drain(from, resource, doDrain); + } + + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + return tankManager.drain(from, maxDrain, doDrain); + } + + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return tankManager.canFill(from, fluid); + } + + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return tankManager.canDrain(from, fluid); + } + + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return tankManager.getTankInfo(from); } /* SMP GUI */ public void getGUINetworkData(int i, int j) { + i -= tankManager.maxMessageId() + 1; switch (i) { case 0: @@ -711,10 +731,11 @@ public class MachineMoistener extends TilePowered implements ISpecialInventory, } public void sendGUINetworkData(Container container, ICrafting iCrafting) { - iCrafting.sendProgressBarUpdate(container, 0, burnTime); - iCrafting.sendProgressBarUpdate(container, 1, totalTime); - iCrafting.sendProgressBarUpdate(container, 2, productionTime); - iCrafting.sendProgressBarUpdate(container, 3, timePerItem); + int i = tankManager.maxMessageId() + 1; + iCrafting.sendProgressBarUpdate(container, i, burnTime); + iCrafting.sendProgressBarUpdate(container, i + 1, totalTime); + iCrafting.sendProgressBarUpdate(container, i + 2, productionTime); + iCrafting.sendProgressBarUpdate(container, i + 3, timePerItem); } // ITRIGGERPROVIDER diff --git a/src/main/java/forestry/factory/gadgets/MachineRaintank.java b/src/main/java/forestry/factory/gadgets/MachineRaintank.java index b8b327b24..c5a2b621d 100755 --- a/src/main/java/forestry/factory/gadgets/MachineRaintank.java +++ b/src/main/java/forestry/factory/gadgets/MachineRaintank.java @@ -21,6 +21,8 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.biome.BiomeGenBase; import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import buildcraft.api.gates.ITrigger; @@ -35,11 +37,13 @@ import forestry.core.interfaces.ILiquidTankContainer; import forestry.core.network.GuiId; import forestry.core.triggers.ForestryTrigger; import forestry.core.utils.Fluids; -import forestry.core.utils.ForestryTank; +import forestry.core.fluids.TankManager; +import forestry.core.fluids.tanks.FilteredTank; import forestry.core.utils.InventoryAdapter; import forestry.core.utils.LiquidHelper; import forestry.core.utils.StackUtils; import forestry.core.utils.Utils; +import net.minecraftforge.fluids.FluidTankInfo; public class MachineRaintank extends TileBase implements ISidedInventory, ILiquidTankContainer { @@ -49,7 +53,8 @@ public class MachineRaintank extends TileBase implements ISidedInventory, ILiqui private static final FluidStack STACK_WATER = LiquidHelper.getLiquid(Defaults.LIQUID_WATER, Defaults.RAINTANK_AMOUNT_PER_UPDATE); /* MEMBER */ - public ForestryTank resourceTank = new ForestryTank(Defaults.RAINTANK_TANK_CAPACITY); + public FilteredTank resourceTank; + private final TankManager tankManager; private final InventoryAdapter inventory = new InventoryAdapter(3, "Items"); private boolean isValidBiome = true; private int fillingTime; @@ -58,6 +63,9 @@ public class MachineRaintank extends TileBase implements ISidedInventory, ILiqui public MachineRaintank() { setHints(Config.hints.get("raintank")); + resourceTank = new FilteredTank(Defaults.RAINTANK_TANK_CAPACITY, FluidRegistry.WATER); + tankManager = new TankManager(resourceTank); + // Raintanks in desert and snow biomes are useless if (worldObj != null) { BiomeGenBase biome = Utils.getBiomeAt(worldObj, xCoord, zCoord); @@ -70,7 +78,7 @@ public class MachineRaintank extends TileBase implements ISidedInventory, ILiqui @Override public String getInventoryName() { - return "factory2.1"; + return getUnlocalizedName(); } @Override @@ -84,10 +92,7 @@ public class MachineRaintank extends TileBase implements ISidedInventory, ILiqui nbttagcompound.setBoolean("IsValidBiome", isValidBiome); - NBTTagCompound NBTresourceSlot = new NBTTagCompound(); - resourceTank.writeToNBT(NBTresourceSlot); - nbttagcompound.setTag("ResourceTank", NBTresourceSlot); - + tankManager.writeTanksToNBT(nbttagcompound); inventory.writeToNBT(nbttagcompound); } @@ -97,10 +102,7 @@ public class MachineRaintank extends TileBase implements ISidedInventory, ILiqui isValidBiome = nbttagcompound.getBoolean("IsValidBiome"); - resourceTank = new ForestryTank(Defaults.RAINTANK_TANK_CAPACITY); - if (nbttagcompound.hasKey("ResourceTank")) - resourceTank.readFromNBT(nbttagcompound.getCompoundTag("ResourceTank")); - + tankManager.readTanksFromNBT(nbttagcompound); inventory.readFromNBT(nbttagcompound); } @@ -267,6 +269,7 @@ public class MachineRaintank extends TileBase implements ISidedInventory, ILiqui /* SMP GUI */ public void getGUINetworkData(int i, int j) { + i -= tankManager.maxMessageId() + 1; switch (i) { case 0: fillingTime = j; @@ -275,33 +278,43 @@ public class MachineRaintank extends TileBase implements ISidedInventory, ILiqui } public void sendGUINetworkData(Container container, ICrafting iCrafting) { - iCrafting.sendProgressBarUpdate(container, 0, fillingTime); + int i = tankManager.maxMessageId() + 1; + iCrafting.sendProgressBarUpdate(container, i, fillingTime); } // / ILIQUIDCONTAINER IMPLEMENTATION @Override public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - // We only accept water - if (!resource.isFluidEqual(STACK_WATER)) - return 0; - - int used = resourceTank.fill(resource, doFill); - - if (doFill && used > 0) - // updateNetworkTime.markTime(worldObj); - sendNetworkUpdate(); - - return used; + return tankManager.fill(from, resource, doFill); } @Override - public FluidStack drain(ForgeDirection from, int quantityMax, boolean doEmpty) { - return resourceTank.drain(quantityMax, doEmpty); + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return tankManager.drain(from, resource, doDrain); } @Override - public ForestryTank[] getTanks() { - return new ForestryTank[] { resourceTank }; + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + return tankManager.drain(from, maxDrain, doDrain); + } + + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return tankManager.canFill(from, fluid); + } + + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return tankManager.canDrain(from, fluid); + } + + @Override + public TankManager getTankManager() { + return tankManager; + } + + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return tankManager.getTankInfo(from); } /* ITRIGGERPROVIDER */ diff --git a/src/main/java/forestry/factory/gadgets/MachineSqueezer.java b/src/main/java/forestry/factory/gadgets/MachineSqueezer.java index da55534c1..4f4e414e8 100755 --- a/src/main/java/forestry/factory/gadgets/MachineSqueezer.java +++ b/src/main/java/forestry/factory/gadgets/MachineSqueezer.java @@ -11,7 +11,9 @@ package forestry.factory.gadgets; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Stack; @@ -25,6 +27,7 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData; import net.minecraftforge.fluids.FluidStack; @@ -44,11 +47,15 @@ import forestry.core.network.EntityNetData; import forestry.core.network.GuiId; import forestry.core.triggers.ForestryTrigger; import forestry.core.utils.EnumTankLevel; -import forestry.core.utils.ForestryTank; +import forestry.core.fluids.tanks.StandardTank; +import forestry.core.fluids.tanks.FilteredTank; +import forestry.core.fluids.TankManager; +import forestry.core.proxy.Proxies; import forestry.core.utils.InventoryAdapter; import forestry.core.utils.LiquidHelper; import forestry.core.utils.StackUtils; import forestry.core.utils.Utils; +import net.minecraftforge.fluids.FluidTankInfo; public class MachineSqueezer extends TilePowered implements ISpecialInventory, ISidedInventory, ILiquidTankContainer { @@ -76,38 +83,22 @@ public class MachineSqueezer extends TilePowered implements ISpecialInventory, I } public boolean matches(ItemStack[] res) { - // No recipe without resource! - if (res == null || res.length <= 0) - return false; - - boolean matchedAll = true; - - for (ItemStack stack : resources) { - boolean matched = false; - for (ItemStack matchStack : res) { - if (matchStack == null) - continue; - - // If the item matches, we need enough items - if (matchStack.isItemEqual(stack)) - if (matchStack.stackSize >= stack.stackSize) { - matched = true; - break; - } - } - if (!matched) - matchedAll = false; - } - return matchedAll; + return StackUtils.containsSets(resources, res, true, true) > 0; } } public static class RecipeManager implements ISqueezerManager { public static ArrayList recipes = new ArrayList(); + public static HashSet recipeFluids = new HashSet(); + public static HashSet recipeInputs = new HashSet(); @Override public void addRecipe(int timePerItem, ItemStack[] resources, FluidStack liquid, ItemStack remnants, int chance) { recipes.add(new MachineSqueezer.Recipe(timePerItem, resources, liquid, remnants, chance)); + if (liquid != null) + recipeFluids.add(liquid.getFluid()); + if (resources != null) + recipeInputs.addAll(Arrays.asList(resources)); } @Override @@ -125,6 +116,15 @@ public class MachineSqueezer extends TilePowered implements ISpecialInventory, I return null; } + public static boolean canUse(ItemStack itemStack) { + if (recipeInputs.contains(itemStack)) + return true; + for (ItemStack recipeInput : recipeInputs) + if (StackUtils.isCraftingEquivalent(recipeInput, itemStack)) + return true; + return false; + } + @Override public Map getRecipes() { HashMap recipeList = new HashMap(); @@ -137,8 +137,9 @@ public class MachineSqueezer extends TilePowered implements ISpecialInventory, I } /* MEMBER */ + private final TankManager tankManager; @EntityNetData - public ForestryTank productTank = new ForestryTank(Defaults.PROCESSOR_TANK_CAPACITY); + public FilteredTank productTank; private final InventoryAdapter inventory = new InventoryAdapter(12, "Items"); private Recipe currentRecipe; @@ -150,11 +151,14 @@ public class MachineSqueezer extends TilePowered implements ISpecialInventory, I public MachineSqueezer() { setHints(Config.hints.get("squeezer")); + productTank = new FilteredTank(Defaults.PROCESSOR_TANK_CAPACITY, RecipeManager.recipeFluids); + productTank.tankMode = StandardTank.TankMode.OUTPUT; + tankManager = new TankManager(productTank); } @Override public String getInventoryName() { - return "factory.5"; + return getUnlocalizedName(); } @Override @@ -202,10 +206,7 @@ public class MachineSqueezer extends TilePowered implements ISpecialInventory, I } nbttagcompound.setTag("PendingLiquids", nbttaglist); - // ProductTank - NBTTagCompound NBTproductSlot = new NBTTagCompound(); - productTank.writeToNBT(NBTproductSlot); - nbttagcompound.setTag("ProductTank", NBTproductSlot); + tankManager.writeTanksToNBT(nbttagcompound); } @Override @@ -232,10 +233,7 @@ public class MachineSqueezer extends TilePowered implements ISpecialInventory, I pendingLiquids.add(FluidStack.loadFluidStackFromNBT(nbttagcompound1)); } - // Product tank - productTank = new ForestryTank(Defaults.PROCESSOR_TANK_CAPACITY); - if (nbttagcompound.hasKey("ProductTank")) - productTank.readFromNBT(nbttagcompound.getCompoundTag("ProductTank")); + tankManager.readTanksFromNBT(nbttagcompound); checkRecipe(); } @@ -290,13 +288,14 @@ public class MachineSqueezer extends TilePowered implements ISpecialInventory, I return true; } + if (!removeResources(currentRecipe.resources)) + return false; + // We are done, add products to queue pendingLiquids.push(currentRecipe.liquid.copy()); if (currentRecipe.remnants != null && worldObj.rand.nextInt(100) < currentRecipe.chance) pendingRemnants.push(currentRecipe.remnants.copy()); - removeResources(currentRecipe.resources); - checkRecipe(); resetRecipe(); @@ -365,8 +364,9 @@ public class MachineSqueezer extends TilePowered implements ISpecialInventory, I return inventory.tryAddStack(stack, SLOT_REMNANT, 1, true); } - private void removeResources(ItemStack[] stacks) { - inventory.removeResources(stacks, SLOT_RESOURCE_1, SLOTS_RESOURCE_COUNT); + private boolean removeResources(ItemStack[] stacks) { + EntityPlayer player = Proxies.common.getPlayer(worldObj, owner); + return inventory.removeSets(1, stacks, SLOT_RESOURCE_1, SLOTS_RESOURCE_COUNT, player, false, true, true); } @Override @@ -397,6 +397,7 @@ public class MachineSqueezer extends TilePowered implements ISpecialInventory, I /* SMP GUI */ public void getGUINetworkData(int i, int j) { + i -= tankManager.maxMessageId() + 1; switch (i) { case 0: productionTime = j; @@ -408,8 +409,9 @@ public class MachineSqueezer extends TilePowered implements ISpecialInventory, I } public void sendGUINetworkData(Container container, ICrafting iCrafting) { - iCrafting.sendProgressBarUpdate(container, 0, productionTime); - iCrafting.sendProgressBarUpdate(container, 1, timePerItem); + int i = tankManager.maxMessageId() + 1; + iCrafting.sendProgressBarUpdate(container, i, productionTime); + iCrafting.sendProgressBarUpdate(container, i + 1, timePerItem); } /* IINVENTORY */ @@ -438,12 +440,22 @@ public class MachineSqueezer extends TilePowered implements ISpecialInventory, I return super.hasCustomInventoryName(); } - /** - * TODO: just a specialsource workaround - */ @Override public boolean isItemValidForSlot(int slotIndex, ItemStack itemstack) { - return super.isItemValidForSlot(slotIndex, itemstack); + + if(slotIndex == SLOT_CAN_INPUT) { + return LiquidHelper.isEmptyContainer(itemstack); + } + + if(slotIndex >= SLOT_RESOURCE_1 && slotIndex < SLOT_RESOURCE_1 + SLOTS_RESOURCE_COUNT) { + if (LiquidHelper.isEmptyContainer(itemstack)) + return false; + + if (RecipeManager.canUse(itemstack)) + return true; + } + + return false; } /** @@ -492,16 +504,9 @@ public class MachineSqueezer extends TilePowered implements ISpecialInventory, I if(!super.canPutStackFromSide(slotIndex, itemstack, side)) return false; - if(slotIndex == SLOT_CAN_INPUT) { - return LiquidHelper.isEmptyContainer(itemstack); - } - - if(slotIndex >= SLOT_RESOURCE_1 && slotIndex < SLOT_RESOURCE_1 + SLOTS_RESOURCE_COUNT) { - return !LiquidHelper.isEmptyContainer(itemstack); - } - - return false; + return slotIndex == SLOT_CAN_INPUT || (slotIndex >= SLOT_RESOURCE_1 && slotIndex < SLOT_RESOURCE_1 + SLOTS_RESOURCE_COUNT); } + /* ISPECIALINVENTORY */ @Override public int addItem(ItemStack stack, boolean doAdd, ForgeDirection from) { @@ -541,13 +546,37 @@ public class MachineSqueezer extends TilePowered implements ISpecialInventory, I /* ILIQUIDCONTAINER IMPLEMENTATION */ @Override - public FluidStack drain(ForgeDirection from, int quantityMax, boolean doEmpty) { - return productTank.drain(quantityMax, doEmpty); + public TankManager getTankManager() { + return tankManager; } @Override - public ForestryTank[] getTanks() { - return new ForestryTank[] { productTank }; + public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + return tankManager.fill(from, resource, doFill); + } + + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return tankManager.drain(from, resource, doDrain); + } + + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + return tankManager.drain(from, maxDrain, doDrain); + } + + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return tankManager.canFill(from, fluid); + } + + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return tankManager.canDrain(from, fluid); + } + + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return tankManager.getTankInfo(from); } /* ITRIGGERPROVIDER */ diff --git a/src/main/java/forestry/factory/gadgets/MachineStill.java b/src/main/java/forestry/factory/gadgets/MachineStill.java index f972240f5..b4fc6214d 100755 --- a/src/main/java/forestry/factory/gadgets/MachineStill.java +++ b/src/main/java/forestry/factory/gadgets/MachineStill.java @@ -12,6 +12,7 @@ package forestry.factory.gadgets; import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedList; import java.util.Map; @@ -23,6 +24,7 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData; import net.minecraftforge.fluids.FluidStack; @@ -42,11 +44,14 @@ import forestry.core.network.EntityNetData; import forestry.core.network.GuiId; import forestry.core.triggers.ForestryTrigger; import forestry.core.utils.EnumTankLevel; -import forestry.core.utils.ForestryTank; +import forestry.core.fluids.tanks.StandardTank; +import forestry.core.fluids.tanks.FilteredTank; +import forestry.core.fluids.TankManager; import forestry.core.utils.InventoryAdapter; import forestry.core.utils.LiquidHelper; import forestry.core.utils.StackUtils; import forestry.core.utils.Utils; +import net.minecraftforge.fluids.FluidTankInfo; public class MachineStill extends TilePowered implements ISpecialInventory, ISidedInventory, ILiquidTankContainer { @@ -84,10 +89,16 @@ public class MachineStill extends TilePowered implements ISpecialInventory, ISid public static class RecipeManager implements IStillManager { public static ArrayList recipes = new ArrayList(); + public static HashSet recipeFluidInputs = new HashSet(); + public static HashSet recipeFluidOutputs = new HashSet(); @Override public void addRecipe(int timePerUnit, FluidStack input, FluidStack output) { recipes.add(new MachineStill.Recipe(timePerUnit, input, output)); + if (input != null) + recipeFluidInputs.add(input.getFluid()); + if (output != null) + recipeFluidOutputs.add(output.getFluid()); } public static Recipe findMatchingRecipe(FluidStack item) { @@ -100,7 +111,7 @@ public class MachineStill extends TilePowered implements ISpecialInventory, ISid } public static boolean isInput(FluidStack res) { - return findMatchingRecipe(res) != null; + return recipeFluidInputs.contains(res.getFluid()); } @Override @@ -116,9 +127,10 @@ public class MachineStill extends TilePowered implements ISpecialInventory, ISid /* MEMBER */ @EntityNetData - public ForestryTank resourceTank = new ForestryTank(Defaults.PROCESSOR_TANK_CAPACITY); + public FilteredTank resourceTank; @EntityNetData - public ForestryTank productTank = new ForestryTank(Defaults.PROCESSOR_TANK_CAPACITY); + public FilteredTank productTank; + private final TankManager tankManager; private final InventoryAdapter inventory = new InventoryAdapter(3, "Items"); @@ -129,11 +141,16 @@ public class MachineStill extends TilePowered implements ISpecialInventory, ISid public MachineStill() { setHints(Config.hints.get("still")); + resourceTank = new FilteredTank(Defaults.PROCESSOR_TANK_CAPACITY, RecipeManager.recipeFluidInputs); + resourceTank.tankMode = StandardTank.TankMode.INPUT; + productTank = new FilteredTank(Defaults.PROCESSOR_TANK_CAPACITY, RecipeManager.recipeFluidOutputs); + productTank.tankMode = StandardTank.TankMode.OUTPUT; + tankManager = new TankManager(resourceTank, productTank); } @Override public String getInventoryName() { - return "factory.6"; + return getUnlocalizedName(); } @Override @@ -153,15 +170,7 @@ public class MachineStill extends TilePowered implements ISpecialInventory, ISid nbttagcompound.setInteger("DistillationTime", distillationTime); nbttagcompound.setInteger("DistillationTotalTime", distillationTotalTime); - NBTTagCompound NBTresourceSlot = new NBTTagCompound(); - NBTTagCompound NBTproductSlot = new NBTTagCompound(); - - resourceTank.writeToNBT(NBTresourceSlot); - productTank.writeToNBT(NBTproductSlot); - - nbttagcompound.setTag("ResourceTank", NBTresourceSlot); - nbttagcompound.setTag("ProductTank", NBTproductSlot); - + tankManager.writeTanksToNBT(nbttagcompound); inventory.writeToNBT(nbttagcompound); } @@ -172,13 +181,7 @@ public class MachineStill extends TilePowered implements ISpecialInventory, ISid distillationTime = nbttagcompound.getInteger("DistillationTime"); distillationTotalTime = nbttagcompound.getInteger("DistillationTotalTime"); - resourceTank = new ForestryTank(Defaults.PROCESSOR_TANK_CAPACITY); - productTank = new ForestryTank(Defaults.PROCESSOR_TANK_CAPACITY); - if (nbttagcompound.hasKey("ResourceTank")) { - resourceTank.readFromNBT(nbttagcompound.getCompoundTag("ResourceTank")); - productTank.readFromNBT(nbttagcompound.getCompoundTag("ProductTank")); - } - + tankManager.readTanksFromNBT(nbttagcompound); inventory.readFromNBT(nbttagcompound); checkRecipe(); @@ -191,7 +194,7 @@ public class MachineStill extends TilePowered implements ISpecialInventory, ISid if (inventory.getStackInSlot(SLOT_CAN) != null) { FluidContainerData container = LiquidHelper.getLiquidContainer(inventory.getStackInSlot(SLOT_CAN)); - if (container != null && RecipeManager.isInput(container.fluid)) { + if (container != null && resourceTank.accepts(container.fluid.getFluid())) { inventory.setInventorySlotContents(SLOT_CAN, StackUtils.replenishByContainer(this, inventory.getStackInSlot(SLOT_CAN), container, resourceTank)); if (inventory.getStackInSlot(SLOT_CAN).stackSize <= 0) @@ -319,7 +322,7 @@ public class MachineStill extends TilePowered implements ISpecialInventory, ISid /* SMP GUI */ public void getGUINetworkData(int i, int j) { - + i -= tankManager.maxMessageId() + 1; switch (i) { case 0: distillationTime = j; @@ -331,8 +334,9 @@ public class MachineStill extends TilePowered implements ISpecialInventory, ISid } public void sendGUINetworkData(Container container, ICrafting iCrafting) { - iCrafting.sendProgressBarUpdate(container, 0, distillationTime); - iCrafting.sendProgressBarUpdate(container, 1, distillationTotalTime); + int i = tankManager.maxMessageId() + 1; + iCrafting.sendProgressBarUpdate(container, i, distillationTime); + iCrafting.sendProgressBarUpdate(container, i + 1, distillationTotalTime); } /* ISPECIALINVENTORY */ @@ -341,7 +345,7 @@ public class MachineStill extends TilePowered implements ISpecialInventory, ISid int inventorySlot; FluidContainerData container = LiquidHelper.getLiquidContainer(stack); - if (container != null && RecipeManager.isInput(container.fluid)) + if (container != null && resourceTank.accepts(container.fluid.getFluid())) inventorySlot = SLOT_CAN; else if (LiquidHelper.isEmptyContainer(stack)) inventorySlot = SLOT_RESOURCE; @@ -456,35 +460,45 @@ public class MachineStill extends TilePowered implements ISpecialInventory, ISid if(slotIndex == SLOT_CAN) { FluidContainerData container = LiquidHelper.getLiquidContainer(itemstack); - return container != null && RecipeManager.isInput(container.fluid); + return container != null && resourceTank.accepts(container.fluid.getFluid()); } return false; } - /* ILIQUIDCONTAINER */ + /* ILiquidTankContainer */ @Override public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + return tankManager.fill(from, resource, doFill); + } - if (!MachineStill.RecipeManager.isInput(resource)) - return 0; - - int used = resourceTank.fill(resource, doFill); - - if (doFill && used > 0) - sendNetworkUpdate(); - - return used; + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return tankManager.drain(from, resource, doDrain); } @Override public FluidStack drain(ForgeDirection from, int quantityMax, boolean doEmpty) { - return productTank.drain(quantityMax, doEmpty); + return tankManager.drain(from, quantityMax, doEmpty); } @Override - public ForestryTank[] getTanks() { - return new ForestryTank[] { resourceTank, productTank }; + public boolean canFill(ForgeDirection from, Fluid fluid) { + return tankManager.canFill(from, fluid); + } + + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return tankManager.canDrain(from, fluid); + } + + @Override + public TankManager getTankManager() { + return tankManager; + } + + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return tankManager.getTankInfo(from); } /* ITRIGGERPROVIDER */ diff --git a/src/main/java/forestry/factory/gadgets/MillRainmaker.java b/src/main/java/forestry/factory/gadgets/MillRainmaker.java index 75a349c33..3bbab49e7 100755 --- a/src/main/java/forestry/factory/gadgets/MillRainmaker.java +++ b/src/main/java/forestry/factory/gadgets/MillRainmaker.java @@ -34,7 +34,7 @@ public class MillRainmaker extends Mill implements ISpecialInventory { @Override public String getInventoryName() { - return "Rainmaker"; + return getUnlocalizedName(); } @Override diff --git a/src/main/java/forestry/factory/gadgets/TileWorktable.java b/src/main/java/forestry/factory/gadgets/TileWorktable.java index 693e93499..83f393db4 100755 --- a/src/main/java/forestry/factory/gadgets/TileWorktable.java +++ b/src/main/java/forestry/factory/gadgets/TileWorktable.java @@ -50,33 +50,19 @@ public class TileWorktable extends TileBase implements ICrafter { private final static RecipeBridge RECIPE_BRIDGE = new RecipeBridge(); private static class RecipeBridge { - - private final LinkedList overrides = new LinkedList(); - - public IRecipe getRecipe(InventoryCrafting crafting, World world) { - for (IRecipe recipe : overrides) { - if (recipe.matches(crafting, world)) - return recipe; - } - - for (Object obj : CraftingManager.getInstance().getRecipeList()) { - IRecipe recipe = (IRecipe) obj; - if (recipe.matches(crafting, world)) - return recipe; - } - - return null; + public ItemStack findMatchingRecipe(InventoryCrafting crafting, World world) { + return CraftingManager.getInstance().findMatchingRecipe(crafting, world); } } /* RECIPE MEMORY */ - public static final class Recipe implements IRecipe, INBTTagable { + public static final class Recipe implements INBTTagable { private InventoryAdapter matrix; private long lastUsed; private boolean locked; private World cachedWorld; - private IRecipe cachedRecipe; + private ItemStack cachedRecipeOutput; public Recipe(InventoryCrafting crafting) { this.matrix = new InventoryAdapter(new PlainInventory(crafting)); @@ -90,9 +76,9 @@ public class TileWorktable extends TileBase implements ICrafter { this.cachedWorld = world; } - private boolean updateCachedIRecipe() { + private boolean updateCachedRecipeOutput() { - if (cachedRecipe != null) + if (cachedRecipeOutput != null) return true; InventoryCrafting crafting = new InventoryCrafting(DUMMY_CONTAINER, 3, 3); @@ -100,8 +86,8 @@ public class TileWorktable extends TileBase implements ICrafter { crafting.setInventorySlotContents(i, matrix.getStackInSlot(i)); } - cachedRecipe = RECIPE_BRIDGE.getRecipe(crafting, cachedWorld); - return cachedRecipe != null; + cachedRecipeOutput = RECIPE_BRIDGE.findMatchingRecipe(crafting, cachedWorld); + return cachedRecipeOutput != null; } public void updateLastUse(World world) { @@ -117,18 +103,16 @@ public class TileWorktable extends TileBase implements ICrafter { return matrix; } - @Override public ItemStack getCraftingResult(InventoryCrafting inventorycrafting) { - if (updateCachedIRecipe()) - return cachedRecipe.getRecipeOutput(); + if (updateCachedRecipeOutput()) + return cachedRecipeOutput; return null; } - @Override public ItemStack getRecipeOutput() { - if (updateCachedIRecipe()) - return cachedRecipe.getRecipeOutput(); + if (updateCachedRecipeOutput()) + return cachedRecipeOutput; return null; } @@ -141,20 +125,17 @@ public class TileWorktable extends TileBase implements ICrafter { return this.locked; } - @Override public int getRecipeSize() { return matrix.getSizeInventory(); } - @Override - public boolean matches(InventoryCrafting crafting, World world) { - if (crafting.getSizeInventory() != matrix.getSizeInventory()) + public boolean hasSameOutput(InventoryCrafting crafting, World world) { + + if (!updateCachedRecipeOutput()) return false; - if (!updateCachedIRecipe()) - return false; - - return cachedRecipe.matches(crafting, world); + ItemStack recipeOutput = RECIPE_BRIDGE.findMatchingRecipe(crafting, world); + return recipeOutput != null && cachedRecipeOutput.isItemEqual(recipeOutput); } @Override @@ -193,29 +174,25 @@ public class TileWorktable extends TileBase implements ICrafter { private LinkedList recipes = new LinkedList(); private long lastUpdate; + public final int capacity = 9; public long getLastUpdate() { return lastUpdate; } - public Recipe getOrCreateRecipe(World world, InventoryCrafting crafting) { - - Recipe memory = getMemorized(crafting, world); - if (memory != null) { - return memory; - } - - return new Recipe(crafting); - } - - public void memorizeRecipe(World world, Recipe recipe) { + public void memorizeRecipe(World world, Recipe recipe, InventoryCrafting crafting) { lastUpdate = world.getTotalWorldTime(); recipe.updateLastUse(world); - if (recipes.contains(recipe)) + Recipe memory = getMemorized(crafting, world); + if (memory != null) { + int index = recipes.indexOf(memory); + recipes.set(index, recipe); return; - if (recipes.size() < 8) { + } + + if (recipes.size() < capacity) { recipes.add(recipe); return; } @@ -265,7 +242,7 @@ public class TileWorktable extends TileBase implements ICrafter { private Recipe getMemorized(InventoryCrafting crafting, World world) { for (Recipe recipe : recipes) { - if (recipe.matches(crafting, world)) + if (recipe.hasSameOutput(crafting, world)) return recipe; } @@ -361,6 +338,7 @@ public class TileWorktable extends TileBase implements ICrafter { } /* MEMBERS */ private Recipe currentRecipe; + private InventoryCrafting currentCrafting; private final RecipeMemory memorized; private final TileInventoryAdapter craftingInventory; private final TileInventoryAdapter accessibleInventory; @@ -372,11 +350,6 @@ public class TileWorktable extends TileBase implements ICrafter { memorized = new RecipeMemory(); } - @Override - public String getInventoryName() { - return "factory2.2"; - } - @Override public void openGui(EntityPlayer player, TileBase tile) { player.openGui(ForestryAPI.instance, GuiId.WorktableGUI.ordinal(), player.worldObj, xCoord, yCoord, zCoord); @@ -425,7 +398,7 @@ public class TileWorktable extends TileBase implements ICrafter { } public void chooseRecipe(int recipeIndex) { - if (recipeIndex == 9) { + if (recipeIndex >= memorized.capacity) { for (int slot = 0; slot < craftingInventory.getSizeInventory(); slot++) { craftingInventory.setInventorySlotContents(slot, null); } @@ -446,14 +419,20 @@ public class TileWorktable extends TileBase implements ICrafter { /* CRAFTING */ public void setRecipe(InventoryCrafting crafting) { - IRecipe recipe = RECIPE_BRIDGE.getRecipe(crafting, worldObj); - currentRecipe = recipe != null ? memorized.getOrCreateRecipe(worldObj, crafting) : null; - updateCraftResult(); + ItemStack recipeOutput = RECIPE_BRIDGE.findMatchingRecipe(crafting, worldObj); + if (recipeOutput == null) { + currentRecipe = null; + currentCrafting = null; + } else { + currentRecipe = new Recipe(crafting); + currentCrafting = crafting; + } + updateCraftResult(currentCrafting); } - private void updateCraftResult() { + private void updateCraftResult(InventoryCrafting inventorycrafting) { if (currentRecipe != null) { - ItemStack result = currentRecipe.getCraftingResult(null); + ItemStack result = currentRecipe.getCraftingResult(inventorycrafting); if (result != null) { craftingInventory.setInventorySlotContents(SLOT_CRAFTING_RESULT, result.copy()); return; @@ -463,57 +442,83 @@ public class TileWorktable extends TileBase implements ICrafter { craftingInventory.setInventorySlotContents(SLOT_CRAFTING_RESULT, null); } - private boolean validateResources() { - // Need at least one matched set + private boolean canCraftCurrentRecipe() { if (currentRecipe == null) return false; - return StackUtils.containsSets(currentRecipe.getMatrix().getStacks(SLOT_CRAFTING_1, 9), accessibleInventory.getStacks(SLOT_INVENTORY_1, SLOT_INVENTORY_COUNT), currentRecipe.getRecipeOutput(), true, true) > 0; - } - private void removeResources(EntityPlayer player) { - removeSets(1, craftingInventory.getStacks(SLOT_CRAFTING_1, 9), player); - } + // Need at least one matched set + ItemStack[] set = craftingInventory.getStacks(SLOT_CRAFTING_1, 9); + ItemStack[] stock = accessibleInventory.getStacks(SLOT_INVENTORY_1, SLOT_INVENTORY_COUNT); + if (StackUtils.containsSets(set, stock, true, true) == 0) + return false; - private void removeSets(int count, ItemStack[] set, EntityPlayer player) { + // Check that it doesn't make a different recipe. + // For example: + // Wood Logs are all ore dictionary equivalent with each other, + // but an Oak Log shouldn't be able to make Ebony Wood Planks + // because it makes Oak Wood Planks using the same recipe. + // Strategy: + // Create a fake crafting inventory using items we have in stock + // in place of the ones in the saved crafting inventory. + // Check that the recipe it makes is the same as the currentRecipe. + InventoryCrafting crafting = new InventoryCrafting(DUMMY_CONTAINER, 3, 3); + ItemStack[] stockCopy = StackUtils.condenseStacks(stock); - for (int i = 0; i < count; i++) { - ItemStack[] condensedSet = StackUtils.condenseStacks(set); - for (ItemStack req : condensedSet) { - for (int j = SLOT_INVENTORY_1; j < SLOT_INVENTORY_1 + SLOT_INVENTORY_COUNT; j++) { - ItemStack pol = accessibleInventory.getStackInSlot(j); - if (pol == null) - continue; + for (int slot = 0; slot < currentCrafting.getSizeInventory(); slot++) { + ItemStack recipeStack = currentCrafting.getStackInSlot(slot); + if (recipeStack == null) + continue; - if (!StackUtils.isCraftingEquivalent(pol, req, true, true)) - continue; + // Use crafting equivalent (not oredict) items first + for (ItemStack stockStack : stockCopy) { + if (stockStack.stackSize > 0 && StackUtils.isCraftingEquivalent(recipeStack, stockStack, false, false)) { + ItemStack stack = new ItemStack(stockStack.getItem(), 1, stockStack.getItemDamage()); + stockStack.stackSize--; + crafting.setInventorySlotContents(slot, stack); + break; + } + } - ItemStack removed = accessibleInventory.decrStackSize(j, req.stackSize); - req.stackSize -= removed.stackSize; - - if (req.getItem().hasContainerItem(req)) - StackUtils.stowContainerItem(removed, accessibleInventory, j, player); - if (req.stackSize <= 0) + // Use oredict items if crafting equivalent items aren't available + if (crafting.getStackInSlot(slot) == null) { + for (ItemStack stockStack : stockCopy) { + if (stockStack.stackSize > 0 && StackUtils.isCraftingEquivalent(recipeStack, stockStack, true, true)) { + ItemStack stack = new ItemStack(stockStack.getItem(), 1, stockStack.getItemDamage()); + stockStack.stackSize--; + crafting.setInventorySlotContents(slot, stack); break; + } } } } + ItemStack recipeOutput = RECIPE_BRIDGE.findMatchingRecipe(crafting, worldObj); + if (recipeOutput == null) + return false; + return recipeOutput.isItemEqual(currentRecipe.getRecipeOutput()); + } + + private boolean removeResources(EntityPlayer player) { + ItemStack[] set = craftingInventory.getStacks(SLOT_CRAFTING_1, 9); + return accessibleInventory.removeSets(1, set, SLOT_INVENTORY_1, SLOT_INVENTORY_COUNT, player, true, true, true); } @Override public boolean canTakeStack(int slotIndex) { - return validateResources(); + if (slotIndex == SLOT_CRAFTING_RESULT) + return canCraftCurrentRecipe(); + return true; } @Override public ItemStack takenFromSlot(int slotIndex, boolean consumeRecipe, EntityPlayer player) { - if (!validateResources()) + if (!removeResources(player)) return null; if (Proxies.common.isSimulating(worldObj)) - memorized.memorizeRecipe(worldObj, currentRecipe); - removeResources(player); - updateCraftResult(); + memorized.memorizeRecipe(worldObj, currentRecipe, currentCrafting); + + updateCraftResult(currentCrafting); return currentRecipe.getRecipeOutput().copy(); } diff --git a/src/main/java/forestry/factory/gui/ContainerBottler.java b/src/main/java/forestry/factory/gui/ContainerBottler.java index 228968e54..3a891e8a7 100755 --- a/src/main/java/forestry/factory/gui/ContainerBottler.java +++ b/src/main/java/forestry/factory/gui/ContainerBottler.java @@ -42,19 +42,6 @@ public class ContainerBottler extends ContainerLiquidTanks { } - // @Override client side only - public void updateProgressBar(int i, int j) { - tile.getGUINetworkData(i, j); - } - - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); - - for (int i = 0; i < crafters.size(); i++) - tile.sendGUINetworkData(this, (ICrafting) crafters.get(i)); - } - @Override public boolean canInteractWith(EntityPlayer entityplayer) { return tile.isUseableByPlayer(entityplayer); diff --git a/src/main/java/forestry/factory/gui/ContainerCarpenter.java b/src/main/java/forestry/factory/gui/ContainerCarpenter.java index ccbf2d96d..acd15dd2a 100755 --- a/src/main/java/forestry/factory/gui/ContainerCarpenter.java +++ b/src/main/java/forestry/factory/gui/ContainerCarpenter.java @@ -12,7 +12,6 @@ package forestry.factory.gui; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.ICrafting; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryCraftResult; import net.minecraft.inventory.Slot; @@ -110,19 +109,9 @@ public class ContainerCarpenter extends ContainerLiquidTanks implements IContain } } - @Override - public void updateProgressBar(int i, int j) { - machine.getGUINetworkData(i, j); - } - @Override public void detectAndSendChanges() { super.detectAndSendChanges(); - - for (int i = 0; i < crafters.size(); i++) { - machine.sendGUINetworkData(this, (ICrafting) crafters.get(i)); - } - updateProductSlot(); } @@ -150,8 +139,7 @@ public class ContainerCarpenter extends ContainerLiquidTanks implements IContain private void resetProductDisplay() { if (machine != null) { - machine.setCurrentRecipe(MachineCarpenter.RecipeManager.findMatchingRecipe(machine.resourceTank.getFluid(), machine.getBoxStack(), craftMatrix, - machine.getWorldObj())); + machine.resetProductDisplay(craftMatrix); updateProductSlot(); } } diff --git a/src/main/java/forestry/factory/gui/ContainerFabricator.java b/src/main/java/forestry/factory/gui/ContainerFabricator.java index 1ff1e592d..1ed6cef6e 100755 --- a/src/main/java/forestry/factory/gui/ContainerFabricator.java +++ b/src/main/java/forestry/factory/gui/ContainerFabricator.java @@ -55,17 +55,4 @@ public class ContainerFabricator extends ContainerLiquidTanks { } - // @Override client side only - public void updateProgressBar(int i, int j) { - tile.getGUINetworkData(i, j); - } - - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); - - for (int i = 0; i < crafters.size(); i++) - tile.sendGUINetworkData(this, (ICrafting) crafters.get(i)); - } - } diff --git a/src/main/java/forestry/factory/gui/ContainerFermenter.java b/src/main/java/forestry/factory/gui/ContainerFermenter.java index d28bd1774..e7aa3acb3 100755 --- a/src/main/java/forestry/factory/gui/ContainerFermenter.java +++ b/src/main/java/forestry/factory/gui/ContainerFermenter.java @@ -43,19 +43,6 @@ public class ContainerFermenter extends ContainerLiquidTanks { } - @Override - public void updateProgressBar(int i, int j) { - fermenter.getGUINetworkData(i, j); - } - - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); - - for (int i = 0; i < crafters.size(); i++) - fermenter.sendGUINetworkData(this, (ICrafting) crafters.get(i)); - } - @Override public boolean canInteractWith(EntityPlayer entityplayer) { return fermenter.isUseableByPlayer(entityplayer); diff --git a/src/main/java/forestry/factory/gui/ContainerMoistener.java b/src/main/java/forestry/factory/gui/ContainerMoistener.java index 9e4363671..d51d771e8 100755 --- a/src/main/java/forestry/factory/gui/ContainerMoistener.java +++ b/src/main/java/forestry/factory/gui/ContainerMoistener.java @@ -57,19 +57,6 @@ public class ContainerMoistener extends ContainerLiquidTanks implements IContain } - // @Override client side only - public void updateProgressBar(int i, int j) { - tile.getGUINetworkData(i, j); - } - - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); - - for (int i = 0; i < crafters.size(); i++) - tile.sendGUINetworkData(this, (ICrafting) crafters.get(i)); - } - @Override public void onCraftMatrixChanged(IInventory iinventory, int slot) { inventory.setInventorySlotContents(slot, iinventory.getStackInSlot(slot)); diff --git a/src/main/java/forestry/factory/gui/ContainerRaintank.java b/src/main/java/forestry/factory/gui/ContainerRaintank.java index 253014dda..ad0b0afa6 100755 --- a/src/main/java/forestry/factory/gui/ContainerRaintank.java +++ b/src/main/java/forestry/factory/gui/ContainerRaintank.java @@ -40,19 +40,6 @@ public class ContainerRaintank extends ContainerLiquidTanks { } - // @Override client side only - public void updateProgressBar(int i, int j) { - tile.getGUINetworkData(i, j); - } - - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); - - for (int i = 0; i < crafters.size(); i++) - tile.sendGUINetworkData(this, (ICrafting) crafters.get(i)); - } - @Override public boolean canInteractWith(EntityPlayer entityplayer) { return tile.isUseableByPlayer(entityplayer); diff --git a/src/main/java/forestry/factory/gui/ContainerSqueezer.java b/src/main/java/forestry/factory/gui/ContainerSqueezer.java index 246ae162f..7c236ca59 100755 --- a/src/main/java/forestry/factory/gui/ContainerSqueezer.java +++ b/src/main/java/forestry/factory/gui/ContainerSqueezer.java @@ -50,17 +50,4 @@ public class ContainerSqueezer extends ContainerLiquidTanks { addSlot(new Slot(player, j1, 8 + j1 * 18, 142)); } - @Override - public void updateProgressBar(int i, int j) { - tile.getGUINetworkData(i, j); - } - - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); - - for (int i = 0; i < crafters.size(); i++) - tile.sendGUINetworkData(this, (ICrafting) crafters.get(i)); - } - } diff --git a/src/main/java/forestry/factory/gui/ContainerStill.java b/src/main/java/forestry/factory/gui/ContainerStill.java index fe7ce5a7d..fa384ee0f 100755 --- a/src/main/java/forestry/factory/gui/ContainerStill.java +++ b/src/main/java/forestry/factory/gui/ContainerStill.java @@ -39,19 +39,6 @@ public class ContainerStill extends ContainerLiquidTanks { } - // @Override client side only - public void updateProgressBar(int i, int j) { - processor.getGUINetworkData(i, j); - } - - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); - - for (int i = 0; i < crafters.size(); i++) - processor.sendGUINetworkData(this, (ICrafting) crafters.get(i)); - } - @Override public boolean canInteractWith(EntityPlayer entityplayer) { return processor.isUseableByPlayer(entityplayer); diff --git a/src/main/java/forestry/factory/gui/ContainerWorktable.java b/src/main/java/forestry/factory/gui/ContainerWorktable.java index 9ffcab696..62a190aec 100755 --- a/src/main/java/forestry/factory/gui/ContainerWorktable.java +++ b/src/main/java/forestry/factory/gui/ContainerWorktable.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.factory.gui; +import forestry.core.utils.StackUtils; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryCraftResult; @@ -25,6 +26,7 @@ import forestry.core.network.PacketPayload; import forestry.core.network.PacketUpdate; import forestry.core.proxy.Proxies; import forestry.factory.gadgets.TileWorktable; +import net.minecraft.item.ItemStack; public class ContainerWorktable extends ContainerForestry implements IContainerCrafting, IGuiSelectable { @@ -91,10 +93,16 @@ public class ContainerWorktable extends ContainerForestry implements IContainerC @Override public void onCraftMatrixChanged(IInventory iinventory, int slot) { -// craftingInventory.setInventorySlotContents(slot, iinventory.getStackInSlot(slot)); - if (slot < craftMatrix.getSizeInventory()) - craftMatrix.setInventorySlotContents(slot, iinventory.getStackInSlot(slot)); - updateRecipe(); + if (slot >= craftMatrix.getSizeInventory()) + return; + + ItemStack stack = iinventory.getStackInSlot(slot); + ItemStack currentStack = craftMatrix.getStackInSlot(slot); + + if (!StackUtils.isIdenticalItem(stack, currentStack)) { + craftMatrix.setInventorySlotContents(slot, stack); + updateRecipe(); + } } private void updateMatrix() { @@ -107,6 +115,10 @@ public class ContainerWorktable extends ContainerForestry implements IContainerC tile.setRecipe(craftMatrix); } + public void clearRecipe() { + sendRecipeClick(0, tile.getMemory().capacity); + } + public void sendRecipeClick(int mouseButton, int recipeIndex) { PacketPayload payload = new PacketPayload(2, 0, 0); payload.intPayload[0] = mouseButton; diff --git a/src/main/java/forestry/factory/gui/GuiBottler.java b/src/main/java/forestry/factory/gui/GuiBottler.java index a2ff20397..fd24dc271 100755 --- a/src/main/java/forestry/factory/gui/GuiBottler.java +++ b/src/main/java/forestry/factory/gui/GuiBottler.java @@ -13,25 +13,17 @@ package forestry.factory.gui; import net.minecraft.entity.player.InventoryPlayer; import forestry.core.config.Defaults; -import forestry.core.gui.GuiForestry; +import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.widgets.TankWidget; -import forestry.core.utils.StringUtil; import forestry.factory.gadgets.MachineBottler; -public class GuiBottler extends GuiForestry { +public class GuiBottler extends GuiForestryTitled { public GuiBottler(InventoryPlayer inventory, MachineBottler processor) { super(Defaults.TEXTURE_PATH_GUI + "/bottler.png", new ContainerBottler(inventory, processor), processor); widgetManager.add(new TankWidget(this.widgetManager, 53, 17, 0)); } - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - super.drawGuiContainerForegroundLayer(mouseX, mouseY); - String name = StringUtil.localize("tile.for." + tile.getInventoryName()); - this.fontRendererObj.drawString(name, getCenteredOffset(name), 6, fontColor.get("gui.title")); - } - @Override protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); diff --git a/src/main/java/forestry/factory/gui/GuiCarpenter.java b/src/main/java/forestry/factory/gui/GuiCarpenter.java index 102cf0666..655e8df89 100755 --- a/src/main/java/forestry/factory/gui/GuiCarpenter.java +++ b/src/main/java/forestry/factory/gui/GuiCarpenter.java @@ -13,12 +13,11 @@ package forestry.factory.gui; import net.minecraft.entity.player.InventoryPlayer; import forestry.core.config.Defaults; -import forestry.core.gui.GuiForestry; +import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.widgets.TankWidget; -import forestry.core.utils.StringUtil; import forestry.factory.gadgets.MachineCarpenter; -public class GuiCarpenter extends GuiForestry { +public class GuiCarpenter extends GuiForestryTitled { public GuiCarpenter(InventoryPlayer inventory, MachineCarpenter tile) { super(Defaults.TEXTURE_PATH_GUI + "/carpenter.png", new ContainerCarpenter(inventory, tile), tile); @@ -33,13 +32,6 @@ public class GuiCarpenter extends GuiForestry { inventorySlots.onContainerClosed(mc.thePlayer); } - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - super.drawGuiContainerForegroundLayer(mouseX, mouseY); - String name = StringUtil.localize("tile.for." + tile.getInventoryName()); - this.fontRendererObj.drawString(name, getCenteredOffset(name), 6, fontColor.get("gui.title")); - } - @Override protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); diff --git a/src/main/java/forestry/factory/gui/GuiCentrifuge.java b/src/main/java/forestry/factory/gui/GuiCentrifuge.java index 254c8d720..dde1b62c8 100755 --- a/src/main/java/forestry/factory/gui/GuiCentrifuge.java +++ b/src/main/java/forestry/factory/gui/GuiCentrifuge.java @@ -13,23 +13,15 @@ package forestry.factory.gui; import net.minecraft.entity.player.InventoryPlayer; import forestry.core.config.Defaults; -import forestry.core.gui.GuiForestry; -import forestry.core.utils.StringUtil; +import forestry.core.gui.GuiForestryTitled; import forestry.factory.gadgets.MachineCentrifuge; -public class GuiCentrifuge extends GuiForestry { +public class GuiCentrifuge extends GuiForestryTitled { public GuiCentrifuge(InventoryPlayer inventory, MachineCentrifuge tile) { super(Defaults.TEXTURE_PATH_GUI + "/centrifuge.png", new ContainerCentrifuge(inventory, tile), tile); } - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - super.drawGuiContainerForegroundLayer(mouseX, mouseY); - String name = StringUtil.localize("tile.for." + tile.getInventoryName()); - this.fontRendererObj.drawString(name, getCenteredOffset(name), 6, fontColor.get("gui.title")); - } - @Override protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); diff --git a/src/main/java/forestry/factory/gui/GuiFabricator.java b/src/main/java/forestry/factory/gui/GuiFabricator.java index 626bd509f..e15044361 100755 --- a/src/main/java/forestry/factory/gui/GuiFabricator.java +++ b/src/main/java/forestry/factory/gui/GuiFabricator.java @@ -13,12 +13,11 @@ package forestry.factory.gui; import net.minecraft.entity.player.InventoryPlayer; import forestry.core.config.Defaults; -import forestry.core.gui.GuiForestry; +import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.widgets.ReservoirWidget; -import forestry.core.utils.StringUtil; import forestry.factory.gadgets.MachineFabricator; -public class GuiFabricator extends GuiForestry { +public class GuiFabricator extends GuiForestryTitled { public GuiFabricator(InventoryPlayer player, MachineFabricator tile) { super(Defaults.TEXTURE_PATH_GUI + "/fabricator.png", new ContainerFabricator(player, tile), tile); @@ -26,13 +25,6 @@ public class GuiFabricator extends GuiForestry { widgetManager.add(new ReservoirWidget(this.widgetManager, 26, 48, 0)); } - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - super.drawGuiContainerForegroundLayer(mouseX, mouseY); - String name = StringUtil.localize("tile.for." + tile.getInventoryName()); - this.fontRendererObj.drawString(name, getCenteredOffset(name), 6, fontColor.get("gui.title")); - } - @Override protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); diff --git a/src/main/java/forestry/factory/gui/GuiFermenter.java b/src/main/java/forestry/factory/gui/GuiFermenter.java index 23ca2d97f..1d51ba00b 100755 --- a/src/main/java/forestry/factory/gui/GuiFermenter.java +++ b/src/main/java/forestry/factory/gui/GuiFermenter.java @@ -13,12 +13,11 @@ package forestry.factory.gui; import net.minecraft.entity.player.InventoryPlayer; import forestry.core.config.Defaults; -import forestry.core.gui.GuiForestry; +import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.widgets.TankWidget; -import forestry.core.utils.StringUtil; import forestry.factory.gadgets.MachineFermenter; -public class GuiFermenter extends GuiForestry { +public class GuiFermenter extends GuiForestryTitled { public GuiFermenter(InventoryPlayer inventory, MachineFermenter tile) { super(Defaults.TEXTURE_PATH_GUI + "/fermenter.png", new ContainerFermenter(inventory, tile), tile); @@ -26,13 +25,6 @@ public class GuiFermenter extends GuiForestry { widgetManager.add(new TankWidget(this.widgetManager, 125, 19, 1)); } - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - super.drawGuiContainerForegroundLayer(mouseX, mouseY); - String name = StringUtil.localize("tile.for." + tile.getInventoryName()); - this.fontRendererObj.drawString(name, getCenteredOffset(name), 6, fontColor.get("gui.title")); - } - @Override protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); diff --git a/src/main/java/forestry/factory/gui/GuiMoistener.java b/src/main/java/forestry/factory/gui/GuiMoistener.java index 8b0b118dc..e4fbd864d 100755 --- a/src/main/java/forestry/factory/gui/GuiMoistener.java +++ b/src/main/java/forestry/factory/gui/GuiMoistener.java @@ -13,25 +13,17 @@ package forestry.factory.gui; import net.minecraft.entity.player.InventoryPlayer; import forestry.core.config.Defaults; -import forestry.core.gui.GuiForestry; +import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.widgets.TankWidget; -import forestry.core.utils.StringUtil; import forestry.factory.gadgets.MachineMoistener; -public class GuiMoistener extends GuiForestry { +public class GuiMoistener extends GuiForestryTitled { public GuiMoistener(InventoryPlayer inventory, MachineMoistener tile) { super(Defaults.TEXTURE_PATH_GUI + "/moistener.png", new ContainerMoistener(inventory, tile), tile); widgetManager.add(new TankWidget(this.widgetManager, 16, 16, 0)); } - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - super.drawGuiContainerForegroundLayer(mouseX, mouseY); - String name = StringUtil.localize("tile.for." + tile.getInventoryName()); - this.fontRendererObj.drawString(name, getCenteredOffset(name), 6, fontColor.get("gui.title")); - } - @Override protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); diff --git a/src/main/java/forestry/factory/gui/GuiRaintank.java b/src/main/java/forestry/factory/gui/GuiRaintank.java index 044ed9a07..02a93a01c 100755 --- a/src/main/java/forestry/factory/gui/GuiRaintank.java +++ b/src/main/java/forestry/factory/gui/GuiRaintank.java @@ -13,25 +13,17 @@ package forestry.factory.gui; import net.minecraft.entity.player.InventoryPlayer; import forestry.core.config.Defaults; -import forestry.core.gui.GuiForestry; +import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.widgets.TankWidget; -import forestry.core.utils.StringUtil; import forestry.factory.gadgets.MachineRaintank; -public class GuiRaintank extends GuiForestry { +public class GuiRaintank extends GuiForestryTitled { public GuiRaintank(InventoryPlayer inventory, MachineRaintank tile) { super(Defaults.TEXTURE_PATH_GUI + "/raintank.png", new ContainerRaintank(inventory, tile), tile); widgetManager.add(new TankWidget(this.widgetManager, 53, 17, 0)); } - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - super.drawGuiContainerForegroundLayer(mouseX, mouseY); - String name = StringUtil.localize("tile.for." + tile.getInventoryName()); - this.fontRendererObj.drawString(name, getCenteredOffset(name), 6, fontColor.get("gui.title")); - } - @Override protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); diff --git a/src/main/java/forestry/factory/gui/GuiSqueezer.java b/src/main/java/forestry/factory/gui/GuiSqueezer.java index c09c07dc1..93797d6ec 100755 --- a/src/main/java/forestry/factory/gui/GuiSqueezer.java +++ b/src/main/java/forestry/factory/gui/GuiSqueezer.java @@ -13,25 +13,17 @@ package forestry.factory.gui; import net.minecraft.entity.player.InventoryPlayer; import forestry.core.config.Defaults; -import forestry.core.gui.GuiForestry; +import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.widgets.TankWidget; -import forestry.core.utils.StringUtil; import forestry.factory.gadgets.MachineSqueezer; -public class GuiSqueezer extends GuiForestry { +public class GuiSqueezer extends GuiForestryTitled { public GuiSqueezer(InventoryPlayer inventory, MachineSqueezer tile) { super(Defaults.TEXTURE_PATH_GUI + "/squeezer.png", new ContainerSqueezer(inventory, tile), tile); widgetManager.add(new TankWidget(this.widgetManager, 85, 15, 0)); } - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - super.drawGuiContainerForegroundLayer(mouseX, mouseY); - String name = StringUtil.localize("tile.for." + tile.getInventoryName()); - this.fontRendererObj.drawString(name, getCenteredOffset(name), 6, fontColor.get("gui.title")); - } - @Override protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); diff --git a/src/main/java/forestry/factory/gui/GuiStill.java b/src/main/java/forestry/factory/gui/GuiStill.java index 74f8f437c..2fcb8cd1f 100755 --- a/src/main/java/forestry/factory/gui/GuiStill.java +++ b/src/main/java/forestry/factory/gui/GuiStill.java @@ -13,12 +13,11 @@ package forestry.factory.gui; import net.minecraft.entity.player.InventoryPlayer; import forestry.core.config.Defaults; -import forestry.core.gui.GuiForestry; +import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.widgets.TankWidget; -import forestry.core.utils.StringUtil; import forestry.factory.gadgets.MachineStill; -public class GuiStill extends GuiForestry { +public class GuiStill extends GuiForestryTitled { public GuiStill(InventoryPlayer inventory, MachineStill tile) { super(Defaults.TEXTURE_PATH_GUI + "/still.png", new ContainerStill(inventory, tile), tile); @@ -26,13 +25,6 @@ public class GuiStill extends GuiForestry { widgetManager.add(new TankWidget(this.widgetManager, 125, 15, 1)); } - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - super.drawGuiContainerForegroundLayer(mouseX, mouseY); - String name = StringUtil.localize("tile.for." + tile.getInventoryName()); - this.fontRendererObj.drawString(name, getCenteredOffset(name), 6, fontColor.get("gui.title")); - } - @Override protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); diff --git a/src/main/java/forestry/factory/gui/GuiWorktable.java b/src/main/java/forestry/factory/gui/GuiWorktable.java index a909d4913..dc1458003 100755 --- a/src/main/java/forestry/factory/gui/GuiWorktable.java +++ b/src/main/java/forestry/factory/gui/GuiWorktable.java @@ -19,7 +19,7 @@ import net.minecraft.item.ItemStack; import org.lwjgl.opengl.GL11; import forestry.core.config.Defaults; -import forestry.core.gui.GuiForestry; +import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.WidgetManager; import forestry.core.gui.widgets.Widget; import forestry.core.proxy.Proxies; @@ -28,7 +28,7 @@ import forestry.core.render.TextureManager; import forestry.core.utils.StringUtil; import forestry.factory.gadgets.TileWorktable; -public class GuiWorktable extends GuiForestry { +public class GuiWorktable extends GuiForestryTitled { private class MemorizedSlot extends Widget { @@ -58,6 +58,7 @@ public class GuiWorktable extends GuiForestry { //RenderHelper.disableStandardItemLighting(); GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glEnable(GL11.GL_BLEND); if (worktable.getMemory().isLocked(slotNumber)) { manager.gui.setZLevel(110f); @@ -81,67 +82,46 @@ public class GuiWorktable extends GuiForestry { } } - private class BookSlot extends Widget { + private class ClearWorktable extends Widget { - private final ItemStack BOOK = new ItemStack(Items.book); - - public BookSlot(WidgetManager manager, int xPos, int yPos) { + public ClearWorktable(WidgetManager manager, int xPos, int yPos) { super(manager, xPos, yPos); + width = 7; + height = 7; } @Override public void draw(int startX, int startY) { - GL11.glPushAttrib(GL11.GL_ENABLE_BIT); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_DEPTH_TEST); - RenderHelper.enableGUIStandardItemLighting(); - OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240, 240); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - - manager.gui.drawItemStack(BOOK, startX + xPos, startY + yPos); - - GL11.glPopAttrib(); - } - - @Override - protected String getLegacyTooltip(EntityPlayer player) { - return StringUtil.localize("gui.worktable.clear"); } @Override public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { - container.sendRecipeClick(mouseButton, 9); + container.clearRecipe(); } } private final TileWorktable worktable; protected ContainerWorktable container; public GuiWorktable(EntityPlayer player, TileWorktable tile) { - super(Defaults.TEXTURE_PATH_GUI + "/worktable.png", new ContainerWorktable(player, tile)); + super(Defaults.TEXTURE_PATH_GUI + "/worktable2.png", new ContainerWorktable(player, tile), tile); ySize = 218; worktable = tile; this.tile = tile; container = (ContainerWorktable) inventorySlots; - widgetManager.add(new BookSlot(widgetManager, 128, 38)); + final int spacing = 18; + int slot = 0; + for (int y = 0; y < 3; y++) { + int yPos = 20 + (y * spacing); + for (int x = 0; x < 3; x++) { + int xPos = 110 + (x * spacing); + widgetManager.add(new MemorizedSlot(widgetManager, xPos, yPos, slot)); + slot += 1; + } + } - widgetManager.add(new MemorizedSlot(widgetManager, 146, 20, 0)); - widgetManager.add(new MemorizedSlot(widgetManager, 146, 38, 1)); - widgetManager.add(new MemorizedSlot(widgetManager, 146, 56, 2)); - - widgetManager.add(new MemorizedSlot(widgetManager, 128, 56, 3)); - widgetManager.add(new MemorizedSlot(widgetManager, 110, 56, 4)); - - widgetManager.add(new MemorizedSlot(widgetManager, 110, 38, 5)); - widgetManager.add(new MemorizedSlot(widgetManager, 110, 20, 6)); - widgetManager.add(new MemorizedSlot(widgetManager, 128, 20, 7)); + widgetManager.add(new ClearWorktable(widgetManager, 66, 19)); } - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - super.drawGuiContainerForegroundLayer(mouseX, mouseY); - String name = StringUtil.localize("tile.for." + tile.getInventoryName()); - this.fontRendererObj.drawString(name, getCenteredOffset(name), 6, fontColor.get("gui.title")); - } } diff --git a/src/main/java/forestry/farming/circuits/CircuitFarmLogic.java b/src/main/java/forestry/farming/circuits/CircuitFarmLogic.java index 3a95355e6..d8beda9e9 100755 --- a/src/main/java/forestry/farming/circuits/CircuitFarmLogic.java +++ b/src/main/java/forestry/farming/circuits/CircuitFarmLogic.java @@ -23,8 +23,8 @@ public class CircuitFarmLogic extends Circuit { private Class logicClass; private boolean isManual = false; - public CircuitFarmLogic(String uid, Class logicClass, String[] descriptions) { - super(uid, false, uid, descriptions); + public CircuitFarmLogic(String uid, Class logicClass) { + super(uid, false); this.logicClass = logicClass; setLimit(4); } diff --git a/src/main/java/forestry/farming/gadgets/BlockMushroom.java b/src/main/java/forestry/farming/gadgets/BlockMushroom.java index bb47886ae..366b6a6ce 100755 --- a/src/main/java/forestry/farming/gadgets/BlockMushroom.java +++ b/src/main/java/forestry/farming/gadgets/BlockMushroom.java @@ -11,12 +11,16 @@ package forestry.farming.gadgets; import java.util.ArrayList; +import java.util.List; import java.util.Random; +import forestry.core.IItemTyped; import net.minecraft.block.Block; import net.minecraft.block.BlockSapling; import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; +import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.world.World; @@ -29,7 +33,11 @@ import forestry.core.config.Defaults; import forestry.core.proxy.Proxies; import forestry.farming.worldgen.WorldGenBigMushroom; -public class BlockMushroom extends BlockSapling { +public class BlockMushroom extends BlockSapling implements IItemTyped { + + public enum MushroomType { + BROWN, RED; + } private final WorldGenerator[] generators; private final ItemStack[] drops; @@ -53,8 +61,9 @@ public class BlockMushroom extends BlockSapling { public ArrayList getDrops(World world, int X, int Y, int Z, int metadata, int fortune) { ArrayList ret = new ArrayList(); - int type = metadata & 0x03; - ret.add(drops[type]); + MushroomType type = getTypeFromMeta(metadata); + + ret.add(drops[type.ordinal()]); return ret; } @@ -71,13 +80,13 @@ public class BlockMushroom extends BlockSapling { return; int meta = world.getBlockMetadata(i, j, k); - int type = meta & 0x03; + MushroomType type = getTypeFromMeta(meta); int maturity = meta >> 2; tickGermling(world, i, j, k, random, type, maturity); } - private void tickGermling(World world, int i, int j, int k, Random random, int type, int maturity) { + private void tickGermling(World world, int i, int j, int k, Random random, MushroomType type, int maturity) { int lightvalue = world.getBlockLightValue(i, j + 1, k); @@ -87,7 +96,7 @@ public class BlockMushroom extends BlockSapling { if (maturity != 3) { maturity = 3; int matX = maturity << 2; - int meta = (matX | type); + int meta = (matX | type.ordinal()); world.setBlockMetadataWithNotify(i, j, k, meta, Defaults.FLAG_BLOCK_SYNCH); } else if (lightvalue <= 7) func_149878_d(world, i, j, k, random); @@ -105,7 +114,22 @@ public class BlockMushroom extends BlockSapling { world.setBlock(i, j, k, this, type, 0); } + @Override + public MushroomType getTypeFromMeta(int meta) { + meta %= 3; + if (meta >= MushroomType.values().length) + return null; + return MushroomType.values()[meta]; + } + /* ICONS */ + @SideOnly(Side.CLIENT) + @Override + public void getSubBlocks(Item item, CreativeTabs tab, List list) { + list.add(new ItemStack(item, 1, 0)); + list.add(new ItemStack(item, 1, 1)); + } + @SideOnly(Side.CLIENT) @Override public void registerBlockIcons(IIconRegister register) { @@ -114,11 +138,14 @@ public class BlockMushroom extends BlockSapling { @SideOnly(Side.CLIENT) @Override public IIcon getIcon(int side, int meta) { - int type = meta & 0x03; - if (type > 0) + MushroomType type = getTypeFromMeta(meta); + + if (type == MushroomType.BROWN) + return Blocks.brown_mushroom.getIcon(side, meta); + else if (type == MushroomType.RED) return Blocks.red_mushroom.getIcon(side, meta); else - return Blocks.brown_mushroom.getIcon(side, meta); + return null; } } diff --git a/src/main/java/forestry/farming/gadgets/TileFarm.java b/src/main/java/forestry/farming/gadgets/TileFarm.java index 82076a604..c25424b1b 100755 --- a/src/main/java/forestry/farming/gadgets/TileFarm.java +++ b/src/main/java/forestry/farming/gadgets/TileFarm.java @@ -284,7 +284,7 @@ public abstract class TileFarm extends TileForestry implements IFarmComponent { @Override public ITileStructure getCentralTE() { - if (!isIntegratedIntoStructure()) + if (!isIntegratedIntoStructure() || !hasMaster()) return null; if (!isMaster) { @@ -349,11 +349,6 @@ public abstract class TileFarm extends TileForestry implements IFarmComponent { public void removeListener(IFarmListener listener) { } - @Override - public String getInventoryName() { - return "Farm"; - } - /* INTERACTION */ @Override public boolean isUseableByPlayer(EntityPlayer player) { diff --git a/src/main/java/forestry/farming/gadgets/TileFarmPlain.java b/src/main/java/forestry/farming/gadgets/TileFarmPlain.java index ec3123714..e38ece0da 100755 --- a/src/main/java/forestry/farming/gadgets/TileFarmPlain.java +++ b/src/main/java/forestry/farming/gadgets/TileFarmPlain.java @@ -19,6 +19,7 @@ import java.util.Set; import java.util.Stack; import java.util.TreeMap; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.ICrafting; import net.minecraft.item.ItemStack; @@ -28,8 +29,11 @@ import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData; +import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; import forestry.api.circuits.ChipsetManager; import forestry.api.circuits.ICircuitBoard; @@ -48,9 +52,12 @@ import forestry.core.config.Defaults; import forestry.core.interfaces.IClimatised; import forestry.core.interfaces.IHintSource; import forestry.core.interfaces.ISocketable; +import forestry.core.interfaces.ILiquidTankContainer; import forestry.core.proxy.Proxies; import forestry.core.utils.DelayTimer; -import forestry.core.utils.ForestryTank; +import forestry.core.fluids.tanks.StandardTank; +import forestry.core.fluids.tanks.FilteredTank; +import forestry.core.fluids.TankManager; import forestry.core.utils.InventoryAdapter; import forestry.core.utils.LiquidHelper; import forestry.core.utils.StackUtils; @@ -60,7 +67,7 @@ import forestry.farming.FarmTarget; import forestry.farming.logic.FarmLogicArboreal; import forestry.plugins.PluginFarming; -public class TileFarmPlain extends TileFarm implements IFarmHousing, ISocketable, IClimatised, IHintSource { +public class TileFarmPlain extends TileFarm implements IFarmHousing, ISocketable, IClimatised, IHintSource, ILiquidTankContainer { public static final int SLOT_RESOURCES_1 = 0; public static final int SLOT_GERMLINGS_1 = 6; @@ -73,8 +80,6 @@ public class TileFarmPlain extends TileFarm implements IFarmHousing, ISocketable public static final int SLOT_COUNT = 22; - public static final FluidStack STACK_WATER = LiquidHelper.getLiquid(Defaults.LIQUID_WATER, 1); - public static final int DELAY_HYDRATION = 100; public static final float RAINFALL_MODIFIER_CAP = 15f; public static final int BUFFER_FERTILIZER = 200; @@ -87,7 +92,8 @@ public class TileFarmPlain extends TileFarm implements IFarmHousing, ISocketable private final InventoryAdapter sockets = new InventoryAdapter(1, "sockets"); - private ForestryTank liquidTank = new ForestryTank(Defaults.PROCESSOR_TANK_CAPACITY); + private FilteredTank liquidTank; + private final TankManager tankManager; private IFarmLogic harvestProvider; // The farm logic which supplied the pending crops. private final Stack pendingCrops = new Stack(); @@ -106,6 +112,8 @@ public class TileFarmPlain extends TileFarm implements IFarmHousing, ISocketable public TileFarmPlain() { fertilizerValue = GameMode.getGameMode().getIntegerSetting("farms.fertilizer.value"); + liquidTank = new FilteredTank(Defaults.PROCESSOR_TANK_CAPACITY, FluidRegistry.WATER); + tankManager = new TankManager(liquidTank); } /* SAVING & LOADING */ @@ -120,9 +128,7 @@ public class TileFarmPlain extends TileFarm implements IFarmHousing, ISocketable refreshFarmLogics(); - liquidTank = new ForestryTank(Defaults.PROCESSOR_TANK_CAPACITY); - if (nbttagcompound.hasKey("LiquidTank")) - liquidTank.readFromNBT(nbttagcompound.getCompoundTag("LiquidTank")); + tankManager.readTanksFromNBT(nbttagcompound); } @Override @@ -134,10 +140,7 @@ public class TileFarmPlain extends TileFarm implements IFarmHousing, ISocketable nbttagcompound.setInteger("HydrationDelay", hydrationDelay); nbttagcompound.setInteger("TicksSinceRainfall", ticksSinceRainfall); - NBTTagCompound NBTresourceSlot = new NBTTagCompound(); - liquidTank.writeToNBT(NBTresourceSlot); - nbttagcompound.setTag("LiquidTank", NBTresourceSlot); - + tankManager.writeTanksToNBT(nbttagcompound); } /* UPDATING */ @@ -170,7 +173,7 @@ public class TileFarmPlain extends TileFarm implements IFarmHousing, ISocketable // Check if we have suitable items waiting in the item slot if (inventory.getStackInSlot(SLOT_CAN) != null) { FluidContainerData container = LiquidHelper.getLiquidContainer(inventory.getStackInSlot(SLOT_CAN)); - if (container != null && LiquidHelper.isLiquid(Defaults.LIQUID_WATER, container.fluid)) { + if (container != null && liquidTank.accepts(container.fluid.getFluid())) { inventory.setInventorySlotContents(SLOT_CAN, StackUtils.replenishByContainer(this, inventory.getStackInSlot(SLOT_CAN), container, liquidTank)); if (inventory.getStackInSlot(SLOT_CAN).stackSize <= 0) @@ -665,8 +668,6 @@ public class TileFarmPlain extends TileFarm implements IFarmHousing, ISocketable @Override public void makeMaster() { super.makeMaster(); - if (liquidTank == null) - liquidTank = new ForestryTank(Defaults.PROCESSOR_TANK_CAPACITY); refreshFarmLogics(); } @@ -675,8 +676,13 @@ public class TileFarmPlain extends TileFarm implements IFarmHousing, ISocketable super.onStructureReset(); } - public ForestryTank getTank() { - return liquidTank; + public StandardTank[] getTanks() { + return new StandardTank[] {liquidTank}; + } + + @Override + public TankManager getTankManager() { + return tankManager; } @Override @@ -757,12 +763,13 @@ public class TileFarmPlain extends TileFarm implements IFarmHousing, ISocketable @Override public void removeResources(ItemStack[] resources) { - inventory.removeResources(resources, SLOT_RESOURCES_1, SLOT_COUNT_RESERVOIRS); + EntityPlayer player = Proxies.common.getPlayer(worldObj, owner); + inventory.removeSets(1, resources, SLOT_RESOURCES_1, SLOT_RESOURCES_1, player, false, true, true); } @Override public boolean hasLiquid(FluidStack liquid) { - return liquidTank.getFluidAmount() >= liquid.amount && liquidTank.getFluid().isFluidEqual(liquid); + return liquidTank.getFluidAmount() >= liquid.amount; } @Override @@ -783,7 +790,8 @@ public class TileFarmPlain extends TileFarm implements IFarmHousing, ISocketable if (!germling.isGermling(inventory.getStackInSlot(i))) continue; - if (!germling.plantSaplingAt(inventory.getStackInSlot(i), world, x, y, z)) + EntityPlayer player = Proxies.common.getPlayer(world, owner); + if (!germling.plantSaplingAt(player, inventory.getStackInSlot(i), world, x, y, z)) continue; inventory.decrStackSize(i, 1); @@ -873,7 +881,7 @@ public class TileFarmPlain extends TileFarm implements IFarmHousing, ISocketable /* NETWORK GUI */ public void getGUINetworkData(int i, int j) { - + i -= tankManager.maxMessageId() + 1; switch (i) { case 0: storedFertilizer = j; @@ -891,10 +899,11 @@ public class TileFarmPlain extends TileFarm implements IFarmHousing, ISocketable } public void sendGUINetworkData(Container container, ICrafting iCrafting) { - iCrafting.sendProgressBarUpdate(container, 0, storedFertilizer); - iCrafting.sendProgressBarUpdate(container, 3, Math.round(temperature * 100)); - iCrafting.sendProgressBarUpdate(container, 4, Math.round(humidity * 100)); - iCrafting.sendProgressBarUpdate(container, 5, ticksSinceRainfall); + int i = tankManager.maxMessageId() + 1; + iCrafting.sendProgressBarUpdate(container, i, storedFertilizer); + iCrafting.sendProgressBarUpdate(container, i + 3, Math.round(temperature * 100)); + iCrafting.sendProgressBarUpdate(container, i + 4, Math.round(humidity * 100)); + iCrafting.sendProgressBarUpdate(container, i + 5, ticksSinceRainfall); } /* ICLIMATISED */ @@ -965,4 +974,34 @@ public class TileFarmPlain extends TileFarm implements IFarmHousing, ISocketable return true; } + /* ILiquidTankContainer */ + @Override + public int fill(ForgeDirection direction, FluidStack resource, boolean doFill) { + return tankManager.fill(direction, resource, doFill); + } + + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return tankManager.drain(from, resource, doDrain); + } + + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + return tankManager.drain(from, maxDrain, doDrain); + } + + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return tankManager.canFill(from, fluid); + } + + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return tankManager.canDrain(from, fluid); + } + + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return tankManager.getTankInfo(from); + } } diff --git a/src/main/java/forestry/farming/gadgets/TileHatch.java b/src/main/java/forestry/farming/gadgets/TileHatch.java index 59a52c946..d8ba476f7 100755 --- a/src/main/java/forestry/farming/gadgets/TileHatch.java +++ b/src/main/java/forestry/farming/gadgets/TileHatch.java @@ -240,6 +240,11 @@ public class TileHatch extends TileFarm implements ISidedInventory { public void closeInventory() { } + @Override + public String getInventoryName() { + return getUnlocalizedName(); + } + /** * TODO: just a specialsource workaround */ diff --git a/src/main/java/forestry/farming/gadgets/TileValve.java b/src/main/java/forestry/farming/gadgets/TileValve.java index 98977348f..d39fb84b1 100755 --- a/src/main/java/forestry/farming/gadgets/TileValve.java +++ b/src/main/java/forestry/farming/gadgets/TileValve.java @@ -10,11 +10,16 @@ ******************************************************************************/ package forestry.farming.gadgets; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.ICrafting; import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; import forestry.core.interfaces.ILiquidTankContainer; -import forestry.core.utils.ForestryTank; +import forestry.core.fluids.TankManager; +import forestry.core.fluids.tanks.FakeTank; +import net.minecraftforge.fluids.FluidTankInfo; public class TileValve extends TileFarm implements ILiquidTankContainer { @@ -33,42 +38,74 @@ public class TileValve extends TileFarm implements ILiquidTankContainer { } /* ILIQUIDTANKCONTAINER */ - private ForestryTank getMasterTank() { - if (!isIntegratedIntoStructure() || !hasMaster()) - return null; + @Override + public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + TankManager tankManager = getTankManager(); + if (tankManager == null) + return FakeTank.INSTANCE.fill(resource, doFill); - TileFarmPlain central = (TileFarmPlain) getCentralTE(); - if (central == null) - return null; - - return central.getTank(); + return tankManager.fill(from, resource, doFill); } @Override - public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - ForestryTank tank = getMasterTank(); - if (tank == null) - return 0; + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + TankManager tankManager = getTankManager(); + if (tankManager == null) + return null; - return tank.fill(resource, doFill); + return tankManager.drain(from, resource, doDrain); } @Override public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { - ForestryTank tank = getMasterTank(); - if (tank == null) - return null; + TankManager tankManager = getTankManager(); + if (tankManager == null) + return FakeTank.INSTANCE.drain(maxDrain, doDrain); - return tank.drain(maxDrain, doDrain); + return tankManager.drain(from, maxDrain, doDrain); } @Override - public ForestryTank[] getTanks() { - ForestryTank tank = getMasterTank(); - if (tank == null) - return ForestryTank.FAKETANK_ARRAY; + public boolean canFill(ForgeDirection from, Fluid fluid) { + TankManager tankManager = getTankManager(); + if (tankManager == null) + return true; - return new ForestryTank[] { tank }; + return tankManager.canFill(from, fluid); } + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + TankManager tankManager = getTankManager(); + if (tankManager == null) + return false; + + return tankManager.canDrain(from, fluid); + } + + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + TankManager tankManager = getTankManager(); + if (tankManager == null) + return FakeTank.INFO; + + return tankManager.getTankInfo(from); + } + + @Override + public TankManager getTankManager() { + TileFarmPlain central = (TileFarmPlain) getCentralTE(); + if (central == null) + return null; + + return central.getTankManager(); + } + + @Override + public void getGUINetworkData(int messageId, int data) { + } + + @Override + public void sendGUINetworkData(Container container, ICrafting iCrafting) { + } } diff --git a/src/main/java/forestry/farming/gui/ContainerFarm.java b/src/main/java/forestry/farming/gui/ContainerFarm.java index d045798f1..4aac1ecc5 100755 --- a/src/main/java/forestry/farming/gui/ContainerFarm.java +++ b/src/main/java/forestry/farming/gui/ContainerFarm.java @@ -10,27 +10,20 @@ ******************************************************************************/ package forestry.farming.gui; - -import java.util.HashMap; -import java.util.Map; - -import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.ICrafting; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; import forestry.api.farming.IFarmLogic; +import forestry.core.fluids.TankManager; +import forestry.core.fluids.tanks.StandardTank; import forestry.core.gui.ContainerSocketed; import forestry.core.gui.slots.SlotCustom; import forestry.core.gui.slots.SlotForestry; import forestry.core.gui.slots.SlotLiquidContainer; import forestry.core.gui.slots.SlotOutput; -import forestry.core.network.PacketTankUpdate; -import forestry.core.proxy.Proxies; -import forestry.core.utils.ForestryTank; import forestry.core.utils.TileInventoryAdapter; import forestry.farming.gadgets.TileFarmPlain; import forestry.plugins.PluginFarming; @@ -134,47 +127,32 @@ public class ContainerFarm extends ContainerSocketed { @Override public void updateProgressBar(int i, int j) { tile.getGUINetworkData(i, j); + TankManager tankManager = tile.getTankManager(); + if (tankManager != null) + tankManager.processGuiUpdate(i, j); } - private Map syncedFluids = new HashMap(); @Override public void detectAndSendChanges() { super.detectAndSendChanges(); + TankManager tankManager = tile.getTankManager(); + if (tankManager != null) + tankManager.updateGuiData(this, crafters); for (int i = 0; i < crafters.size(); i++) { tile.sendGUINetworkData(this, (ICrafting) crafters.get(i)); } - - ForestryTank tank = tile.getTank(); - - // If null has been synced - if (tank.getFluid() == null && getTank(0).getFluidAmount() <= 0) - return; - // If fluid has been synced - if (tank.getFluid() != null && tank.getFluid().isFluidStackIdentical(getTank(0).getFluid())) - return; - - for (int j = 0; j < this.crafters.size(); ++j) { - if (this.crafters.get(j) instanceof EntityPlayerMP) { - EntityPlayerMP player = (EntityPlayerMP) this.crafters.get(j); - Proxies.net.sendToPlayer(new PacketTankUpdate(0, tank), player); - } - } - syncedFluids.put(0, new ForestryTank(tank.getFluid() == null ? null : tank.getFluid().copy(), tank.getCapacity())); - } @Override - public void onTankUpdate(NBTTagCompound nbt) { - int tankID = nbt.getByte("tank"); - int capacity = nbt.getShort("capacity"); - ForestryTank tank = new ForestryTank(capacity); - tank.readFromNBT(nbt); - syncedFluids.put(tankID, tank); + public void addCraftingToCrafters(ICrafting iCrafting) { + super.addCraftingToCrafters(iCrafting); + TankManager tankManager = tile.getTankManager(); + if (tankManager != null) + tankManager.initGuiData(this, iCrafting); } - @Override - public ForestryTank getTank(int slot) { - return syncedFluids.get(slot) == null ? ForestryTank.FAKETANK : syncedFluids.get(slot); + public StandardTank getTank(int slot) { + return tile.getTankManager().get(slot); } } diff --git a/src/main/java/forestry/farming/gui/GuiFarm.java b/src/main/java/forestry/farming/gui/GuiFarm.java index f79759599..4de688b67 100755 --- a/src/main/java/forestry/farming/gui/GuiFarm.java +++ b/src/main/java/forestry/farming/gui/GuiFarm.java @@ -148,7 +148,7 @@ public class GuiFarm extends GuiForestry { @Override protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { super.drawGuiContainerForegroundLayer(mouseX, mouseY); - String title = StringUtil.localize("Farm"); + String title = StringUtil.localize("gui.farm.title"); this.fontRendererObj.drawString(title, getCenteredOffset(title), 6, fontColor.get("gui.title")); } diff --git a/src/main/java/forestry/farming/logic/FarmableCocoa.java b/src/main/java/forestry/farming/logic/FarmableCocoa.java index 81922fb82..47d0a380b 100755 --- a/src/main/java/forestry/farming/logic/FarmableCocoa.java +++ b/src/main/java/forestry/farming/logic/FarmableCocoa.java @@ -11,6 +11,7 @@ package forestry.farming.logic; import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; @@ -56,7 +57,7 @@ public class FarmableCocoa implements IFarmable { } @Override - public boolean plantSaplingAt(ItemStack germling, World world, int x, int y, int z) { + public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { return BlockUtil.tryPlantPot(world, x, y, z, COCOA_PLANT); } diff --git a/src/main/java/forestry/farming/logic/FarmableFarmCraftory.java b/src/main/java/forestry/farming/logic/FarmableFarmCraftory.java index 2d4b4ec73..bf8fa7cf2 100755 --- a/src/main/java/forestry/farming/logic/FarmableFarmCraftory.java +++ b/src/main/java/forestry/farming/logic/FarmableFarmCraftory.java @@ -13,6 +13,7 @@ package forestry.farming.logic; import java.util.Collection; import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; @@ -20,7 +21,6 @@ import net.minecraft.world.World; import forestry.api.farming.ICrop; import forestry.api.farming.IFarmable; import forestry.core.utils.StackUtils; -import forestry.core.utils.Utils; import forestry.core.utils.Vect; import forestry.plugins.PluginFarmCraftory; @@ -71,8 +71,8 @@ public class FarmableFarmCraftory implements IFarmable { } @Override - public boolean plantSaplingAt(ItemStack germling, World world, int x, int y, int z) { - return germling.copy().tryPlaceItemIntoWorld(Utils.getForestryPlayer(world, x, y, z), world, x, y - 1, z, 1, 0, 0, 0); + public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { + return germling.copy().tryPlaceItemIntoWorld(player, world, x, y - 1, z, 1, 0, 0, 0); } @Override diff --git a/src/main/java/forestry/farming/logic/FarmableGE.java b/src/main/java/forestry/farming/logic/FarmableGE.java index f7c1f5ea9..7281d3023 100755 --- a/src/main/java/forestry/farming/logic/FarmableGE.java +++ b/src/main/java/forestry/farming/logic/FarmableGE.java @@ -11,6 +11,7 @@ package forestry.farming.logic; import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; @@ -18,7 +19,6 @@ import forestry.api.arboriculture.ITree; import forestry.api.farming.ICrop; import forestry.api.farming.IFarmable; import forestry.core.config.ForestryBlock; -import forestry.core.utils.Utils; import forestry.core.utils.Vect; import forestry.plugins.PluginArboriculture; @@ -44,8 +44,8 @@ public class FarmableGE implements IFarmable { } @Override - public boolean plantSaplingAt(ItemStack germling, World world, int x, int y, int z) { - return germling.copy().tryPlaceItemIntoWorld(Utils.getForestryPlayer(world, x, y, z), world, x, y - 1, z, 1, 0, 0, 0); + public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { + return germling.copy().tryPlaceItemIntoWorld(player, world, x, y - 1, z, 1, 0, 0, 0); } @Override diff --git a/src/main/java/forestry/farming/logic/FarmableGenericCrop.java b/src/main/java/forestry/farming/logic/FarmableGenericCrop.java index 6346480cf..60c7c7d55 100755 --- a/src/main/java/forestry/farming/logic/FarmableGenericCrop.java +++ b/src/main/java/forestry/farming/logic/FarmableGenericCrop.java @@ -11,12 +11,12 @@ package forestry.farming.logic; import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import forestry.api.farming.ICrop; import forestry.api.farming.IFarmable; -import forestry.core.utils.Utils; import forestry.core.utils.Vect; public class FarmableGenericCrop implements IFarmable { @@ -65,8 +65,8 @@ public class FarmableGenericCrop implements IFarmable { } @Override - public boolean plantSaplingAt(ItemStack germling, World world, int x, int y, int z) { - return germling.copy().tryPlaceItemIntoWorld(Utils.getForestryPlayer(world, x, y, z), world, x, y - 1, z, 1, 0, 0, 0); + public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { + return germling.copy().tryPlaceItemIntoWorld(player, world, x, y - 1, z, 1, 0, 0, 0); } @Override diff --git a/src/main/java/forestry/farming/logic/FarmableGenericSapling.java b/src/main/java/forestry/farming/logic/FarmableGenericSapling.java index 4aefa7f20..d75de37c5 100755 --- a/src/main/java/forestry/farming/logic/FarmableGenericSapling.java +++ b/src/main/java/forestry/farming/logic/FarmableGenericSapling.java @@ -11,13 +11,13 @@ package forestry.farming.logic; import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import forestry.api.farming.ICrop; import forestry.api.farming.IFarmable; import forestry.core.utils.StackUtils; -import forestry.core.utils.Utils; import forestry.core.utils.Vect; public class FarmableGenericSapling implements IFarmable { @@ -79,8 +79,8 @@ public class FarmableGenericSapling implements IFarmable { } @Override - public boolean plantSaplingAt(ItemStack germling, World world, int x, int y, int z) { - return germling.copy().tryPlaceItemIntoWorld(Utils.getForestryPlayer(world, x, y, z), world, x, y - 1, z, 1, 0, 0, 0); + public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { + return germling.copy().tryPlaceItemIntoWorld(player, world, x, y - 1, z, 1, 0, 0, 0); } } diff --git a/src/main/java/forestry/farming/logic/FarmableGourd.java b/src/main/java/forestry/farming/logic/FarmableGourd.java index 79c56c852..989fedc80 100755 --- a/src/main/java/forestry/farming/logic/FarmableGourd.java +++ b/src/main/java/forestry/farming/logic/FarmableGourd.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.farming.logic; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; @@ -67,7 +68,7 @@ public class FarmableGourd implements IFarmable { } @Override - public boolean plantSaplingAt(ItemStack germling, World world, int x, int y, int z) { + public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { return world.setBlock(x, y, z, StackUtils.getBlock(stem), 0, Defaults.FLAG_BLOCK_SYNCH); } diff --git a/src/main/java/forestry/farming/logic/FarmableStacked.java b/src/main/java/forestry/farming/logic/FarmableStacked.java index dcb05bd2c..6b22e542f 100755 --- a/src/main/java/forestry/farming/logic/FarmableStacked.java +++ b/src/main/java/forestry/farming/logic/FarmableStacked.java @@ -11,6 +11,7 @@ package forestry.farming.logic; import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; @@ -49,7 +50,7 @@ public class FarmableStacked implements IFarmable { } @Override - public boolean plantSaplingAt(ItemStack germling, World world, int x, int y, int z) { + public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { return world.setBlock(x, y, z, block, 0, Defaults.FLAG_BLOCK_SYNCH); } diff --git a/src/main/java/forestry/farming/logic/FarmableVanillaSapling.java b/src/main/java/forestry/farming/logic/FarmableVanillaSapling.java index e9d0d6dc9..f40168c88 100755 --- a/src/main/java/forestry/farming/logic/FarmableVanillaSapling.java +++ b/src/main/java/forestry/farming/logic/FarmableVanillaSapling.java @@ -12,6 +12,7 @@ package forestry.farming.logic; import java.util.Map; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; @@ -20,7 +21,6 @@ import net.minecraft.world.World; import forestry.api.arboriculture.ITree; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IIndividual; -import forestry.core.utils.Utils; import forestry.plugins.PluginArboriculture; public class FarmableVanillaSapling extends FarmableGenericSapling { @@ -33,7 +33,7 @@ public class FarmableVanillaSapling extends FarmableGenericSapling { } @Override - public boolean plantSaplingAt(ItemStack germling, World world, int x, int y, int z) { + public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { ITree tree = null; for (Map.Entry entry : AlleleManager.ersatzSaplings.entrySet()) if (entry.getKey().isItemEqual(germling) && entry.getValue() instanceof ITree) { @@ -44,7 +44,7 @@ public class FarmableVanillaSapling extends FarmableGenericSapling { if (tree == null) return false; - return PluginArboriculture.treeInterface.plantSapling(world, tree, Utils.getForestryPlayerProfile(), x, y, z); + return PluginArboriculture.treeInterface.plantSapling(world, tree, player.getGameProfile(), x, y, z); } } diff --git a/src/main/java/forestry/farming/logic/FarmableVanillaShroom.java b/src/main/java/forestry/farming/logic/FarmableVanillaShroom.java index c92603f47..4754ebf3a 100755 --- a/src/main/java/forestry/farming/logic/FarmableVanillaShroom.java +++ b/src/main/java/forestry/farming/logic/FarmableVanillaShroom.java @@ -11,6 +11,7 @@ package forestry.farming.logic; import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.world.World; @@ -39,7 +40,7 @@ public class FarmableVanillaShroom extends FarmableGenericSapling { } @Override - public boolean plantSaplingAt(ItemStack germling, World world, int x, int y, int z) { + public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { int meta = 0; if (StackUtils.equals(Blocks.red_mushroom, germling)) meta = 1; diff --git a/src/main/java/forestry/farming/triggers/TriggerLowLiquid.java b/src/main/java/forestry/farming/triggers/TriggerLowLiquid.java index 52c46865c..a68f933ab 100755 --- a/src/main/java/forestry/farming/triggers/TriggerLowLiquid.java +++ b/src/main/java/forestry/farming/triggers/TriggerLowLiquid.java @@ -18,9 +18,10 @@ import buildcraft.api.gates.ITriggerParameter; import forestry.api.core.ITileStructure; import forestry.core.triggers.Trigger; -import forestry.core.utils.ForestryTank; +import forestry.core.fluids.TankManager; import forestry.farming.gadgets.TileFarmPlain; import forestry.farming.gadgets.TileHatch; +import net.minecraftforge.fluids.FluidTankInfo; public class TriggerLowLiquid extends Trigger { @@ -49,7 +50,8 @@ public class TriggerLowLiquid extends Trigger { if (central == null || !(central instanceof TileFarmPlain)) return false; - ForestryTank tank = ((TileFarmPlain) central).getTank(); - return ((float) tank.getFluidAmount() / tank.getCapacity()) <= threshold; + TankManager tankManager = ((TileFarmPlain) central).getTankManager(); + FluidTankInfo info = tankManager.getTankInfo(0); + return ((float) info.fluid.amount / info.capacity) <= threshold; } } diff --git a/src/main/java/forestry/farming/triggers/TriggerLowSoil.java b/src/main/java/forestry/farming/triggers/TriggerLowSoil.java index 632475f96..80b2a91f6 100755 --- a/src/main/java/forestry/farming/triggers/TriggerLowSoil.java +++ b/src/main/java/forestry/farming/triggers/TriggerLowSoil.java @@ -56,9 +56,9 @@ public class TriggerLowSoil extends Trigger { return false; ItemStack filter; - if (parameter == null || parameter.getItemStack() == null) - filter = new ItemStack(Blocks.air, threshold, -1); - else { + if (parameter == null || parameter.getItemStack() == null) { + filter = new ItemStack(Blocks.bedrock, threshold); + } else { filter = parameter.getItemStack().copy(); filter.stackSize = threshold; } diff --git a/src/main/java/forestry/food/items/ItemBeverage.java b/src/main/java/forestry/food/items/ItemBeverage.java index 5f1476887..1e69a1a9a 100755 --- a/src/main/java/forestry/food/items/ItemBeverage.java +++ b/src/main/java/forestry/food/items/ItemBeverage.java @@ -12,6 +12,7 @@ package forestry.food.items; import java.util.List; +import forestry.core.items.ItemForestryFood; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; @@ -28,12 +29,11 @@ import cpw.mods.fml.relauncher.SideOnly; import forestry.api.food.BeverageManager; import forestry.api.food.IBeverageEffect; -import forestry.core.CreativeTabForestry; import forestry.core.config.Config; import forestry.core.proxy.Proxies; import forestry.core.render.TextureManager; -public class ItemBeverage extends Item { +public class ItemBeverage extends ItemForestryFood { public static class BeverageInfo { @@ -113,10 +113,9 @@ public class ItemBeverage extends Item { public BeverageInfo[] beverages; public ItemBeverage(BeverageInfo... beverages) { - super(); + super(1, 0.2f); setMaxStackSize(1); this.beverages = beverages; - setCreativeTab(CreativeTabForestry.tabForestry); } /** @@ -135,7 +134,7 @@ public class ItemBeverage extends Item { IBeverageEffect[] effects = beverage.loadEffects(itemstack); itemstack.stackSize--; - entityplayer.getFoodStats().addStats(beverage.heal, beverage.saturation); + entityplayer.getFoodStats().func_151686_a(this, itemstack); world.playSoundAtEntity(entityplayer, "random.burp", 0.5F, world.rand.nextFloat() * 0.1F + 0.9F); if (!Proxies.common.isSimulating(world)) @@ -147,6 +146,20 @@ public class ItemBeverage extends Item { return itemstack; } + @Override + public int func_150905_g(ItemStack itemstack) { + int meta = itemstack.getItemDamage(); + BeverageInfo beverage = beverages[meta]; + return beverage.heal; + } + + @Override + public float func_150906_h(ItemStack itemstack) { + int meta = itemstack.getItemDamage(); + BeverageInfo beverage = beverages[meta]; + return beverage.saturation; + } + @Override public int getMaxItemUseDuration(ItemStack itemstack) { return 32; diff --git a/src/main/java/forestry/lepidopterology/gui/ContainerFlutterlyzer.java b/src/main/java/forestry/lepidopterology/gui/ContainerFlutterlyzer.java index 176de6ebb..d6d755837 100755 --- a/src/main/java/forestry/lepidopterology/gui/ContainerFlutterlyzer.java +++ b/src/main/java/forestry/lepidopterology/gui/ContainerFlutterlyzer.java @@ -10,75 +10,19 @@ ******************************************************************************/ package forestry.lepidopterology.gui; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.init.Blocks; -import net.minecraft.item.ItemStack; - +import forestry.core.gui.ContainerAlyzer; import forestry.core.config.ForestryItem; -import forestry.core.gui.ContainerItemInventory; -import forestry.core.gui.slots.SlotCustom; -import forestry.core.proxy.Proxies; import forestry.lepidopterology.items.ItemButterflyGE; import forestry.lepidopterology.items.ItemFlutterlyzer.FlutterlyzerInventory; -public class ContainerFlutterlyzer extends ContainerItemInventory { +import net.minecraft.entity.player.InventoryPlayer; + +public class ContainerFlutterlyzer extends ContainerAlyzer { FlutterlyzerInventory inventory; public ContainerFlutterlyzer(InventoryPlayer inventoryplayer, FlutterlyzerInventory inventory) { - super(inventory, inventoryplayer.player); - - this.inventory = inventory; - - // Energy - this.addSlot(new SlotCustom(inventory, FlutterlyzerInventory.SLOT_ENERGY, 172, 8, new Object[] { ForestryItem.honeydew, ForestryItem.honeyDrop })); - - // Bee to analyze - this.addSlot(new SlotCustom(inventory, FlutterlyzerInventory.SLOT_SPECIMEN, 172, 26, new Object[] { ItemButterflyGE.class, Blocks.sapling })); - - // Analyzed bee - this.addSlot(new SlotCustom(inventory, FlutterlyzerInventory.SLOT_ANALYZE_1, 172, 57, new Object[] { ItemButterflyGE.class })); - this.addSlot(new SlotCustom(inventory, FlutterlyzerInventory.SLOT_ANALYZE_2, 172, 75, new Object[] { ItemButterflyGE.class })); - this.addSlot(new SlotCustom(inventory, FlutterlyzerInventory.SLOT_ANALYZE_3, 172, 93, new Object[] { ItemButterflyGE.class })); - this.addSlot(new SlotCustom(inventory, FlutterlyzerInventory.SLOT_ANALYZE_4, 172, 111, new Object[] { ItemButterflyGE.class })); - this.addSlot(new SlotCustom(inventory, FlutterlyzerInventory.SLOT_ANALYZE_5, 172, 129, new Object[] { ItemButterflyGE.class })); - - // Player inventory - for (int i1 = 0; i1 < 3; i1++) - for (int l1 = 0; l1 < 9; l1++) - addSecuredSlot(inventoryplayer, l1 + i1 * 9 + 9, 18 + l1 * 18, 156 + i1 * 18); - // Player hotbar - for (int j1 = 0; j1 < 9; j1++) - addSecuredSlot(inventoryplayer, j1, 18 + j1 * 18, 214); - - } - - @Override - public void onContainerClosed(EntityPlayer entityplayer) { - - if (!Proxies.common.isSimulating(entityplayer.worldObj)) - return; - - // Last slot is the energy slot, so we don't save that one. - for (int i = 0; i < inventory.getSizeInventory(); i++) { - if (i == FlutterlyzerInventory.SLOT_ENERGY) - continue; - ItemStack stack = inventory.getStackInSlot(i); - if (stack == null) - continue; - - Proxies.common.dropItemPlayer(entityplayer, stack); - inventory.setInventorySlotContents(i, null); - } - - inventory.onGuiSaved(entityplayer); - - } - - @Override - protected boolean isAcceptedItem(EntityPlayer player, ItemStack stack) { - return true; + super(inventoryplayer, inventory, new Object[] { ForestryItem.honeydew, ForestryItem.honeyDrop }, new Object[] { ItemButterflyGE.class }); } } diff --git a/src/main/java/forestry/lepidopterology/gui/GuiFlutterlyzer.java b/src/main/java/forestry/lepidopterology/gui/GuiFlutterlyzer.java index 89eed4d6a..fc117ca51 100755 --- a/src/main/java/forestry/lepidopterology/gui/GuiFlutterlyzer.java +++ b/src/main/java/forestry/lepidopterology/gui/GuiFlutterlyzer.java @@ -45,8 +45,7 @@ public class GuiFlutterlyzer extends GuiAlyzer { super(AlleleManager.alleleRegistry.getSpeciesRoot("rootButterflies"), player, new ContainerFlutterlyzer(player.inventory, inventory), inventory, 1, inventory.getSizeInventory()); - xSize = 196; - ySize = 238; + guiName = "gui.flutterlyzer"; ArrayList butterflyList = new ArrayList(); ((ItemButterflyGE) ForestryItem.butterflyGE.item()).addCreativeItems(butterflyList, false); @@ -97,35 +96,6 @@ public class GuiFlutterlyzer extends GuiAlyzer { } - private void drawAnalyticsOverview() { - - startPage(); - - newLine(); - String title = StringUtil.localize("item.flutterlyzer").toUpperCase(); - drawCenteredLine(title, 8, 158); - newLine(); - - fontRendererObj.drawSplitString(StringUtil.localize("gui.flutterlyzer.help"), (int) ((guiLeft + COLUMN_0 + 4) * (1 / factor)), - (int) ((guiTop + 42) * (1 / factor)), (int) (158 * (1 / factor)), fontColor.get("gui.screen")); - newLine(); - newLine(); - newLine(); - newLine(); - - drawLine(StringUtil.localize("gui.beealyzer.overview") + ":", COLUMN_0 + 4); - newLine(); - drawLine("I : " + StringUtil.localize("gui.general"), COLUMN_0 + 4); - newLine(); - drawLine("II : " + StringUtil.localize("gui.environment"), COLUMN_0 + 4); - newLine(); - drawLine("III: " + StringUtil.localize("gui.produce"), COLUMN_0 + 4); - newLine(); - drawLine("IV : " + StringUtil.localize("gui.evolution"), COLUMN_0 + 4); - - endPage(); - } - private void drawAnalyticsPage1(IButterfly butterfly) { startPage(COLUMN_0, COLUMN_1, COLUMN_2); diff --git a/src/main/java/forestry/lepidopterology/items/ItemFlutterlyzer.java b/src/main/java/forestry/lepidopterology/items/ItemFlutterlyzer.java index 9d56cfbd9..8d037ae50 100755 --- a/src/main/java/forestry/lepidopterology/items/ItemFlutterlyzer.java +++ b/src/main/java/forestry/lepidopterology/items/ItemFlutterlyzer.java @@ -13,9 +13,9 @@ package forestry.lepidopterology.items; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; import net.minecraft.world.World; +import forestry.core.utils.AlyzerInventory; import forestry.api.core.ForestryAPI; import forestry.api.core.Tabs; import forestry.api.lepidopterology.IButterfly; @@ -27,21 +27,11 @@ import forestry.core.interfaces.IHintSource; import forestry.core.items.ItemInventoried; import forestry.core.network.GuiId; import forestry.core.proxy.Proxies; -import forestry.core.utils.ItemInventory; import forestry.plugins.PluginLepidopterology; public class ItemFlutterlyzer extends ItemInventoried { - public static class FlutterlyzerInventory extends ItemInventory implements IErrorSource, IHintSource { - - public final static int SLOT_SPECIMEN = 0; - public final static int SLOT_ANALYZE_1 = 1; - public final static int SLOT_ANALYZE_2 = 2; - public final static int SLOT_ANALYZE_3 = 3; - public final static int SLOT_ANALYZE_4 = 4; - public final static int SLOT_ANALYZE_5 = 6; - public final static int SLOT_ENERGY = 5; - EntityPlayer player; + public static class FlutterlyzerInventory extends AlyzerInventory implements IErrorSource, IHintSource { public FlutterlyzerInventory(EntityPlayer player) { super(ItemFlutterlyzer.class, 7); @@ -53,22 +43,6 @@ public class ItemFlutterlyzer extends ItemInventoried { this.player = player; } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - - NBTTagList nbttaglist = new NBTTagList(); - for (int i = SLOT_ENERGY; i < SLOT_ENERGY + 1; i++) { - if (inventoryStacks[i] != null) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - nbttagcompound1.setByte("Slot", (byte) i); - inventoryStacks[i].writeToNBT(nbttagcompound1); - nbttaglist.appendTag(nbttagcompound1); - } - } - nbttagcompound.setTag("Items", nbttaglist); - - } - private boolean isEnergy(ItemStack itemstack) { if (itemstack == null || itemstack.stackSize <= 0) return false; diff --git a/src/main/java/forestry/mail/CommandMail.java b/src/main/java/forestry/mail/CommandMail.java index 0fb18a23c..d0cd4ed6b 100755 --- a/src/main/java/forestry/mail/CommandMail.java +++ b/src/main/java/forestry/mail/CommandMail.java @@ -12,7 +12,6 @@ package forestry.mail; import java.util.List; -import forestry.api.mail.MailAddress; import net.minecraft.command.ICommand; import net.minecraft.command.ICommandSender; import net.minecraft.command.WrongUsageException; diff --git a/src/main/java/forestry/mail/EnumAddressee.java b/src/main/java/forestry/mail/EnumAddressee.java deleted file mode 100755 index 30aa2b2d1..000000000 --- a/src/main/java/forestry/mail/EnumAddressee.java +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.mail; - -import java.util.Locale; - -public enum EnumAddressee { - PLAYER, TRADER; - - public static EnumAddressee fromString(String ident) { - for(EnumAddressee addr : values()) { - if(addr.toString().equals(ident)) - return addr; - } - - return null; - } - - public static String asString(EnumAddressee addressee) { - return addressee.toString().toLowerCase(Locale.ENGLISH); - } -} diff --git a/src/main/java/forestry/mail/Letter.java b/src/main/java/forestry/mail/Letter.java index 515cc3be9..62641f252 100755 --- a/src/main/java/forestry/mail/Letter.java +++ b/src/main/java/forestry/mail/Letter.java @@ -19,7 +19,7 @@ import net.minecraft.nbt.NBTTagCompound; import forestry.api.core.INBTTagable; import forestry.api.mail.ILetter; import forestry.api.mail.IStamps; -import forestry.api.mail.MailAddress; +import forestry.api.mail.IMailAddress; import forestry.core.utils.InventoryAdapter; import forestry.core.utils.StringUtil; import org.apache.commons.lang3.StringUtils; @@ -32,15 +32,15 @@ public class Letter implements ILetter, INBTTagable { private boolean isProcessed = false; - private MailAddress sender; - private MailAddress[] recipient; + private IMailAddress sender; + private IMailAddress[] recipient; private String text; private InventoryAdapter inventory = new InventoryAdapter(22, "INV"); - public Letter(MailAddress sender, MailAddress recipient) { + public Letter(IMailAddress sender, IMailAddress recipient) { this.sender = sender; - this.recipient = new MailAddress[] { recipient }; + this.recipient = new IMailAddress[] { recipient }; } public Letter(NBTTagCompound nbttagcompound) { @@ -191,7 +191,7 @@ public class Letter implements ILetter, INBTTagable { if (getRecipients().length <= 0) return false; - MailAddress recipient = getRecipients()[0]; + IMailAddress recipient = getRecipients()[0]; if (recipient == null) return false; @@ -202,36 +202,36 @@ public class Letter implements ILetter, INBTTagable { } @Override - public void setSender(MailAddress address) { + public void setSender(IMailAddress address) { this.sender = address; } @Override - public MailAddress getSender() { + public IMailAddress getSender() { return sender; } - public void setRecipients(MailAddress[] recipients) { + public void setRecipients(IMailAddress[] recipients) { this.recipient = recipients; } @Override - public void setRecipient(MailAddress address) { + public void setRecipient(IMailAddress address) { if (address == null) - this.recipient = new MailAddress[] {}; + this.recipient = new IMailAddress[] {}; else - this.recipient = new MailAddress[] { address }; + this.recipient = new IMailAddress[] { address }; } @Override - public MailAddress[] getRecipients() { + public IMailAddress[] getRecipients() { return recipient; } @Override public String getRecipientString() { String recipientString = ""; - for (MailAddress address : recipient) { + for (IMailAddress address : recipient) { if (recipientString.length() > 0) recipientString += ", "; recipientString += address.getName(); diff --git a/src/main/java/forestry/mail/MailAddress.java b/src/main/java/forestry/mail/MailAddress.java new file mode 100644 index 000000000..2e9563d6e --- /dev/null +++ b/src/main/java/forestry/mail/MailAddress.java @@ -0,0 +1,161 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.mail; + +import java.util.Locale; +import java.util.UUID; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTUtil; +import net.minecraft.world.World; +import net.minecraft.entity.player.EntityPlayer; + +import com.mojang.authlib.GameProfile; + +import forestry.api.core.INBTTagable; +import forestry.core.proxy.Proxies; +import forestry.core.network.EntityNetData; +import forestry.api.mail.EnumAddressee; +import forestry.api.mail.IMailAddress; + +public class MailAddress implements INBTTagable, IMailAddress { + @EntityNetData + private EnumAddressee type; + @EntityNetData + private GameProfile gameProfile; // gameProfile is a fake GameProfile for traders, and real for players + + private static final GameProfile invalidGameProfile = new GameProfile(new UUID(0,0), ""); + + public MailAddress() { + this.type = EnumAddressee.PLAYER; + this.gameProfile = invalidGameProfile; + } + + public MailAddress(GameProfile gameProfile) { + if (gameProfile == null) + throw new IllegalArgumentException("gameProfile must not be null"); + + this.type = EnumAddressee.PLAYER; + this.gameProfile = gameProfile; + } + + public MailAddress(String name) { + if (name == null) + throw new IllegalArgumentException("name must not be null"); + + this.type = EnumAddressee.TRADER; + this.gameProfile = new GameProfile(new UUID(0,0), name); + } + + public MailAddress(IMailAddress address) { + this.type = address.getType(); + if (type == EnumAddressee.TRADER) { + String name = address.getName(); + this.gameProfile = new GameProfile(new UUID(0, 0), name); + } else if (type == EnumAddressee.PLAYER) { + this.gameProfile = address.getPlayerProfile(); + } + } + + public EnumAddressee getType() { + return type; + } + + public String getName() { + return gameProfile.getName(); + } + + @Override + public String toString() { + String name = getName().toLowerCase(Locale.ENGLISH); + if (isPlayer()) { + return type + "-" + name + "-" + gameProfile.getId(); + } else { + return type + "-" + name; + } + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof MailAddress)) + return false; + + MailAddress address = (MailAddress)o; + return address.gameProfile.equals(gameProfile); + } + + @Override + public int hashCode() { + return gameProfile.hashCode(); + } + + public boolean isPlayer() { + return type == EnumAddressee.PLAYER; + } + + public boolean isTrader() { + return type == EnumAddressee.TRADER; + } + + public boolean isValid() { + return !gameProfile.equals(invalidGameProfile); + } + + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + type = null; + if(nbttagcompound.hasKey("TP")) { + String typeName = nbttagcompound.getString("TP"); + type = EnumAddressee.fromString(typeName); + } + + if (type == null) { + type = EnumAddressee.PLAYER; + gameProfile = invalidGameProfile; + } else if(nbttagcompound.hasKey("profile")) { + NBTTagCompound profileTag = nbttagcompound.getCompoundTag("profile"); + gameProfile = NBTUtil.func_152459_a(profileTag); + } + } + + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + nbttagcompound.setString("TP", type.toString()); + + if (gameProfile != null) { + NBTTagCompound profileNbt = new NBTTagCompound(); + NBTUtil.func_152460_a(profileNbt, gameProfile); + nbttagcompound.setTag("profile", profileNbt); + } + } + + public static MailAddress loadFromNBT(NBTTagCompound nbttagcompound) { + MailAddress address = new MailAddress(); + address.readFromNBT(nbttagcompound); + return address; + } + + public boolean isClientPlayer(World world) { + if (!this.isPlayer()) + return false; + + EntityPlayer addressPlayer = Proxies.common.getPlayer(world, gameProfile); + EntityPlayer clientPlayer = Proxies.common.getPlayer(); + + return addressPlayer != null && clientPlayer != null && clientPlayer.equals(addressPlayer); + } + + public GameProfile getPlayerProfile() { + if (!this.isPlayer()) + return null; + return gameProfile; + } +} diff --git a/src/main/java/forestry/mail/POBox.java b/src/main/java/forestry/mail/POBox.java index 261ce5e3e..5fbc694f2 100755 --- a/src/main/java/forestry/mail/POBox.java +++ b/src/main/java/forestry/mail/POBox.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.mail; -import forestry.api.mail.MailAddress; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; @@ -19,6 +18,7 @@ import net.minecraft.world.WorldSavedData; import forestry.api.mail.ILetter; import forestry.api.mail.PostManager; +import forestry.api.mail.IMailAddress; import forestry.core.utils.InventoryAdapter; public class POBox extends WorldSavedData implements IInventory { @@ -26,10 +26,10 @@ public class POBox extends WorldSavedData implements IInventory { public static final String SAVE_NAME = "POBox_"; public static final short SLOT_SIZE = 84; - private MailAddress address; + private IMailAddress address; private final InventoryAdapter letters = new InventoryAdapter(SLOT_SIZE, "Letters"); - public POBox(MailAddress address) { + public POBox(IMailAddress address) { super(SAVE_NAME + address); if (!address.isPlayer()) { throw new IllegalArgumentException("POBox address must be a player"); diff --git a/src/main/java/forestry/mail/PacketHandlerMail.java b/src/main/java/forestry/mail/PacketHandlerMail.java index 9678186cd..d971f9446 100755 --- a/src/main/java/forestry/mail/PacketHandlerMail.java +++ b/src/main/java/forestry/mail/PacketHandlerMail.java @@ -12,7 +12,6 @@ package forestry.mail; import java.io.DataInputStream; -import forestry.api.mail.MailAddress; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; @@ -24,7 +23,7 @@ import forestry.mail.gui.ContainerCatalogue; import forestry.mail.gui.ContainerLetter; import forestry.mail.gui.ContainerTradeName; import forestry.mail.network.PacketPOBoxInfo; -import forestry.mail.network.PacketTradeInfo; +import forestry.mail.network.PacketLetterInfo; import forestry.plugins.PluginMail; public class PacketHandlerMail implements IPacketHandler { @@ -36,10 +35,10 @@ public class PacketHandlerMail implements IPacketHandler { PacketUpdate packet; switch (packetID) { - case PacketIds.TRADING_INFO: - PacketTradeInfo packetT = new PacketTradeInfo(); + case PacketIds.LETTER_INFO: + PacketLetterInfo packetT = new PacketLetterInfo(); packetT.readData(data); - onTradeInfo(packetT); + onLetterInfo(packetT); break; case PacketIds.POBOX_INFO: PacketPOBoxInfo packetP = new PacketPOBoxInfo(); @@ -70,11 +69,11 @@ public class PacketHandlerMail implements IPacketHandler { } } - private void onTradeInfo(PacketTradeInfo packet) { + private void onLetterInfo(PacketLetterInfo packet) { Container container = Proxies.common.getClientInstance().thePlayer.openContainer; if (container instanceof ContainerLetter) { - ((ContainerLetter) container).handleTradeInfoUpdate(packet); + ((ContainerLetter) container).handleLetterInfoUpdate(packet); } else if(container instanceof ContainerCatalogue) { ((ContainerCatalogue) container).handleTradeInfoUpdate(packet); } diff --git a/src/main/java/forestry/mail/PostOffice.java b/src/main/java/forestry/mail/PostOffice.java index c75ffe303..611765e40 100755 --- a/src/main/java/forestry/mail/PostOffice.java +++ b/src/main/java/forestry/mail/PostOffice.java @@ -12,15 +12,12 @@ package forestry.mail; import java.io.File; import java.util.LinkedHashMap; -import java.util.UUID; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import net.minecraft.world.WorldSavedData; -import com.mojang.authlib.GameProfile; - import forestry.api.mail.EnumPostage; import forestry.api.mail.ILetter; import forestry.api.mail.IPostOffice; @@ -28,8 +25,8 @@ import forestry.api.mail.IPostalCarrier; import forestry.api.mail.IPostalState; import forestry.api.mail.IStamps; import forestry.api.mail.ITradeStation; -import forestry.api.mail.MailAddress; import forestry.api.mail.PostManager; +import forestry.api.mail.IMailAddress; import forestry.core.config.ForestryItem; public class PostOffice extends WorldSavedData implements IPostOffice { @@ -47,6 +44,10 @@ public class PostOffice extends WorldSavedData implements IPostOffice { super(s); } + public void setWorld(World world) { + refreshActiveTradeStations(world); + } + @Override public void readFromNBT(NBTTagCompound nbttagcompound) { for (int i = 0; i < collectedPostage.length; i++) { @@ -63,18 +64,15 @@ public class PostOffice extends WorldSavedData implements IPostOffice { } /* TRADE STATION MANAGMENT */ - private LinkedHashMap activeTradeStations; + private LinkedHashMap activeTradeStations; @Override - public LinkedHashMap getActiveTradeStations(World world) { - if (activeTradeStations == null) - refreshActiveTradeStations(world); - + public LinkedHashMap getActiveTradeStations(World world) { return this.activeTradeStations; } private void refreshActiveTradeStations(World world) { - activeTradeStations = new LinkedHashMap(); + activeTradeStations = new LinkedHashMap(); if (world == null || world.getSaveHandler() == null) return; File worldSave = world.getSaveHandler().getMapFileFromName("dummy"); @@ -101,18 +99,12 @@ public class PostOffice extends WorldSavedData implements IPostOffice { @Override public void registerTradeStation(ITradeStation trade) { - if (activeTradeStations == null) - return; - if (!activeTradeStations.containsKey(trade.getAddress())) activeTradeStations.put(trade.getAddress(), trade); } @Override public void deregisterTradeStation(ITradeStation trade) { - if (activeTradeStations == null) - return; - activeTradeStations.remove(trade.getAddress()); } @@ -166,7 +158,7 @@ public class PostOffice extends WorldSavedData implements IPostOffice { return EnumDeliveryState.NOT_MAILABLE; IPostalState state = EnumDeliveryState.NOT_MAILABLE; - for (MailAddress address : letter.getRecipients()) { + for (IMailAddress address : letter.getRecipients()) { IPostalCarrier carrier = PostManager.postRegistry.getCarrier(address.getType()); if (carrier == null) continue; @@ -174,13 +166,6 @@ public class PostOffice extends WorldSavedData implements IPostOffice { if (!state.isOk()) break; } - /* - for (MailAddress address : letter.getRecipients()) - if (address.isPlayer()) - state = storeInPOBox(world, address, itemstack, doLodge); - else if (address.getType().equals(EnumAddressee.TRADER.toString())) - state = handleTradeLetter(world, address, itemstack, doLodge); - */ if (!state.isOk()) return state; diff --git a/src/main/java/forestry/mail/PostRegistry.java b/src/main/java/forestry/mail/PostRegistry.java index d9a5c9c04..64f2812a2 100755 --- a/src/main/java/forestry/mail/PostRegistry.java +++ b/src/main/java/forestry/mail/PostRegistry.java @@ -25,8 +25,9 @@ import forestry.api.mail.IPostOffice; import forestry.api.mail.IPostRegistry; import forestry.api.mail.IPostalCarrier; import forestry.api.mail.ITradeStation; -import forestry.api.mail.MailAddress; import forestry.api.mail.PostManager; +import forestry.api.mail.IMailAddress; +import forestry.api.mail.EnumAddressee; import forestry.core.config.ForestryItem; import forestry.mail.items.ItemLetter; import forestry.plugins.PluginMail; @@ -34,8 +35,8 @@ import forestry.plugins.PluginMail; public class PostRegistry implements IPostRegistry { public static PostOffice cachedPostOffice; - public static HashMap cachedPOBoxes = new HashMap(); - public static HashMap cachedTradeStations = new HashMap(); + public static HashMap cachedPOBoxes = new HashMap(); + public static HashMap cachedTradeStations = new HashMap(); /** * @param world the Minecraft world the PO box will be in @@ -43,11 +44,11 @@ public class PostRegistry implements IPostRegistry { * @return true if the passed address is valid for PO Boxes. */ @Override - public boolean isValidPOBox(World world, MailAddress address) { + public boolean isValidPOBox(World world, IMailAddress address) { return address.isPlayer() && address.getName().matches("^[a-zA-Z0-9]+$"); } - public static POBox getPOBox(World world, MailAddress address) { + public static POBox getPOBox(World world, IMailAddress address) { if (cachedPOBoxes.containsKey(address)) return cachedPOBoxes.get(address); @@ -58,7 +59,7 @@ public class PostRegistry implements IPostRegistry { return pobox; } - public static POBox getOrCreatePOBox(World world, MailAddress address) { + public static POBox getOrCreatePOBox(World world, IMailAddress address) { POBox pobox = getPOBox(world, address); if (pobox == null) { @@ -78,8 +79,8 @@ public class PostRegistry implements IPostRegistry { * @return true if the passed address can be an address for a trade station */ @Override - public boolean isValidTradeAddress(World world, MailAddress address) { - return !address.isPlayer() && address.getName().matches("^[a-zA-Z0-9]+$"); + public boolean isValidTradeAddress(World world, IMailAddress address) { + return address.isTrader() && address.getName().matches("^[a-zA-Z0-9]+$"); } /** @@ -88,12 +89,12 @@ public class PostRegistry implements IPostRegistry { * @return true if the trade address has not yet been used before. */ @Override - public boolean isAvailableTradeAddress(World world, MailAddress address) { + public boolean isAvailableTradeAddress(World world, IMailAddress address) { return getTradeStation(world, address) == null; } @Override - public TradeStation getTradeStation(World world, MailAddress address) { + public TradeStation getTradeStation(World world, IMailAddress address) { if (cachedTradeStations.containsKey(address)) return (TradeStation)cachedTradeStations.get(address); @@ -110,7 +111,7 @@ public class PostRegistry implements IPostRegistry { } @Override - public TradeStation getOrCreateTradeStation(World world, GameProfile owner, MailAddress address) { + public TradeStation getOrCreateTradeStation(World world, GameProfile owner, IMailAddress address) { TradeStation trade = getTradeStation(world, address); if (trade == null) { @@ -125,7 +126,7 @@ public class PostRegistry implements IPostRegistry { } @Override - public void deleteTradeStation(World world, MailAddress address) { + public void deleteTradeStation(World world, IMailAddress address) { TradeStation trade = getTradeStation(world, address); if (trade == null) return; @@ -151,31 +152,43 @@ public class PostRegistry implements IPostRegistry { world.setItemData(PostOffice.SAVE_NAME, office); } + office.setWorld(world); + cachedPostOffice = office; return office; } - /* CARRIER */ - private final HashMap carriers = new HashMap(); + @Override + public IMailAddress getMailAddress(GameProfile gameProfile) { + return new MailAddress(gameProfile); + } @Override - public Map getRegisteredCarriers() { + public IMailAddress getMailAddress(String traderName) { + return new MailAddress(traderName); + } + + /* CARRIER */ + private final HashMap carriers = new HashMap(); + + @Override + public Map getRegisteredCarriers() { return carriers; } @Override public void registerCarrier(IPostalCarrier carrier) { - carriers.put(carrier.getUID(), carrier); + carriers.put(carrier.getType(), carrier); } @Override - public IPostalCarrier getCarrier(String uid) { - return carriers.get(uid); + public IPostalCarrier getCarrier(EnumAddressee type) { + return carriers.get(type); } /* LETTERS */ @Override - public ILetter createLetter(MailAddress sender, MailAddress recipient) { + public ILetter createLetter(IMailAddress sender, IMailAddress recipient) { return new Letter(sender, recipient); } diff --git a/src/main/java/forestry/mail/PostalCarrier.java b/src/main/java/forestry/mail/PostalCarrier.java index c53b43740..ca0301eaf 100755 --- a/src/main/java/forestry/mail/PostalCarrier.java +++ b/src/main/java/forestry/mail/PostalCarrier.java @@ -20,32 +20,28 @@ import net.minecraft.world.World; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import com.mojang.authlib.GameProfile; - import forestry.core.render.TextureManager; import forestry.core.utils.StringUtil; import forestry.plugins.PluginMail; public class PostalCarrier implements IPostalCarrier { - private final String uid; private final String iconID; private final EnumAddressee type; public PostalCarrier(EnumAddressee type) { - uid = type.toString().toLowerCase(Locale.ENGLISH); - iconID = "mail/carrier." + uid; + iconID = "mail/carrier." + type; this.type = type; } @Override - public String getUID() { - return uid; + public EnumAddressee getType() { + return type; } @Override public String getName() { - return StringUtil.localize("gui.addressee." + uid); + return StringUtil.localize("gui.addressee." + type); } @Override @@ -55,14 +51,14 @@ public class PostalCarrier implements IPostalCarrier { } @Override - public IPostalState deliverLetter(World world, IPostOffice office, MailAddress recipient, ItemStack letterstack, boolean doDeliver) { + public IPostalState deliverLetter(World world, IPostOffice office, IMailAddress recipient, ItemStack letterstack, boolean doDeliver) { if(type == EnumAddressee.TRADER) return handleTradeLetter(world, office, recipient, letterstack, doDeliver); else return storeInPOBox(world, office, recipient, letterstack, doDeliver); } - private IPostalState handleTradeLetter(World world, IPostOffice office, MailAddress recipient, ItemStack letterstack, boolean doLodge) { + private IPostalState handleTradeLetter(World world, IPostOffice office, IMailAddress recipient, ItemStack letterstack, boolean doLodge) { IPostalState state = EnumDeliveryState.NOT_MAILABLE; ITradeStation trade = PostManager.postRegistry.getTradeStation(world, recipient); @@ -74,7 +70,7 @@ public class PostalCarrier implements IPostalCarrier { return state; } - private EnumDeliveryState storeInPOBox(World world, IPostOffice office, MailAddress recipient, ItemStack letterstack, boolean doLodge) { + private EnumDeliveryState storeInPOBox(World world, IPostOffice office, IMailAddress recipient, ItemStack letterstack, boolean doLodge) { POBox pobox = PostRegistry.getPOBox(world, recipient); if (pobox == null) diff --git a/src/main/java/forestry/mail/TradeStation.java b/src/main/java/forestry/mail/TradeStation.java index bae1dd188..e0defc5af 100755 --- a/src/main/java/forestry/mail/TradeStation.java +++ b/src/main/java/forestry/mail/TradeStation.java @@ -28,9 +28,9 @@ import forestry.api.mail.ILetter; import forestry.api.mail.IPostalState; import forestry.api.mail.IStamps; import forestry.api.mail.ITradeStation; -import forestry.api.mail.MailAddress; import forestry.api.mail.PostManager; import forestry.api.mail.TradeStationInfo; +import forestry.api.mail.IMailAddress; import forestry.core.config.ForestryItem; import forestry.core.utils.InventoryAdapter; import forestry.core.utils.StackUtils; @@ -40,29 +40,32 @@ public class TradeStation extends WorldSavedData implements ITradeStation, IInve // / CONSTANTS public static final String SAVE_NAME = "TradePO_"; - public static final short SLOT_SIZE = 39; public static final short SLOT_TRADEGOOD = 0; + public static final short SLOT_TRADEGOOD_COUNT = 1; public static final short SLOT_EXCHANGE_1 = 1; public static final short SLOT_EXCHANGE_COUNT = 4; public static final short SLOT_LETTERS_1 = 5; public static final short SLOT_LETTERS_COUNT = 6; public static final short SLOT_STAMPS_1 = 11; public static final short SLOT_STAMPS_COUNT = 4; - public static final short SLOT_INPUTBUF_1 = 15; - public static final short SLOT_OUTPUTBUF_1 = 27; - public static final short SLOT_BUFFER_COUNT = 12; + public static final short SLOT_RECEIVE_BUFFER = 15; + public static final short SLOT_RECEIVE_BUFFER_COUNT = 15; + public static final short SLOT_SEND_BUFFER = 30; + public static final short SLOT_SEND_BUFFER_COUNT = 10; + public static final short SLOT_SIZE = SLOT_TRADEGOOD_COUNT + SLOT_EXCHANGE_COUNT + SLOT_LETTERS_COUNT + SLOT_STAMPS_COUNT + SLOT_RECEIVE_BUFFER_COUNT + SLOT_SEND_BUFFER_COUNT; + // / MEMBER private GameProfile owner; - private MailAddress address; + private IMailAddress address; private boolean isVirtual = false; private boolean isInvalid = false; private final InventoryAdapter inventory = new InventoryAdapter(SLOT_SIZE, "INV"); // / CONSTRUCTORS - public TradeStation(GameProfile owner, MailAddress address) { + public TradeStation(GameProfile owner, IMailAddress address) { super(SAVE_NAME + address); - if (address.isPlayer()) { - throw new IllegalArgumentException("TradeStation address must not be a player"); + if (!address.isTrader()) { + throw new IllegalArgumentException("TradeStation address must be a trader"); } this.owner = owner; this.address = address; @@ -73,7 +76,7 @@ public class TradeStation extends WorldSavedData implements ITradeStation, IInve } @Override - public MailAddress getAddress() { + public IMailAddress getAddress() { return this.address; } @@ -160,7 +163,7 @@ public class TradeStation extends WorldSavedData implements ITradeStation, IInve /* ILETTERHANDLER */ @Override - public IPostalState handleLetter(World world, MailAddress recipient, ItemStack letterstack, boolean doLodge) { + public IPostalState handleLetter(World world, IMailAddress recipient, ItemStack letterstack, boolean doLodge) { boolean sendOwnerNotice = doLodge && owner != null; @@ -235,7 +238,7 @@ public class TradeStation extends WorldSavedData implements ITradeStation, IInve if (stack == null) continue; - inventory.tryAddStack(stack.copy(), SLOT_OUTPUTBUF_1, SLOT_BUFFER_COUNT, false); + inventory.tryAddStack(stack.copy(), SLOT_RECEIVE_BUFFER, SLOT_RECEIVE_BUFFER_COUNT, false); } } @@ -275,7 +278,7 @@ public class TradeStation extends WorldSavedData implements ITradeStation, IInve // How many orders are fillable? int itemCount = 0; - for (ItemStack stack : inventory.getStacks(SLOT_INPUTBUF_1, SLOT_BUFFER_COUNT)) { + for (ItemStack stack : inventory.getStacks(SLOT_SEND_BUFFER, SLOT_SEND_BUFFER_COUNT)) { if (stack != null && stack.isItemEqual(tradegood) && ItemStack.areItemStackTagsEqual(stack, tradegood)) itemCount += stack.stackSize; } @@ -283,13 +286,20 @@ public class TradeStation extends WorldSavedData implements ITradeStation, IInve return (int) Math.floor(itemCount / tradegood.stackSize); } + public boolean canReceivePayment() { + InventoryAdapter test = inventory.copy(); + ItemStack [] payment = inventory.getStacks(SLOT_EXCHANGE_1, SLOT_EXCHANGE_COUNT); + + return test.tryAddStacksCopy(payment, SLOT_RECEIVE_BUFFER, SLOT_RECEIVE_BUFFER_COUNT, true); + } + private int countStorablePayment(int max, ItemStack[] exchange) { InventoryAdapter test = inventory.copy(); int count = 0; for (int i = 0; i < max; i++) { - if (test.tryAddStacksCopy(exchange, true)) + if (test.tryAddStacksCopy(exchange, SLOT_RECEIVE_BUFFER, SLOT_RECEIVE_BUFFER_COUNT, true)) count++; else break; @@ -302,7 +312,7 @@ public class TradeStation extends WorldSavedData implements ITradeStation, IInve for (int j = 0; j < filled; j++) { int toRemove = inventory.getStackInSlot(SLOT_TRADEGOOD).stackSize; - for (int i = SLOT_INPUTBUF_1; i < SLOT_INPUTBUF_1 + SLOT_BUFFER_COUNT; i++) { + for (int i = SLOT_SEND_BUFFER; i < SLOT_SEND_BUFFER + SLOT_SEND_BUFFER_COUNT; i++) { ItemStack buffer = inventory.getStackInSlot(i); if (buffer == null) continue; diff --git a/src/main/java/forestry/mail/gadgets/MachineMailbox.java b/src/main/java/forestry/mail/gadgets/MachineMailbox.java index e289970e9..f26e1dfea 100755 --- a/src/main/java/forestry/mail/gadgets/MachineMailbox.java +++ b/src/main/java/forestry/mail/gadgets/MachineMailbox.java @@ -12,11 +12,13 @@ package forestry.mail.gadgets; import java.util.LinkedList; +import com.mojang.authlib.GameProfile; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraft.util.ChatComponentTranslation; +import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; @@ -26,8 +28,8 @@ import forestry.api.core.ForestryAPI; import forestry.api.core.ISpecialInventory; import forestry.api.mail.ILetter; import forestry.api.mail.IPostalState; -import forestry.api.mail.MailAddress; import forestry.api.mail.PostManager; +import forestry.api.mail.IMailAddress; import forestry.core.config.Config; import forestry.core.gadgets.TileBase; @@ -52,7 +54,7 @@ public class MachineMailbox extends TileBase implements IMailContainer, ISpecial @Override public String getInventoryName() { - return "mail.0"; + return getUnlocalizedName(); } /* GUI */ @@ -79,24 +81,18 @@ public class MachineMailbox extends TileBase implements IMailContainer, ISpecial @Override public void updateServerSide() { if (!isLinked) { - getOrCreateMailInventory(); + getOrCreateMailInventory(worldObj, getOwnerProfile()); isLinked = true; } } /* MAIL HANDLING */ - public IInventory getOrCreateMailInventory() { - // Handle client side - if (!Proxies.common.isSimulating(worldObj)) + public IInventory getOrCreateMailInventory(World world, GameProfile playerProfile) { + if (!Proxies.common.isSimulating(world)) return new InventoryAdapter(POBox.SLOT_SIZE, "Letters"); - EntityPlayer player = Proxies.common.getPlayer(); - - if (player == null || player.getGameProfile() == null) - return new InventoryAdapter(POBox.SLOT_SIZE, "Letters"); - - MailAddress address = new MailAddress(player.getGameProfile()); + IMailAddress address = PostManager.postRegistry.getMailAddress(playerProfile); return PostRegistry.getOrCreatePOBox(worldObj, address); } @@ -116,7 +112,7 @@ public class MachineMailbox extends TileBase implements IMailContainer, ISpecial @Override public boolean hasMail() { - IInventory mailInventory = getOrCreateMailInventory(); + IInventory mailInventory = getOrCreateMailInventory(worldObj, getOwnerProfile()); for (int i = 0; i < mailInventory.getSizeInventory(); i++) if (mailInventory.getStackInSlot(i) != null) return true; @@ -132,19 +128,6 @@ public class MachineMailbox extends TileBase implements IMailContainer, ISpecial return res; } - /* ISIDEDINVENTORY */ - private static int[] slotIndices; - - public int[] getSizeInventorySide(int side) { - IInventory inventory = getOrCreateMailInventory(); - if(slotIndices == null) { - slotIndices = new int[inventory.getSizeInventory()]; - for(int i = 0; i < inventory.getSizeInventory(); i++) - slotIndices[i] = i; - } - return slotIndices; - } - /* ISPECIALINVENTORY */ @Override public int addItem(ItemStack stack, boolean doAdd, ForgeDirection from) { @@ -163,7 +146,7 @@ public class MachineMailbox extends TileBase implements IMailContainer, ISpecial public ItemStack[] extractItem(boolean doRemove, ForgeDirection from, int maxItemCount) { ItemStack product = null; - IInventory mailInventory = getOrCreateMailInventory(); + IInventory mailInventory = getOrCreateMailInventory(worldObj, getOwnerProfile()); for (int i = 0; i < mailInventory.getSizeInventory(); i++) { ItemStack slotStack = mailInventory.getStackInSlot(i); diff --git a/src/main/java/forestry/mail/gadgets/MachinePhilatelist.java b/src/main/java/forestry/mail/gadgets/MachinePhilatelist.java index 27531aa05..5352cf720 100755 --- a/src/main/java/forestry/mail/gadgets/MachinePhilatelist.java +++ b/src/main/java/forestry/mail/gadgets/MachinePhilatelist.java @@ -37,7 +37,7 @@ public class MachinePhilatelist extends TileBase implements IInventory { @Override public String getInventoryName() { - return "mail.2"; + return getUnlocalizedName(); } @Override diff --git a/src/main/java/forestry/mail/gadgets/MachineTrader.java b/src/main/java/forestry/mail/gadgets/MachineTrader.java index 661d463f7..2b9812530 100755 --- a/src/main/java/forestry/mail/gadgets/MachineTrader.java +++ b/src/main/java/forestry/mail/gadgets/MachineTrader.java @@ -12,7 +12,6 @@ package forestry.mail.gadgets; import java.util.LinkedList; -import forestry.api.mail.MailAddress; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.inventory.IInventory; @@ -28,6 +27,8 @@ import forestry.api.core.ForestryAPI; import forestry.api.core.ISpecialInventory; import forestry.api.mail.IStamps; import forestry.api.mail.PostManager; +import forestry.api.mail.IMailAddress; +import forestry.mail.MailAddress; import forestry.core.EnumErrorCode; import forestry.core.gadgets.TileBase; import forestry.core.network.EntityNetData; @@ -41,7 +42,7 @@ import forestry.plugins.PluginMail; public class MachineTrader extends TileBase implements ISpecialInventory, ISidedInventory { @EntityNetData - public MailAddress address; + private MailAddress address; public MachineTrader() { address = new MailAddress(); @@ -49,7 +50,7 @@ public class MachineTrader extends TileBase implements ISpecialInventory, ISided @Override public String getInventoryName() { - return "mail.1"; + return getUnlocalizedName(); } @Override @@ -89,21 +90,61 @@ public class MachineTrader extends TileBase implements ISpecialInventory, ISided } /* UPDATING */ + + /** + * The trade station should show errors for missing stamps and paper first. + * Once it is able to send letters, it should display other error states. + */ @Override public void updateServerSide() { - if (worldObj.getTotalWorldTime() % 40 * 10 != 0) + if (!isLinked() || worldObj.getTotalWorldTime() % 4 != 0) return; - if (!hasPaperMin(0.0f) || !hasInputBufMin(0.0f)) { - setErrorState(EnumErrorCode.NORESOURCE); + EnumErrorCode errorCode = EnumErrorCode.OK; + + if (!hasPostageMin(3)) + errorCode = EnumErrorCode.NOSTAMPS; + + if (!hasPaperMin(2)) { + if (errorCode == EnumErrorCode.NOSTAMPS) + errorCode = EnumErrorCode.NOSTAMPSNOPAPER; + else + errorCode = EnumErrorCode.NOPAPER; + } + + if (errorCode != EnumErrorCode.OK) { + setErrorState(errorCode); return; } - if (!hasPostageMin(3)) { // Assumes that the trade station owner should have a notice. - setErrorState(EnumErrorCode.NOSTAMPS); + + IInventory inventory = getOrCreateTradeInventory(); + ItemStack tradeGood = inventory.getStackInSlot(TradeStation.SLOT_TRADEGOOD); + + if (tradeGood == null) { + setErrorState(EnumErrorCode.NOTRADE); return; } + boolean hasRequest = hasItemCount(TradeStation.SLOT_EXCHANGE_1, TradeStation.SLOT_EXCHANGE_COUNT, null, 1); + if (!hasRequest) { + setErrorState(EnumErrorCode.NOTRADE); + return; + } + + boolean hasSupplies = hasItemCount(TradeStation.SLOT_SEND_BUFFER, TradeStation.SLOT_SEND_BUFFER_COUNT, tradeGood, tradeGood.stackSize); + if(!hasSupplies) { + setErrorState(EnumErrorCode.NOSUPPLIES); + return; + } + + if (inventory instanceof TradeStation) { + if (!((TradeStation)inventory).canReceivePayment()) { + setErrorState(EnumErrorCode.NOSPACE); + return; + } + } + setErrorState(EnumErrorCode.OK); } @@ -113,31 +154,64 @@ public class MachineTrader extends TileBase implements ISpecialInventory, ISided return address.isValid(); } - private float percentOccupied(int startSlot, int countSlots) { - int max = 0; - int avail = 0; + /** + * Returns true if there are 'itemCount' of 'item' in the inventory + * wildcard when item == null, counts all types of items + */ + private boolean hasItemCount(int startSlot, int countSlots, ItemStack item, int itemCount) { + int count = 0; IInventory tradeInventory = this.getOrCreateTradeInventory(); for (int i = startSlot; i < startSlot + countSlots; i++) { - max += 64; - if (tradeInventory.getStackInSlot(i) == null) + ItemStack itemInSlot = tradeInventory.getStackInSlot(i); + if (itemInSlot == null) continue; - avail += tradeInventory.getStackInSlot(i).stackSize; + if (item == null || StackUtils.isIdenticalItem(itemInSlot, item)) + count += itemInSlot.stackSize; + if (count >= itemCount) + return true; } - return ((float) avail / (float) max); + return false; } - public boolean hasPaperMin(float percentage) { - return percentOccupied(TradeStation.SLOT_LETTERS_1, TradeStation.SLOT_LETTERS_COUNT) > percentage; + /** + * Returns the percentage of the inventory that is occupied by 'item' + * if item == null, returns the percentage occupied by all kinds of items + */ + private float percentOccupied(int startSlot, int countSlots, ItemStack item) { + int count = 0; + int total = 0; + + IInventory tradeInventory = this.getOrCreateTradeInventory(); + for (int i = startSlot; i < startSlot + countSlots; i++) { + ItemStack itemInSlot = tradeInventory.getStackInSlot(i); + if (itemInSlot == null) { + total += 64; + } else { + total += itemInSlot.getMaxStackSize(); + if (item == null || StackUtils.isIdenticalItem(itemInSlot, item)) + count += itemInSlot.stackSize; + } + } + + return ((float)count / (float)total); + } + + public boolean hasPaperMin(int count) { + return hasItemCount(TradeStation.SLOT_LETTERS_1, TradeStation.SLOT_LETTERS_COUNT, new ItemStack(Items.paper), count); } public boolean hasInputBufMin(float percentage) { - return percentOccupied(TradeStation.SLOT_INPUTBUF_1, TradeStation.SLOT_BUFFER_COUNT) > percentage; + IInventory inventory = getOrCreateTradeInventory(); + ItemStack tradeGood = inventory.getStackInSlot(TradeStation.SLOT_TRADEGOOD); + if (tradeGood == null) + return true; + return percentOccupied(TradeStation.SLOT_SEND_BUFFER, TradeStation.SLOT_SEND_BUFFER_COUNT, tradeGood) > percentage; } public boolean hasOutputBufMin(float percentage) { - return percentOccupied(TradeStation.SLOT_OUTPUTBUF_1, TradeStation.SLOT_BUFFER_COUNT) > percentage; + return percentOccupied(TradeStation.SLOT_RECEIVE_BUFFER, TradeStation.SLOT_RECEIVE_BUFFER_COUNT, null) > percentage; } public boolean hasPostageMin(int postage) { @@ -153,17 +227,19 @@ public class MachineTrader extends TileBase implements ISpecialInventory, ISided continue; posted += ((IStamps) stamp.getItem()).getPostage(stamp).getValue() * stamp.stackSize; + if (posted >= postage) + return true; } - return posted >= postage; + return false; } /* ADDRESS */ - public MailAddress getAddress() { + public IMailAddress getAddress() { return address; } - public void setAddress(MailAddress address) { + public void setAddress(IMailAddress address) { if (address == null) throw new NullPointerException("address must not be null"); @@ -181,12 +257,11 @@ public class MachineTrader extends TileBase implements ISpecialInventory, ISided return; } - this.address = address; + this.address = new MailAddress(address); PostManager.postRegistry.getOrCreateTradeStation(worldObj, getOwnerProfile(), address); setErrorState(EnumErrorCode.OK); - sendNetworkUpdate(); } else - this.address = address; + this.address = new MailAddress(address); } /* TRADING */ @@ -231,7 +306,7 @@ public class MachineTrader extends TileBase implements ISpecialInventory, ISided if (!tradegood.isItemEqual(stack)) return 0; - return StackUtils.addToInventory(stack, inventory, doAdd, TradeStation.SLOT_INPUTBUF_1, TradeStation.SLOT_BUFFER_COUNT); + return StackUtils.addToInventory(stack, inventory, doAdd, TradeStation.SLOT_SEND_BUFFER, TradeStation.SLOT_SEND_BUFFER_COUNT); } @Override @@ -242,7 +317,7 @@ public class MachineTrader extends TileBase implements ISpecialInventory, ISided ItemStack product = null; IInventory inventory = getOrCreateTradeInventory(); - for (int i = TradeStation.SLOT_OUTPUTBUF_1; i < TradeStation.SLOT_OUTPUTBUF_1 + TradeStation.SLOT_BUFFER_COUNT; i++) { + for (int i = TradeStation.SLOT_RECEIVE_BUFFER; i < TradeStation.SLOT_RECEIVE_BUFFER + TradeStation.SLOT_RECEIVE_BUFFER_COUNT; i++) { ItemStack stackSlot = inventory.getStackInSlot(i); if (stackSlot == null) continue; @@ -278,7 +353,7 @@ public class MachineTrader extends TileBase implements ISpecialInventory, ISided if(!super.canTakeStackFromSide(slotIndex, itemstack, side)) return false; - if(slotIndex >= TradeStation.SLOT_OUTPUTBUF_1 && slotIndex < TradeStation.SLOT_OUTPUTBUF_1 + TradeStation.SLOT_BUFFER_COUNT) + if(slotIndex >= TradeStation.SLOT_RECEIVE_BUFFER && slotIndex < TradeStation.SLOT_RECEIVE_BUFFER + TradeStation.SLOT_RECEIVE_BUFFER_COUNT) return true; return false; @@ -298,7 +373,7 @@ public class MachineTrader extends TileBase implements ISpecialInventory, ISided return itemstack.getItem() instanceof IStamps; } - if (slotIndex >= TradeStation.SLOT_INPUTBUF_1 && slotIndex < TradeStation.SLOT_BUFFER_COUNT) { + if (slotIndex >= TradeStation.SLOT_SEND_BUFFER && slotIndex < TradeStation.SLOT_SEND_BUFFER_COUNT) { IInventory inventory = getOrCreateTradeInventory(); ItemStack tradegood = inventory.getStackInSlot(TradeStation.SLOT_TRADEGOOD); if(tradegood == null) @@ -405,8 +480,8 @@ public class MachineTrader extends TileBase implements ISpecialInventory, ISided @Override public LinkedList getCustomTriggers() { LinkedList res = new LinkedList(); - res.add(PluginMail.lowPaper25); - res.add(PluginMail.lowPaper10); + res.add(PluginMail.lowPaper64); + res.add(PluginMail.lowPaper32); res.add(PluginMail.lowInput25); res.add(PluginMail.lowInput10); res.add(PluginMail.lowPostage40); diff --git a/src/main/java/forestry/mail/gui/ContainerCatalogue.java b/src/main/java/forestry/mail/gui/ContainerCatalogue.java index 1b4e27641..85341d988 100755 --- a/src/main/java/forestry/mail/gui/ContainerCatalogue.java +++ b/src/main/java/forestry/mail/gui/ContainerCatalogue.java @@ -15,26 +15,27 @@ import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Set; -import forestry.api.mail.MailAddress; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.ICrafting; import forestry.api.mail.ITradeStation; import forestry.api.mail.PostManager; import forestry.api.mail.TradeStationInfo; +import forestry.api.mail.IMailAddress; +import forestry.api.mail.EnumAddressee; +import forestry.mail.network.PacketLetterInfo; +import forestry.mail.EnumStationState; import forestry.core.gui.ContainerForestry; import forestry.core.gui.IGuiSelectable; import forestry.core.network.PacketIds; import forestry.core.network.PacketPayload; import forestry.core.network.PacketUpdate; import forestry.core.proxy.Proxies; -import forestry.mail.EnumStationState; -import forestry.mail.network.PacketTradeInfo; public class ContainerCatalogue extends ContainerForestry implements IGuiSelectable { private final EntityPlayer player; - private final LinkedHashMap stations; + private final LinkedHashMap stations; private TradeStationInfo currentTrade = null; private Iterator iterator = null; @@ -57,7 +58,7 @@ public class ContainerCatalogue extends ContainerForestry implements IGuiSelecta this.player = player; // Filter out any trade stations which do not actually offer anything. - stations = new LinkedHashMap(); + stations = new LinkedHashMap(); rebuildStationsList(); } @@ -183,7 +184,7 @@ public class ContainerCatalogue extends ContainerForestry implements IGuiSelecta needsSynch = true; } - public void handleTradeInfoUpdate(PacketTradeInfo packet) { + public void handleTradeInfoUpdate(PacketLetterInfo packet) { setTradeInfo(packet.tradeInfo); } @@ -207,7 +208,7 @@ public class ContainerCatalogue extends ContainerForestry implements IGuiSelecta crafter.sendProgressBarUpdate(this, 2, currentFilter); } - Proxies.net.sendToPlayer(new PacketTradeInfo(PacketIds.TRADING_INFO, currentTrade), player); + Proxies.net.sendToPlayer(new PacketLetterInfo(PacketIds.LETTER_INFO, EnumAddressee.TRADER, currentTrade, null), player); needsSynch = false; } } diff --git a/src/main/java/forestry/mail/gui/ContainerLetter.java b/src/main/java/forestry/mail/gui/ContainerLetter.java index a21c26b3a..0d372854c 100755 --- a/src/main/java/forestry/mail/gui/ContainerLetter.java +++ b/src/main/java/forestry/mail/gui/ContainerLetter.java @@ -11,17 +11,23 @@ package forestry.mail.gui; import java.util.Iterator; -import java.util.Locale; +import java.util.UUID; +import org.apache.commons.lang3.StringUtils; + +import com.mojang.authlib.GameProfile; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; +import net.minecraft.server.MinecraftServer; import net.minecraft.world.World; + import forestry.api.mail.ILetter; import forestry.api.mail.IPostalCarrier; import forestry.api.mail.ITradeStation; -import forestry.api.mail.MailAddress; +import forestry.api.mail.IMailAddress; import forestry.api.mail.PostManager; import forestry.api.mail.TradeStationInfo; +import forestry.api.mail.EnumAddressee; import forestry.core.gui.ContainerItemInventory; import forestry.core.gui.slots.SlotClosed; import forestry.core.gui.slots.SlotCustom; @@ -29,17 +35,16 @@ import forestry.core.network.PacketIds; import forestry.core.network.PacketPayload; import forestry.core.network.PacketUpdate; import forestry.core.proxy.Proxies; -import forestry.mail.EnumAddressee; import forestry.mail.Letter; import forestry.mail.items.ItemLetter; import forestry.mail.items.ItemLetter.LetterInventory; import forestry.mail.items.ItemStamps; -import forestry.mail.network.PacketTradeInfo; +import forestry.mail.network.PacketLetterInfo; public class ContainerLetter extends ContainerItemInventory { private final LetterInventory letterInventory; - private String carrier = EnumAddressee.PLAYER.toString().toLowerCase(Locale.ENGLISH); + private EnumAddressee carrierType = EnumAddressee.PLAYER; private TradeStationInfo tradeInfo = null; public ContainerLetter(EntityPlayer player, LetterInventory inventory) { @@ -83,7 +88,7 @@ public class ContainerLetter extends ContainerItemInventory { if (letterInventory.getLetter() != null) if (letterInventory.getLetter().getRecipients() != null) if (letterInventory.getLetter().getRecipients().length > 0) - this.carrier = letterInventory.getLetter().getRecipients()[0].getType(); + this.carrierType = letterInventory.getLetter().getRecipients()[0].getType(); } @Override @@ -91,8 +96,10 @@ public class ContainerLetter extends ContainerItemInventory { if (Proxies.common.isSimulating(entityplayer.worldObj)) { ILetter letter = letterInventory.getLetter(); - if (!letter.isProcessed()) - letter.setSender(new MailAddress(entityplayer.getGameProfile())); + if (!letter.isProcessed()) { + IMailAddress sender = PostManager.postRegistry.getMailAddress(entityplayer.getGameProfile()); + letter.setSender(sender); + } } super.onContainerClosed(entityplayer); @@ -107,18 +114,18 @@ public class ContainerLetter extends ContainerItemInventory { return letterInventory.getLetter(); } - public void setCarrierType(String type) { - this.carrier = type; + public void setCarrierType(EnumAddressee type) { + this.carrierType = type; } - public String getCarrierType() { - return this.carrier; + public EnumAddressee getCarrierType() { + return this.carrierType; } public void advanceCarrierType() { Iterator it = PostManager.postRegistry.getRegisteredCarriers().values().iterator(); while(it.hasNext()) { - if(it.next().getUID().equals(carrier)) + if(it.next().getType().equals(carrierType)) break; } @@ -128,39 +135,49 @@ public class ContainerLetter extends ContainerItemInventory { else postal = PostManager.postRegistry.getRegisteredCarriers().values().iterator().next(); - setCarrierType(postal.getUID()); + setCarrierType(postal.getType()); } - public void setRecipient(MailAddress address) { - if (address == null) + public void setRecipient(String recipientName, EnumAddressee type) { + if (StringUtils.isBlank(recipientName) || type == null) return; - - getLetter().setRecipient(address); - carrier = address.getType(); // / Send to server - PacketPayload payload = new PacketPayload(0, 0, 2); - payload.stringPayload[0] = getRecipient().getName(); - payload.stringPayload[1] = this.carrier; + PacketPayload payload = new PacketPayload(0,0,2); + payload.stringPayload[0] = recipientName; + payload.stringPayload[1] = type.toString(); PacketUpdate packet = new PacketUpdate(PacketIds.LETTER_RECIPIENT, payload); Proxies.net.sendToServer(packet); } public void handleSetRecipient(EntityPlayer player, PacketUpdate packet) { - String identifierName = packet.payload.stringPayload[0]; - String type = packet.payload.stringPayload[1]; - MailAddress recipient = MailAddress.makeMailAddress(identifierName, type); + String recipientName = packet.payload.stringPayload[0]; + String typeName = packet.payload.stringPayload[1]; + + EnumAddressee type = EnumAddressee.fromString(typeName); + IMailAddress recipient; + if (type == EnumAddressee.PLAYER) { + GameProfile gameProfile = MinecraftServer.getServer().func_152358_ax().func_152655_a(recipientName); + if (gameProfile == null) + gameProfile = new GameProfile(new UUID(0, 0), recipientName); + recipient = PostManager.postRegistry.getMailAddress(gameProfile); + } else if (type == EnumAddressee.TRADER) { + recipient = PostManager.postRegistry.getMailAddress(recipientName); + } else { + return; + } + getLetter().setRecipient(recipient); // Update the trading info updateTradeInfo(player.worldObj, recipient); - // Update trade info on client - Proxies.net.sendToPlayer(new PacketTradeInfo(PacketIds.TRADING_INFO, tradeInfo), player); + // Update info on client + Proxies.net.sendToPlayer(new PacketLetterInfo(PacketIds.LETTER_INFO, type, tradeInfo, recipient), player); } - public MailAddress getRecipient() { + public IMailAddress getRecipient() { if (getLetter().getRecipients().length > 0) return getLetter().getRecipients()[0]; else @@ -188,7 +205,7 @@ public class ContainerLetter extends ContainerItemInventory { } /* Managing Trade info */ - public void updateTradeInfo(World world, MailAddress address) { + public void updateTradeInfo(World world, IMailAddress address) { // Updating is done by the server. if (!Proxies.common.isSimulating(world)) return; @@ -203,8 +220,13 @@ public class ContainerLetter extends ContainerItemInventory { setTradeInfo(station.getTradeInfo()); } - public void handleTradeInfoUpdate(PacketTradeInfo packet) { - this.setTradeInfo(packet.tradeInfo); + public void handleLetterInfoUpdate(PacketLetterInfo packet) { + carrierType = packet.type; + if (packet.type == EnumAddressee.PLAYER) { + getLetter().setRecipient(packet.address); + } else if (packet.type == EnumAddressee.TRADER) { + this.setTradeInfo(packet.tradeInfo); + } } public TradeStationInfo getTradeInfo() { diff --git a/src/main/java/forestry/mail/gui/ContainerMailbox.java b/src/main/java/forestry/mail/gui/ContainerMailbox.java index 6d697647a..4569fccb8 100755 --- a/src/main/java/forestry/mail/gui/ContainerMailbox.java +++ b/src/main/java/forestry/mail/gui/ContainerMailbox.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.mail.gui; -import forestry.api.mail.MailAddress; +import forestry.api.mail.PostManager; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.IInventory; @@ -22,10 +22,14 @@ import forestry.core.gui.slots.SlotClosed; import forestry.core.proxy.Proxies; import forestry.mail.POBox; import forestry.mail.gadgets.MachineMailbox; +import forestry.api.mail.IMailAddress; import forestry.plugins.PluginMail; public class ContainerMailbox extends ContainerForestry { + public static final short SLOT_LETTERS = 0; + public static final short SLOT_LETTERS_COUNT = 7 * 12; + MachineMailbox mailbox; POBox mailinventory; @@ -35,7 +39,7 @@ public class ContainerMailbox extends ContainerForestry { // Mailbox contents this.mailbox = tile; - IInventory inv = mailbox.getOrCreateMailInventory(); + IInventory inv = mailbox.getOrCreateMailInventory(player.player.worldObj, player.player.getGameProfile()); if (inv instanceof POBox) mailinventory = (POBox) inv; @@ -57,9 +61,11 @@ public class ContainerMailbox extends ContainerForestry { public ItemStack slotClick(int slotIndex, int button, int par3, EntityPlayer player) { ItemStack stack = super.slotClick(slotIndex, button, par3, player); - if (Proxies.common.isSimulating(player.worldObj) && mailinventory != null) { - MailAddress address = new MailAddress(mailbox.getOwnerProfile()); - PluginMail.proxy.setPOBoxInfo(mailbox.getWorldObj(), address, mailinventory.getPOBoxInfo()); + if (slotIndex >= SLOT_LETTERS && slotIndex < SLOT_LETTERS + SLOT_LETTERS_COUNT) { + if (Proxies.common.isSimulating(player.worldObj) && mailinventory != null) { + IMailAddress address = PostManager.postRegistry.getMailAddress(player.getGameProfile()); + PluginMail.proxy.setPOBoxInfo(mailbox.getWorldObj(), address, mailinventory.getPOBoxInfo()); + } } return stack; diff --git a/src/main/java/forestry/mail/gui/ContainerTradeName.java b/src/main/java/forestry/mail/gui/ContainerTradeName.java index ee3f34d3d..b97913f2e 100755 --- a/src/main/java/forestry/mail/gui/ContainerTradeName.java +++ b/src/main/java/forestry/mail/gui/ContainerTradeName.java @@ -20,7 +20,8 @@ import forestry.core.network.PacketUpdate; import forestry.core.proxy.Proxies; import forestry.core.utils.InventoryAdapter; import forestry.mail.gadgets.MachineTrader; -import forestry.api.mail.MailAddress; +import forestry.api.mail.PostManager; +import forestry.api.mail.IMailAddress; import org.apache.commons.lang3.StringUtils; @@ -35,7 +36,7 @@ public class ContainerTradeName extends ContainerForestry { isLinked = machine.isLinked(); } - public MailAddress getAddress() { + public IMailAddress getAddress() { return machine.getAddress(); } @@ -50,13 +51,13 @@ public class ContainerTradeName extends ContainerForestry { PacketUpdate packet = new PacketUpdate(PacketIds.TRADING_ADDRESS_SET, payload); Proxies.net.sendToServer(packet); - MailAddress address = new MailAddress(addressName); + IMailAddress address = PostManager.postRegistry.getMailAddress(addressName); machine.setAddress(address); } public void handleSetAddress(PacketUpdate packet) { String addressName = packet.payload.stringPayload[0]; - MailAddress address = new MailAddress(addressName); + IMailAddress address = PostManager.postRegistry.getMailAddress(addressName); machine.setAddress(address); } diff --git a/src/main/java/forestry/mail/gui/ContainerTrader.java b/src/main/java/forestry/mail/gui/ContainerTrader.java index 26bdb81d1..ea85064cb 100755 --- a/src/main/java/forestry/mail/gui/ContainerTrader.java +++ b/src/main/java/forestry/mail/gui/ContainerTrader.java @@ -16,12 +16,11 @@ import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import forestry.core.gui.ContainerForestry; -import forestry.core.gui.slots.SlotClosed; import forestry.core.gui.slots.SlotCustom; import forestry.mail.TradeStation; import forestry.mail.gadgets.MachineTrader; import forestry.mail.items.ItemStamps; -import forestry.api.mail.MailAddress; +import forestry.api.mail.IMailAddress; public class ContainerTrader extends ContainerForestry { @@ -51,15 +50,15 @@ public class ContainerTrader extends ContainerForestry { for (int j = 0; j < 2; j++) addSlot(new SlotCustom(inventory, TradeStation.SLOT_LETTERS_1 + j + i * 2, 15 + j * 18, 73 + i * 18, new Object[] { Items.paper })); - // Input buffer - for (int i = 0; i < 6; i++) - for (int j = 0; j < 2; j++) - addSlot(new Slot(inventory, TradeStation.SLOT_INPUTBUF_1 + j + i * 2, 123 + j * 18, 19 + i * 18)); + // Buffers + final int bufCols = 5; + for (int i = 0; i < 3; i++) + for (int j = 0; j < bufCols; j++) + addSlot(new Slot(inventory, TradeStation.SLOT_RECEIVE_BUFFER + j + i * bufCols, 123 + j * 18, 19 + i * 18)); - // Output buffer - for (int i = 0; i < 6; i++) - for (int j = 0; j < 2; j++) - addSlot(new SlotClosed(inventory, TradeStation.SLOT_OUTPUTBUF_1 + j + i * 2, 177 + j * 18, 19 + i * 18)); + for (int i = 0; i < 2; i++) + for (int j = 0; j < bufCols; j++) + addSlot(new Slot(inventory, TradeStation.SLOT_SEND_BUFFER + j + i * bufCols, 123 + j * 18, (19 + (18 * 4)) + i * 18)); // Player inventory for (int i = 0; i < 3; i++) @@ -75,7 +74,7 @@ public class ContainerTrader extends ContainerForestry { return machine.isLinked(); } - public MailAddress getAddress() { + public IMailAddress getAddress() { return machine.getAddress(); } diff --git a/src/main/java/forestry/mail/gui/GuiCatalogue.java b/src/main/java/forestry/mail/gui/GuiCatalogue.java index 95b19e5ed..3fc16135e 100755 --- a/src/main/java/forestry/mail/gui/GuiCatalogue.java +++ b/src/main/java/forestry/mail/gui/GuiCatalogue.java @@ -23,7 +23,7 @@ import forestry.core.config.SessionVars; import forestry.core.gadgets.TileForestry; import forestry.core.gui.GuiForestry; import forestry.core.utils.StringUtil; -import forestry.mail.EnumAddressee; +import forestry.api.mail.EnumAddressee; public class GuiCatalogue extends GuiForestry { @@ -136,7 +136,7 @@ public class GuiCatalogue extends GuiForestry { TradeStationInfo info = container.getTradeInfo(); if(info != null) { SessionVars.setStringVar("mail.letter.recipient", info.address.getName()); - SessionVars.setStringVar("mail.letter.addressee", EnumAddressee.asString(EnumAddressee.TRADER)); + SessionVars.setStringVar("mail.letter.addressee", EnumAddressee.TRADER.toString()); } mc.displayGuiScreen((GuiScreen)null); break; diff --git a/src/main/java/forestry/mail/gui/GuiLetter.java b/src/main/java/forestry/mail/gui/GuiLetter.java index 881585196..7bd389742 100755 --- a/src/main/java/forestry/mail/gui/GuiLetter.java +++ b/src/main/java/forestry/mail/gui/GuiLetter.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.mail.gui; -import java.util.Locale; +import java.util.ArrayList; import net.minecraft.client.gui.GuiTextField; import net.minecraft.entity.player.EntityPlayer; @@ -20,7 +20,7 @@ import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.GL11; import forestry.api.mail.IPostalCarrier; -import forestry.api.mail.MailAddress; +import forestry.api.mail.IMailAddress; import forestry.api.mail.PostManager; import forestry.core.config.Defaults; import forestry.core.config.SessionVars; @@ -30,7 +30,7 @@ import forestry.core.gui.GuiTextBox; import forestry.core.gui.widgets.Widget; import forestry.core.proxy.Proxies; import forestry.core.utils.StringUtil; -import forestry.mail.EnumAddressee; +import forestry.api.mail.EnumAddressee; import forestry.mail.items.ItemLetter.LetterInventory; public class GuiLetter extends GuiForestry { @@ -56,7 +56,7 @@ public class GuiLetter extends GuiForestry { @Override protected String getLegacyTooltip(EntityPlayer player) { - return StringUtil.localize("gui.addressee." + container.getCarrierType().toLowerCase(Locale.ENGLISH)); + return StringUtil.localize("gui.addressee." + container.getCarrierType().toString()); } @Override @@ -76,6 +76,8 @@ public class GuiLetter extends GuiForestry { boolean addressFocus; boolean textFocus; + protected ArrayList tradeInfoWidgets; + private final ContainerLetter container; public GuiLetter(EntityPlayer player, LetterInventory inventory) { @@ -86,6 +88,7 @@ public class GuiLetter extends GuiForestry { this.container = (ContainerLetter) inventorySlots; this.isProcessedLetter = container.getLetter().isProcessed(); this.widgetManager.add(new AddresseeSlot(16, 12)); + this.tradeInfoWidgets = new ArrayList(); } @Override @@ -95,10 +98,9 @@ public class GuiLetter extends GuiForestry { Keyboard.enableRepeatEvents(true); address = new GuiTextField(this.fontRendererObj, guiLeft + 46, guiTop + 13, 93, 13); - MailAddress recipient = container.getRecipient(); + IMailAddress recipient = container.getRecipient(); if (recipient != null) { address.setText(recipient.getName()); - setRecipient(recipient); } text = new GuiTextBox(this.fontRendererObj, guiLeft + 17, guiTop + 31, 122, 57); @@ -158,8 +160,8 @@ public class GuiLetter extends GuiForestry { if (addressFocus != address.isFocused()) { String recipient = this.address.getText(); if (StringUtils.isNotBlank(recipient)) { - MailAddress recipientAddress = MailAddress.makeMailAddress(recipient, container.getCarrierType()); - setRecipient(recipientAddress); + EnumAddressee recipientType = container.getCarrierType(); + setRecipient(recipient, recipientType); } } addressFocus = address.isFocused(); @@ -173,9 +175,10 @@ public class GuiLetter extends GuiForestry { fontRendererObj.drawString(address.getText(), guiLeft + 49, guiTop + 16, fontColor.get("gui.mail.lettertext")); fontRendererObj.drawSplitString(text.getText(), guiLeft + 20, guiTop + 34, 119, fontColor.get("gui.mail.lettertext")); } else { + clearTradeInfoWidgets(); address.drawTextBox(); - if (container.getCarrierType().equals(EnumAddressee.TRADER.toString().toLowerCase(Locale.ENGLISH))) - drawTradePreview(guiLeft + 18, guiTop + 32); + if (container.getCarrierType() == EnumAddressee.TRADER) + drawTradePreview(18, 32); else text.drawTextBox(); } @@ -192,32 +195,37 @@ public class GuiLetter extends GuiForestry { infoString = "chat.mail." + container.getTradeInfo().state.getIdentifier(); if (infoString != null) { - fontRendererObj.drawSplitString(StringUtil.localize(infoString), x, y, 119, fontColor.get("gui.mail.lettertext")); + fontRendererObj.drawSplitString(StringUtil.localize(infoString), guiLeft + x, guiTop + y, 119, fontColor.get("gui.mail.lettertext")); return; } - fontRendererObj.drawString(StringUtil.localize("gui.mail.pleasesend"), x, y, fontColor.get("gui.mail.lettertext")); + fontRendererObj.drawString(StringUtil.localize("gui.mail.pleasesend"), guiLeft + x, guiTop + y, fontColor.get("gui.mail.lettertext")); - itemRender.renderItemAndEffectIntoGUI(fontRendererObj, mc.renderEngine, container.getTradeInfo().tradegood, x, y + 10); - itemRender.renderItemOverlayIntoGUI(fontRendererObj, mc.renderEngine, container.getTradeInfo().tradegood, x, y + 10); + addTradeInfoWidget(new ItemStackWidget(x, y + 10, container.getTradeInfo().tradegood)); GL11.glDisable(GL11.GL_LIGHTING); - fontRendererObj.drawString(StringUtil.localize("gui.mail.foreveryattached"), x, y + 28, fontColor.get("gui.mail.lettertext")); + fontRendererObj.drawString(StringUtil.localize("gui.mail.foreveryattached"), guiLeft + x, guiTop + y + 28, fontColor.get("gui.mail.lettertext")); GL11.glEnable(GL11.GL_LIGHTING); for (int i = 0; i < container.getTradeInfo().required.length; i++) { - GL11.glDisable(GL11.GL_LIGHTING); - itemRender.renderItemAndEffectIntoGUI(fontRendererObj, mc.renderEngine, container.getTradeInfo().required[i], x + i * 18, y + 38); - itemRender.renderItemOverlayIntoGUI(fontRendererObj, mc.renderEngine, container.getTradeInfo().required[i], x + i * 18, y + 38); - GL11.glEnable(GL11.GL_LIGHTING); + addTradeInfoWidget(new ItemStackWidget(x + i * 18, y + 38, container.getTradeInfo().required[i])); } + } + private void addTradeInfoWidget(Widget widget) { + tradeInfoWidgets.add(widget); + widgetManager.add(widget); + } + + private void clearTradeInfoWidgets() { + for (Widget widget : tradeInfoWidgets) + widgetManager.remove(widget); } @Override public void onGuiClosed() { - MailAddress recipientAddress = MailAddress.makeMailAddress(this.address.getText(), container.getCarrierType()); - - setRecipient(recipientAddress); + String recipientName = this.address.getText(); + EnumAddressee recipientType = container.getCarrierType(); + setRecipient(recipientName, recipientType); setText(); Keyboard.enableRepeatEvents(false); super.onGuiClosed(); @@ -233,24 +241,24 @@ public class GuiLetter extends GuiForestry { return; String recipient = SessionVars.getStringVar("mail.letter.recipient"); - String type = SessionVars.getStringVar("mail.letter.addressee"); + String typeName = SessionVars.getStringVar("mail.letter.addressee"); - if (recipient != null && type != null) { + if (StringUtils.isNotBlank(recipient) && StringUtils.isNotBlank(typeName)) { address.setText(recipient); - MailAddress recipientAddress = MailAddress.makeMailAddress(recipient, type); - setRecipient(recipientAddress); + + EnumAddressee type = EnumAddressee.fromString(typeName); + setRecipient(recipient, type); } SessionVars.clearStringVar("mail.letter.recipient"); SessionVars.clearStringVar("mail.letter.addressee"); } - private void setRecipient(MailAddress recipientAddress) { - if (this.isProcessedLetter || recipientAddress == null) + private void setRecipient(String recipientName, EnumAddressee type) { + if (this.isProcessedLetter || StringUtils.isBlank(recipientName) || type == null) return; - container.setRecipient(recipientAddress); - container.updateTradeInfo(this.mc.theWorld, recipientAddress); + container.setRecipient(recipientName, type); } private void setText() { diff --git a/src/main/java/forestry/mail/gui/GuiTrader.java b/src/main/java/forestry/mail/gui/GuiTrader.java index f32521eba..5e9999436 100755 --- a/src/main/java/forestry/mail/gui/GuiTrader.java +++ b/src/main/java/forestry/mail/gui/GuiTrader.java @@ -16,14 +16,13 @@ import forestry.core.config.Defaults; import forestry.core.gui.GuiForestry; import forestry.core.utils.StringUtil; import forestry.mail.gadgets.MachineTrader; -import forestry.api.mail.MailAddress; public class GuiTrader extends GuiForestry { private final ContainerTrader container; public GuiTrader(InventoryPlayer inventoryplayer, MachineTrader tile) { - super(Defaults.TEXTURE_PATH_GUI + "/mailtrader.png", new ContainerTrader(inventoryplayer, tile), tile); + super(Defaults.TEXTURE_PATH_GUI + "/mailtrader2.png", new ContainerTrader(inventoryplayer, tile), tile); this.xSize = 226; this.ySize = 220; @@ -33,8 +32,14 @@ public class GuiTrader extends GuiForestry { @Override protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { super.drawGuiContainerForegroundLayer(mouseX, mouseY); - String name = StringUtil.localize("tile.for." + tile.getInventoryName()); + String name = StringUtil.localizeTile(tile.getUnlocalizedName()); this.fontRendererObj.drawString(name, getCenteredOffset(name), 6, fontColor.get("gui.mail.text")); + + String receive = StringUtil.localize("gui.mail.receive"); + this.fontRendererObj.drawString(receive, getCenteredOffset(receive, 70) + 51, 45, fontColor.get("gui.mail.text")); + + String send = StringUtil.localize("gui.mail.send"); + this.fontRendererObj.drawString(send, getCenteredOffset(send, 70) + 51, 99, fontColor.get("gui.mail.text")); } @Override diff --git a/src/main/java/forestry/mail/network/PacketLetterInfo.java b/src/main/java/forestry/mail/network/PacketLetterInfo.java new file mode 100644 index 000000000..857939524 --- /dev/null +++ b/src/main/java/forestry/mail/network/PacketLetterInfo.java @@ -0,0 +1,125 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.mail.network; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.UUID; + +import net.minecraft.item.ItemStack; +import com.mojang.authlib.GameProfile; + +import forestry.api.mail.TradeStationInfo; +import forestry.api.mail.IMailAddress; +import forestry.api.mail.EnumAddressee; +import forestry.api.mail.PostManager; +import forestry.core.network.ForestryPacket; +import forestry.mail.EnumStationState; + +public class PacketLetterInfo extends ForestryPacket { + + public EnumAddressee type; + public TradeStationInfo tradeInfo; + public IMailAddress address; + + public PacketLetterInfo() { + } + + public PacketLetterInfo(int id, EnumAddressee type, TradeStationInfo info, IMailAddress address) { + super(id); + this.type = type; + if (type == EnumAddressee.TRADER) + this.tradeInfo = info; + else if (type == EnumAddressee.PLAYER) + this.address = address; + } + + @Override + public void writeData(DataOutputStream data) throws IOException { + + if (type == null) { + data.writeShort(-1); + return; + } + data.writeShort(0); + + data.writeUTF(type.toString()); + + if (type == EnumAddressee.PLAYER) { + + if (address == null) { + data.writeShort(-1); + return; + } + data.writeShort(0); + + GameProfile profile = address.getPlayerProfile(); + + data.writeLong(profile.getId().getMostSignificantBits()); + data.writeLong(profile.getId().getLeastSignificantBits()); + data.writeUTF(profile.getName()); + + } else if (type == EnumAddressee.TRADER) { + + if (tradeInfo == null) { + data.writeShort(-1); + return; + } + + data.writeShort(0); + + data.writeUTF(tradeInfo.address.getName()); + + data.writeLong(tradeInfo.owner.getId().getMostSignificantBits()); + data.writeLong(tradeInfo.owner.getId().getLeastSignificantBits()); + data.writeUTF(tradeInfo.owner.getName()); + + writeItemStack(tradeInfo.tradegood, data); + data.writeShort(tradeInfo.required.length); + for (int i = 0; i < tradeInfo.required.length; i++) + writeItemStack(tradeInfo.required[i], data); + data.writeShort(tradeInfo.state.ordinal()); + } + } + + @Override + public void readData(DataInputStream data) throws IOException { + + if (data.readShort() < 0) + return; + + type = EnumAddressee.fromString(data.readUTF()); + + if (type == EnumAddressee.PLAYER) { + if (data.readShort() < 0) + return; + GameProfile player = new GameProfile(new UUID(data.readLong(), data.readLong()), data.readUTF()); + this.address = PostManager.postRegistry.getMailAddress(player); + + } else if (type == EnumAddressee.TRADER) { + if (data.readShort() < 0) + return; + IMailAddress address = PostManager.postRegistry.getMailAddress(data.readUTF()); + GameProfile owner = new GameProfile(new UUID(data.readLong(), data.readLong()), data.readUTF()); + ItemStack tradegood; + ItemStack[] required; + + tradegood = readItemStack(data); + required = new ItemStack[data.readShort()]; + for (int i = 0; i < required.length; i++) + required[i] = readItemStack(data); + + this.tradeInfo = new TradeStationInfo(address, owner, tradegood, required, EnumStationState.values()[data.readShort()]); + } + } + +} diff --git a/src/main/java/forestry/mail/network/PacketTradeInfo.java b/src/main/java/forestry/mail/network/PacketTradeInfo.java deleted file mode 100755 index 63ba14da3..000000000 --- a/src/main/java/forestry/mail/network/PacketTradeInfo.java +++ /dev/null @@ -1,82 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.mail.network; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.UUID; - -import forestry.api.mail.MailAddress; -import net.minecraft.item.ItemStack; - -import com.mojang.authlib.GameProfile; - -import forestry.api.mail.TradeStationInfo; -import forestry.core.network.ForestryPacket; -import forestry.mail.EnumStationState; - -public class PacketTradeInfo extends ForestryPacket { - - public TradeStationInfo tradeInfo; - - public PacketTradeInfo() { - } - - public PacketTradeInfo(int id, TradeStationInfo info) { - super(id); - this.tradeInfo = info; - } - - @Override - public void writeData(DataOutputStream data) throws IOException { - - if (tradeInfo == null) { - data.writeShort(-1); - return; - } - - data.writeShort(0); - - data.writeUTF(tradeInfo.address.getName()); - - data.writeLong(tradeInfo.owner.getId().getMostSignificantBits()); - data.writeLong(tradeInfo.owner.getId().getLeastSignificantBits()); - data.writeUTF(tradeInfo.owner.getName()); - - writeItemStack(tradeInfo.tradegood, data); - data.writeShort(tradeInfo.required.length); - for (int i = 0; i < tradeInfo.required.length; i++) - writeItemStack(tradeInfo.required[i], data); - data.writeShort(tradeInfo.state.ordinal()); - } - - @Override - public void readData(DataInputStream data) throws IOException { - - short isNotNull = data.readShort(); - if (isNotNull < 0) - return; - - MailAddress address = new MailAddress(data.readUTF()); - GameProfile owner = new GameProfile(new UUID(data.readLong(), data.readLong()), data.readUTF()); - ItemStack tradegood; - ItemStack[] required; - - tradegood = readItemStack(data); - required = new ItemStack[data.readShort()]; - for (int i = 0; i < required.length; i++) - required[i] = readItemStack(data); - - this.tradeInfo = new TradeStationInfo(address, owner, tradegood, required, EnumStationState.values()[data.readShort()]); - } - -} diff --git a/src/main/java/forestry/mail/proxy/ClientProxyMail.java b/src/main/java/forestry/mail/proxy/ClientProxyMail.java index 48ce4c1ae..7ffa4b197 100755 --- a/src/main/java/forestry/mail/proxy/ClientProxyMail.java +++ b/src/main/java/forestry/mail/proxy/ClientProxyMail.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.mail.proxy; -import forestry.api.mail.MailAddress; +import com.mojang.authlib.GameProfile; import net.minecraft.world.World; import forestry.core.network.ForestryPacket; @@ -20,6 +20,8 @@ import forestry.mail.POBox; import forestry.mail.POBoxInfo; import forestry.mail.PostRegistry; import forestry.mail.gui.GuiMailboxInfo; +import forestry.api.mail.IMailAddress; +import forestry.api.mail.PostManager; public class ClientProxyMail extends ProxyMail { @@ -38,7 +40,8 @@ public class ClientProxyMail extends ProxyMail { if (!Proxies.common.isSimulating(Proxies.common.getRenderWorld())) Proxies.net.sendToServer(new ForestryPacket(PacketIds.POBOX_INFO_REQUEST)); else { - MailAddress address = new MailAddress(Proxies.common.getClientInstance().thePlayer.getGameProfile()); + GameProfile profile = Proxies.common.getClientInstance().thePlayer.getGameProfile(); + IMailAddress address = PostManager.postRegistry.getMailAddress(profile); POBox pobox = PostRegistry.getPOBox(Proxies.common.getRenderWorld(), address); if (pobox != null) setPOBoxInfo(Proxies.common.getRenderWorld(), address, pobox.getPOBoxInfo()); @@ -46,7 +49,7 @@ public class ClientProxyMail extends ProxyMail { } @Override - public void setPOBoxInfo(World world, MailAddress address, POBoxInfo info) { + public void setPOBoxInfo(World world, IMailAddress address, POBoxInfo info) { if (address.isClientPlayer(world)) GuiMailboxInfo.instance.setPOBoxInfo(info); } diff --git a/src/main/java/forestry/mail/proxy/ProxyMail.java b/src/main/java/forestry/mail/proxy/ProxyMail.java index 523c21694..acb3221c5 100755 --- a/src/main/java/forestry/mail/proxy/ProxyMail.java +++ b/src/main/java/forestry/mail/proxy/ProxyMail.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.mail.proxy; -import forestry.api.mail.MailAddress; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; @@ -18,6 +17,7 @@ import forestry.core.network.PacketIds; import forestry.core.proxy.Proxies; import forestry.mail.POBoxInfo; import forestry.mail.network.PacketPOBoxInfo; +import forestry.api.mail.IMailAddress; public class ProxyMail { @@ -27,8 +27,8 @@ public class ProxyMail { public void resetMailboxInfo() { } - public void setPOBoxInfo(World world, MailAddress address, POBoxInfo info) { - EntityPlayer player = address.getPlayer(world); + public void setPOBoxInfo(World world, IMailAddress address, POBoxInfo info) { + EntityPlayer player = Proxies.common.getPlayer(world, address.getPlayerProfile()); if (player != null) Proxies.net.sendToPlayer(new PacketPOBoxInfo(PacketIds.POBOX_INFO, info), player); } diff --git a/src/main/java/forestry/mail/triggers/TriggerLowPaper.java b/src/main/java/forestry/mail/triggers/TriggerLowPaper.java index 3d9402c1c..f2e374310 100755 --- a/src/main/java/forestry/mail/triggers/TriggerLowPaper.java +++ b/src/main/java/forestry/mail/triggers/TriggerLowPaper.java @@ -21,9 +21,9 @@ import forestry.mail.gadgets.MachineTrader; public class TriggerLowPaper extends Trigger { - float threshold; + int threshold; - public TriggerLowPaper(String tag, float threshold) { + public TriggerLowPaper(String tag, int threshold) { super(tag, "lowPaper"); this.threshold = threshold; } diff --git a/src/main/java/forestry/plugins/PluginArboriculture.java b/src/main/java/forestry/plugins/PluginArboriculture.java index f896efb4f..31f51f179 100755 --- a/src/main/java/forestry/plugins/PluginArboriculture.java +++ b/src/main/java/forestry/plugins/PluginArboriculture.java @@ -89,6 +89,7 @@ import forestry.arboriculture.genetics.TreeTemplates; import forestry.arboriculture.genetics.TreekeepingMode; import forestry.arboriculture.items.ItemGermlingGE; import forestry.arboriculture.items.ItemGrafter; +import forestry.arboriculture.items.ItemLeavesBlock; import forestry.arboriculture.items.ItemStairs; import forestry.arboriculture.items.ItemTreealyzer; import forestry.arboriculture.items.ItemWoodBlock; @@ -233,7 +234,7 @@ public class PluginArboriculture extends NativePlugin implements IFuelHandler { ForestryBlock.saplingGE.registerBlock(new BlockSapling(), ItemForestryBlock.class, "saplingGE"); // Leaves - ForestryBlock.leaves.registerBlock(new BlockLeaves(), ItemForestryBlock.class, "leaves"); + ForestryBlock.leaves.registerBlock(new BlockLeaves(), ItemLeavesBlock.class, "leaves"); // Pods ForestryBlock.pods.registerBlock(new BlockFruitPod(), ItemForestryBlock.class, "pods"); diff --git a/src/main/java/forestry/plugins/PluginBuildCraft.java b/src/main/java/forestry/plugins/PluginBuildCraft.java index 8b638e8a0..763d679e9 100755 --- a/src/main/java/forestry/plugins/PluginBuildCraft.java +++ b/src/main/java/forestry/plugins/PluginBuildCraft.java @@ -53,6 +53,7 @@ public class PluginBuildCraft implements IPlugin, ITriggerProvider { public static Item wrench; public static Item stoneGear; public static Item pipeWaterproof; + public static final String validVersionRange = "[6.0.0,6.1.0)"; public PluginBuildCraft() { if (PluginBuildCraft.instance == null) @@ -64,7 +65,7 @@ public class PluginBuildCraft implements IPlugin, ITriggerProvider { */ @Override public boolean isAvailable() { - return (Proxies.common.isModLoaded("BuildCraft|Core") && Proxies.common.isModLoaded("BuildCraft|Transport")); + return (Proxies.common.isModLoaded("BuildCraft|Core", validVersionRange) && Proxies.common.isModLoaded("BuildCraft|Transport", validVersionRange)); } @Override diff --git a/src/main/java/forestry/plugins/PluginCore.java b/src/main/java/forestry/plugins/PluginCore.java index e75a3e390..d1ede8490 100755 --- a/src/main/java/forestry/plugins/PluginCore.java +++ b/src/main/java/forestry/plugins/PluginCore.java @@ -64,6 +64,7 @@ import forestry.core.items.ItemAssemblyKit; import forestry.core.items.ItemCrated; import forestry.core.items.ItemForestry; import forestry.core.items.ItemForestryBlock; +import forestry.core.items.ItemTypedBlock; import forestry.core.items.ItemForestryPickaxe; import forestry.core.items.ItemForestryShovel; import forestry.core.items.ItemFruit; @@ -111,7 +112,7 @@ public class PluginCore extends NativePlugin implements IFuelHandler { definitionEscritoire = ((BlockBase) ForestryBlock.core.block()).addDefinition(new MachineDefinition(Defaults.DEFINITION_ESCRITOIRE_META, "forestry.Escritoire", TileEscritoire.class, Proxies.render.getRenderEscritoire())); - ForestryBlock.soil.registerBlock(new BlockSoil(), ItemForestryBlock.class, "soil"); + ForestryBlock.soil.registerBlock(new BlockSoil(), ItemTypedBlock.class, "soil"); ForestryBlock.soil.block().setHarvestLevel("shovel", 0, 0); ForestryBlock.soil.block().setHarvestLevel("shovel", 0, 1); @@ -354,9 +355,6 @@ public class PluginCore extends NativePlugin implements IFuelHandler { ForestryItem.cratedWheat.registerItem(new ItemCrated(new ItemStack(Items.wheat)), "cratedWheat"); ForestryItem.cratedMycelium.registerItem(new ItemCrated(new ItemStack(Blocks.mycelium)), "cratedMycelium"); ForestryItem.cratedMulch.registerItem(new ItemCrated(ForestryItem.mulch.getItemStack()), "cratedMulch"); - ForestryItem.cratedSilver.registerItem(new ItemCrated(), "cratedSilver"); - ForestryItem.cratedBrass.registerItem(new ItemCrated(), "cratedBrass"); - ForestryItem.cratedNikolite.registerItem(new ItemCrated(), "cratedNikolite"); ForestryItem.cratedCookies.registerItem(new ItemCrated(new ItemStack(Items.cookie)), "cratedCookies"); ForestryItem.cratedRedstone.registerItem(new ItemCrated(new ItemStack(Items.redstone)), "cratedRedstone"); ForestryItem.cratedLapis.registerItem(new ItemCrated(new ItemStack(Items.dye, 1, 4)), "cratedLapis"); @@ -365,10 +363,6 @@ public class PluginCore extends NativePlugin implements IFuelHandler { ForestryItem.cratedGlowstone.registerItem(new ItemCrated(new ItemStack(Items.glowstone_dust)), "cratedGlowstone"); ForestryItem.cratedApples.registerItem(new ItemCrated(new ItemStack(Items.apple)), "cratedApples"); ForestryItem.cratedNetherwart.registerItem(new ItemCrated(new ItemStack(Items.nether_wart)), "cratedNetherwart"); - ForestryItem.cratedResin.registerItem(new ItemCrated(), "cratedResin"); - ForestryItem.cratedRubber.registerItem(new ItemCrated(), "cratedRubber"); - ForestryItem.cratedScrap.registerItem(new ItemCrated(), "cratedScrap"); - ForestryItem.cratedUUM.registerItem(new ItemCrated(), "cratedUUM"); ForestryItem.cratedPhosphor.registerItem(new ItemCrated(ForestryItem.phosphor.getItemStack()), "cratedPhosphor"); ForestryItem.cratedAsh.registerItem(new ItemCrated(ForestryItem.ash.getItemStack()), "cratedAsh"); ForestryItem.cratedCharcoal.registerItem(new ItemCrated(new ItemStack(Items.coal, 1, 1)), "cratedCharcoal"); diff --git a/src/main/java/forestry/plugins/PluginEnergy.java b/src/main/java/forestry/plugins/PluginEnergy.java index f578cac3c..c25538fbd 100755 --- a/src/main/java/forestry/plugins/PluginEnergy.java +++ b/src/main/java/forestry/plugins/PluginEnergy.java @@ -13,7 +13,8 @@ package forestry.plugins; import net.minecraft.block.material.Material; import net.minecraft.init.Blocks; import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; + +import net.minecraftforge.fluids.FluidStack; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.network.IGuiHandler; @@ -21,6 +22,7 @@ import cpw.mods.fml.common.network.IGuiHandler; import forestry.api.circuits.ChipsetManager; import forestry.api.circuits.ICircuitLayout; import forestry.api.core.PluginInfo; +import forestry.api.fuels.FuelManager; import forestry.api.fuels.GeneratorFuel; import forestry.core.GameMode; import forestry.core.circuits.Circuit; @@ -146,18 +148,19 @@ public class PluginEnergy extends NativePlugin { definitionGenerator.register(); definitionEngineClockwork.register(); - GeneratorFuel.fuels.put(LiquidHelper.getLiquid(Defaults.LIQUID_ETHANOL, 1).getFluid().getID(), new GeneratorFuel(LiquidHelper.getLiquid(Defaults.LIQUID_ETHANOL, 1), - (int) (32 * GameMode.getGameMode().getFloatSetting("fuel.ethanol.generator")), 4)); - GeneratorFuel.fuels.put(LiquidHelper.getLiquid(Defaults.LIQUID_BIOMASS, 1).getFluid().getID(), new GeneratorFuel(LiquidHelper.getLiquid(Defaults.LIQUID_BIOMASS, 1), - (int) (8 * GameMode.getGameMode().getFloatSetting("fuel.biomass.generator")), 1)); + FluidStack ethanol = LiquidHelper.getLiquid(Defaults.LIQUID_ETHANOL, 1); + GeneratorFuel ethanolFuel = new GeneratorFuel(ethanol, (int) (32 * GameMode.getGameMode().getFloatSetting("fuel.ethanol.generator")), 4); + FuelManager.generatorFuel.put(ethanol.getFluid(), ethanolFuel); - Circuit.energyElectricChoke1 = new CircuitElectricChoke("energyChoke1"); - Circuit.energyFireDampener1 = new CircuitFireDampener("energyDampener1"); - Circuit.energyElectricEfficiency1 = new CircuitElectricEfficiency("energyEfficiency1"); - Circuit.energyElectricBoost1 = new CircuitElectricBoost("energyBoost1", 2, 7, 2, "electric.boost.1", new String[]{"Increases output by 2 MJ/t", - "Increases intake by 7 EU/t"}); - Circuit.energyElectricBoost2 = new CircuitElectricBoost("energyBoost2", 2, 15, 4, "electric.boost.2", new String[]{"Increases output by 4 MJ/t", - "Increases intake by 15 EU/t"}); + FluidStack biomass = LiquidHelper.getLiquid(Defaults.LIQUID_BIOMASS, 1); + GeneratorFuel biomassFuel = new GeneratorFuel(biomass, (int) (8 * GameMode.getGameMode().getFloatSetting("fuel.biomass.generator")), 1); + FuelManager.generatorFuel.put(biomass.getFluid(), biomassFuel); + + Circuit.energyElectricChoke1 = new CircuitElectricChoke("electric.choke.1"); + Circuit.energyFireDampener1 = new CircuitFireDampener("dampener.1"); + Circuit.energyElectricEfficiency1 = new CircuitElectricEfficiency("electric.efficiency.1"); + Circuit.energyElectricBoost1 = new CircuitElectricBoost("electric.boost.1", 2, 7, 2); + Circuit.energyElectricBoost2 = new CircuitElectricBoost("electric.boost.2", 2, 15, 4); } @Override diff --git a/src/main/java/forestry/plugins/PluginFarming.java b/src/main/java/forestry/plugins/PluginFarming.java index b5980eb2c..018f20a78 100755 --- a/src/main/java/forestry/plugins/PluginFarming.java +++ b/src/main/java/forestry/plugins/PluginFarming.java @@ -40,7 +40,7 @@ import forestry.core.config.ForestryBlock; import forestry.core.config.ForestryItem; import forestry.core.interfaces.IOreDictionaryHandler; import forestry.core.interfaces.ISaveEventHandler; -import forestry.core.items.ItemForestryBlock; +import forestry.core.items.ItemTypedBlock; import forestry.core.proxy.Proxies; import forestry.core.triggers.Trigger; import forestry.core.utils.ShapedRecipeCustom; @@ -107,7 +107,7 @@ public class PluginFarming extends NativePlugin { Farmables.farmInterface = new FarmHelper(); - ForestryBlock.mushroom.registerBlock(new BlockMushroom(), ItemForestryBlock.class, "mushroom"); + ForestryBlock.mushroom.registerBlock(new BlockMushroom(), ItemTypedBlock.class, "mushroom"); Farmables.farmables.put("farmArboreal", new ArrayList()); Farmables.farmables.get("farmArboreal").add(new FarmableVanillaSapling()); @@ -171,24 +171,24 @@ public class PluginFarming extends NativePlugin { GameRegistry.registerTileEntity(TileValve.class, "forestry.FarmValve"); GameRegistry.registerTileEntity(TileControl.class, "forestry.FarmControl"); - Circuit.farmArborealManaged = new CircuitFarmLogic("managedArboreal", FarmLogicArboreal.class, new String[]{"Arboreal Plants"}); - Circuit.farmShroomManaged = new CircuitFarmLogic("managedShroom", FarmLogicShroom.class, new String[]{"Mushrooms"}); - Circuit.farmPeatManaged = new CircuitFarmLogic("managedPeat", FarmLogicPeat.class, new String[]{"Peat Bog"}); - Circuit.farmCerealManaged = new CircuitFarmLogic("managedCereal", FarmLogicCereal.class, new String[]{"Crops"}); - Circuit.farmVegetableManaged = new CircuitFarmLogic("managedVegetable", FarmLogicVegetable.class, new String[]{"Vegetables"}); - Circuit.farmInfernalManaged = new CircuitFarmLogic("managedInfernal", FarmLogicInfernal.class, new String[]{"Infernal Crops"}); + Circuit.farmArborealManaged = new CircuitFarmLogic("managedArboreal", FarmLogicArboreal.class); + Circuit.farmShroomManaged = new CircuitFarmLogic("managedShroom", FarmLogicShroom.class); + Circuit.farmPeatManaged = new CircuitFarmLogic("managedPeat", FarmLogicPeat.class); + Circuit.farmCerealManaged = new CircuitFarmLogic("managedCereal", FarmLogicCereal.class); + Circuit.farmVegetableManaged = new CircuitFarmLogic("managedVegetable", FarmLogicVegetable.class); + Circuit.farmInfernalManaged = new CircuitFarmLogic("managedInfernal", FarmLogicInfernal.class); - Circuit.farmPeatManual = new CircuitFarmLogic("manualPeat", FarmLogicPeat.class, new String[]{"Peat Bog"}).setManual(); - Circuit.farmShroomManual = new CircuitFarmLogic("manualShroom", FarmLogicShroom.class, new String[]{"Mushrooms"}).setManual(); - Circuit.farmCerealManual = new CircuitFarmLogic("manualCereal", FarmLogicCereal.class, new String[]{"Crops"}).setManual(); - Circuit.farmVegetableManual = new CircuitFarmLogic("manualVegetable", FarmLogicVegetable.class, new String[]{"Vegetables"}).setManual(); - Circuit.farmSucculentManual = new CircuitFarmLogic("manualSucculent", FarmLogicSucculent.class, new String[]{"Succulents"}).setManual(); - Circuit.farmPoalesManual = new CircuitFarmLogic("manualPoales", FarmLogicPoale.class, new String[]{"Reeds"}).setManual(); - Circuit.farmGourdManual = new CircuitFarmLogic("manualGourd", FarmLogicGourd.class, new String[]{"Gourds"}).setManual(); - Circuit.farmCocoaManual = new CircuitFarmLogic("manualCocoa", FarmLogicCocoa.class, new String[]{"Cocoa Plantation"}).setManual(); + Circuit.farmPeatManual = new CircuitFarmLogic("manualPeat", FarmLogicPeat.class).setManual(); + Circuit.farmShroomManual = new CircuitFarmLogic("manualShroom", FarmLogicShroom.class).setManual(); + Circuit.farmCerealManual = new CircuitFarmLogic("manualCereal", FarmLogicCereal.class).setManual(); + Circuit.farmVegetableManual = new CircuitFarmLogic("manualVegetable", FarmLogicVegetable.class).setManual(); + Circuit.farmSucculentManual = new CircuitFarmLogic("manualSucculent", FarmLogicSucculent.class).setManual(); + Circuit.farmPoalesManual = new CircuitFarmLogic("manualPoales", FarmLogicPoale.class).setManual(); + Circuit.farmGourdManual = new CircuitFarmLogic("manualGourd", FarmLogicGourd.class).setManual(); + Circuit.farmCocoaManual = new CircuitFarmLogic("manualCocoa", FarmLogicCocoa.class).setManual(); - Circuit.farmOrchardManual = new CircuitFarmLogic("manualOrchard", FarmLogicOrchard.class, new String[]{"Orchard"}); - Circuit.farmRubberManual = new CircuitFarmLogic("manualRubber", FarmLogicRubber.class, new String[]{"Rubber Plantation"}); + Circuit.farmOrchardManual = new CircuitFarmLogic("manualOrchard", FarmLogicOrchard.class); + Circuit.farmRubberManual = new CircuitFarmLogic("manualRubber", FarmLogicRubber.class); MinecraftForge.EVENT_BUS.register(new EventHandlerFarming()); } diff --git a/src/main/java/forestry/plugins/PluginIC2.java b/src/main/java/forestry/plugins/PluginIC2.java index 251c8b33e..a247d5bd2 100755 --- a/src/main/java/forestry/plugins/PluginIC2.java +++ b/src/main/java/forestry/plugins/PluginIC2.java @@ -59,6 +59,9 @@ public class PluginIC2 implements IPlugin { public static ItemStack waterCell; public static ItemStack rubber; public static ItemStack scrap; + public static ItemStack silver; + public static ItemStack brass; + public static ItemStack uuMatter; public static int fuelcanMeta; public PluginIC2() { @@ -101,16 +104,6 @@ public class PluginIC2 implements IPlugin { // Remove some items from the recycler registerBackpackItems(); - - if (rubbersapling != null && resin != null) { - String imc = String.format("farmArboreal@%s.%s.%s.%s", - GameData.getBlockRegistry().getNameForObject(StackUtils.getBlock(rubbersapling)), - rubbersapling.getItemDamage(), - GameData.getItemRegistry().getNameForObject(resin.getItem()), - resin.getItemDamage()); - Proxies.log.finest("Sending IMC '%s'.", imc); - FMLInterModComms.sendMessage(Defaults.MOD, "add-farmable-sapling", imc); - } } private void initFermentation() { @@ -128,68 +121,113 @@ public class PluginIC2 implements IPlugin { private void initLiquidContainers() { emptyCell = IC2Items.getItem("cell"); - lavaCell = IC2Items.getItem("lavaCell"); - waterCell = IC2Items.getItem("waterCell"); - if (emptyCell == null || lavaCell == null || waterCell == null) { - Proxies.log.fine("Any of the following IC2 items could not be found: empty cell, water cell, lava cell. Skipped adding IC2 liquid containers."); + if (emptyCell == null) { + Proxies.log.fine("IC2 empty cell could not be found. Skipped adding IC2 liquid containers."); return; } - LiquidHelper.injectTinContainer(Defaults.LIQUID_LAVA, Defaults.BUCKET_VOLUME, lavaCell, emptyCell); - LiquidHelper.injectTinContainer(Defaults.LIQUID_WATER, Defaults.BUCKET_VOLUME, waterCell, emptyCell); - if (GameMode.getGameMode().getStackSetting("recipe.output.bogearth.can").stackSize > 0) - Proxies.common - .addRecipe(GameMode.getGameMode().getStackSetting("recipe.output.bogearth.can"), "#Y#", "YXY", "#Y#", '#', Blocks.dirt, 'X', waterCell, 'Y', Blocks.sand); + lavaCell = IC2Items.getItem("lavaCell"); + if (lavaCell != null) + LiquidHelper.injectTinContainer(Defaults.LIQUID_LAVA, Defaults.BUCKET_VOLUME, lavaCell, emptyCell); + + waterCell = IC2Items.getItem("waterCell"); + if (waterCell != null) { + LiquidHelper.injectTinContainer(Defaults.LIQUID_WATER, Defaults.BUCKET_VOLUME, waterCell, emptyCell); + + ItemStack bogEarthCan = GameMode.getGameMode().getStackSetting("recipe.output.bogearth.can"); + if (bogEarthCan.stackSize > 0) + Proxies.common.addRecipe(bogEarthCan, "#Y#", "YXY", "#Y#", '#', Blocks.dirt, 'X', waterCell, 'Y', Blocks.sand); + } } private void initRubberChain() { treetap = IC2Items.getItem("treetap"); - resin = IC2Items.getItem("resin"); rubberwood = IC2Items.getItem("rubberWood"); + + resin = IC2Items.getItem("resin"); + if (resin != null) + RecipeManagers.centrifugeManager.addRecipe(20, ForestryItem.propolis.getItemStack(), resin); + else + Proxies.log.fine("Missing IC2 resin, skipping centrifuge recipe for propolis to resin."); + rubbersapling = IC2Items.getItem("rubberSapling"); - rubberleaves = IC2Items.getItem("rubberLeaves"); - fuelcanFilled = IC2Items.getItem("filledFuelCan"); - fuelcanEmpty = IC2Items.getItem("fuelCan"); - if (treetap == null || resin == null || rubberwood == null || rubbersapling == null || rubberleaves == null || fuelcanFilled == null - || fuelcanEmpty == null) { - Proxies.log - .fine("Any of the following IC2 blocks and items could not be found: resin, rubber wood, saplings or leaves, filled fuel cans, empty fuel cans. Skipped adding rubber chain."); - return; + if (rubbersapling != null) { + RecipeUtil.injectLeveledRecipe(rubbersapling, GameMode.getGameMode().getIntegerSetting("fermenter.yield.sapling"), Defaults.LIQUID_BIOMASS); + BackpackManager.backpackItems[2].add(rubbersapling); + } else { + Proxies.log.fine("Missing IC2 rubber sapling, skipping fermenter recipe for converting rubber sapling to biomass."); } - // Add extra recipes - RecipeManagers.centrifugeManager.addRecipe(20, ForestryItem.propolis.getItemStack(), resin); - ItemStack fuelcanStack = new ItemStack(fuelcanFilled.getItem(), 1, 0); - NBTTagCompound compound = new NBTTagCompound(); - compound.setInteger("value", 15288); - fuelcanStack.setTagCompound(compound); - RecipeManagers.bottlerManager.addRecipe(20, LiquidHelper.getLiquid(Defaults.LIQUID_ETHANOL, Defaults.BOTTLER_FUELCAN_VOLUME), fuelcanEmpty, fuelcanStack); + if (rubbersapling != null && resin != null) { + String saplingName = GameData.getBlockRegistry().getNameForObject(StackUtils.getBlock(rubbersapling)); + String resinName = GameData.getItemRegistry().getNameForObject(resin.getItem()); + String imc = String.format("farmArboreal@%s.%s.%s.%s", + saplingName, rubbersapling.getItemDamage(), + resinName, resin.getItemDamage()); + Proxies.log.finest("Sending IMC '%s'.", imc); + FMLInterModComms.sendMessage(Defaults.MOD, "add-farmable-sapling", imc); + } - RecipeUtil.injectLeveledRecipe(rubbersapling, GameMode.getGameMode().getIntegerSetting("fermenter.yield.sapling"), Defaults.LIQUID_BIOMASS); + rubberleaves = IC2Items.getItem("rubberLeaves"); + if (rubberleaves != null) + BackpackManager.backpackItems[2].add(rubberleaves); + else + Proxies.log.fine("Missing IC2 rubber leaves"); + + fuelcanFilled = IC2Items.getItem("filledFuelCan"); + fuelcanEmpty = IC2Items.getItem("fuelCan"); + if (fuelcanEmpty != null && fuelcanFilled != null) { + ItemStack fuelcanStack = new ItemStack(fuelcanFilled.getItem(), 1, 0); + NBTTagCompound compound = new NBTTagCompound(); + compound.setInteger("value", 15288); + fuelcanStack.setTagCompound(compound); + RecipeManagers.bottlerManager.addRecipe(20, LiquidHelper.getLiquid(Defaults.LIQUID_ETHANOL, Defaults.BOTTLER_FUELCAN_VOLUME), fuelcanEmpty, fuelcanStack); + } else { + Proxies.log.fine("Missing IC2 fuelcanEmpty or fuelcanFilled, skipping bottler recipe for ethanol to filled fuel can."); + } - // Add backpack items - BackpackManager.backpackItems[2].add(rubbersapling); - BackpackManager.backpackItems[2].add(rubberleaves); // Rubber wood is added via ore dictionary. } private void initCrates() { - resin = IC2Items.getItem("resin"); - rubber = IC2Items.getItem("rubber"); - scrap = IC2Items.getItem("scrap"); // Add crates for the IC2 items that exist. + + resin = IC2Items.getItem("resin"); if (resin != null) { + ForestryItem.cratedResin.registerItem(new ItemCrated(), "cratedResin"); ((ItemCrated) ForestryItem.cratedResin.item()).setContained(ForestryItem.cratedResin.getItemStack(), resin); } + rubber = IC2Items.getItem("rubber"); if (rubber != null) { + ForestryItem.cratedRubber.registerItem(new ItemCrated(), "cratedRubber"); ((ItemCrated) ForestryItem.cratedRubber.item()).setContained(ForestryItem.cratedRubber.getItemStack(), rubber); } + scrap = IC2Items.getItem("scrap"); if (scrap != null) { + ForestryItem.cratedScrap.registerItem(new ItemCrated(), "cratedScrap"); ((ItemCrated) ForestryItem.cratedScrap.item()).setContained(ForestryItem.cratedScrap.getItemStack(), scrap); } + + uuMatter = IC2Items.getItem("matter"); + if (uuMatter != null) { + ForestryItem.cratedUUM.registerItem(new ItemCrated(), "cratedUUM"); + ((ItemCrated) ForestryItem.cratedUUM.item()).setContained(ForestryItem.cratedUUM.getItemStack(), uuMatter); + } + + silver = IC2Items.getItem("silverIngot"); + if (silver != null) { + ForestryItem.cratedSilver.registerItem(new ItemCrated(), "cratedSilver"); + ((ItemCrated) ForestryItem.cratedSilver.item()).setContained(ForestryItem.cratedSilver.getItemStack(), silver); + } + + brass = IC2Items.getItem("bronzeIngot"); + if (brass != null) { + ForestryItem.cratedBrass.registerItem(new ItemCrated(), "cratedBrass"); + ((ItemCrated) ForestryItem.cratedBrass.item()).setContained(ForestryItem.cratedBrass.getItemStack(), brass); + } } private void registerBackpackItems() { diff --git a/src/main/java/forestry/plugins/PluginMail.java b/src/main/java/forestry/plugins/PluginMail.java index 22b471e6e..0329b1ea7 100755 --- a/src/main/java/forestry/plugins/PluginMail.java +++ b/src/main/java/forestry/plugins/PluginMail.java @@ -38,7 +38,7 @@ import forestry.core.triggers.Trigger; import forestry.core.utils.LiquidHelper; import forestry.core.utils.ShapedRecipeCustom; import forestry.mail.CommandMail; -import forestry.mail.EnumAddressee; +import forestry.api.mail.EnumAddressee; import forestry.mail.GuiHandlerMail; import forestry.mail.PacketHandlerMail; import forestry.mail.PostRegistry; @@ -65,8 +65,8 @@ public class PluginMail extends NativePlugin { @SidedProxy(clientSide = "forestry.mail.proxy.ClientProxyMail", serverSide = "forestry.mail.proxy.ProxyMail") public static ProxyMail proxy; public static Trigger triggerHasMail; - public static Trigger lowPaper25; - public static Trigger lowPaper10; + public static Trigger lowPaper64; + public static Trigger lowPaper32; public static Trigger lowPostage40; public static Trigger lowPostage20; public static Trigger lowInput25; @@ -90,8 +90,8 @@ public class PluginMail extends NativePlugin { new TickHandlerMailClient(); triggerHasMail = new TriggerHasMail(); - lowPaper25 = new TriggerLowPaper("mail.lowPaper.25", 0.25f); - lowPaper10 = new TriggerLowPaper("mail.lowPaper.10", 0.1f); + lowPaper64 = new TriggerLowPaper("mail.lowPaper.64", 64); + lowPaper32 = new TriggerLowPaper("mail.lowPaper.32", 32); lowPostage40 = new TriggerLowStamps("mail.lowStamps.40", 40); lowPostage20 = new TriggerLowStamps("mail.lowStamps.20", 20); lowInput25 = new TriggerLowInput("mail.lowInput.25", 0.25f); diff --git a/src/main/java/forestry/plugins/PluginNatura.java b/src/main/java/forestry/plugins/PluginNatura.java index 61a45fcf0..5ccf0fba9 100755 --- a/src/main/java/forestry/plugins/PluginNatura.java +++ b/src/main/java/forestry/plugins/PluginNatura.java @@ -12,7 +12,9 @@ package forestry.plugins; import java.util.ArrayList; +import cpw.mods.fml.common.registry.GameData; import net.minecraft.block.Block; +import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import cpw.mods.fml.common.event.FMLInterModComms; @@ -33,6 +35,7 @@ public class PluginNatura extends NativePlugin { public static Block leavesNatura; public static Block saplingNatura; + public static Block saplingNaturaRare; @Override public boolean isAvailable() { @@ -47,9 +50,20 @@ public class PluginNatura extends NativePlugin { logWillow = GameRegistry.findBlock(NATURA, "willow"); leavesNatura = GameRegistry.findBlock(NATURA, "floraleaves"); saplingNatura = GameRegistry.findBlock(NATURA, "florasapling"); - + saplingNaturaRare = GameRegistry.findBlock(NATURA, "Rare Sapling"); + + ArrayList saplingItemKeys = new ArrayList(); + if(saplingNatura != null) - FMLInterModComms.sendMessage(Defaults.MOD, "add-farmable-sapling", String.format("farmArboreal@%s.-1", saplingNatura)); + saplingItemKeys.add("florasapling"); + if(saplingNaturaRare != null) + saplingItemKeys.add("Rare Sapling"); + + for (String key : saplingItemKeys) { + Item saplingItem = GameRegistry.findItem(NATURA, key); + String saplingName = GameData.getItemRegistry().getNameForObject(saplingItem); + FMLInterModComms.sendMessage(Defaults.MOD, "add-farmable-sapling", String.format("farmArboreal@%s.-1", saplingName)); + } } @Override protected void registerItems() {} diff --git a/src/main/java/forestry/plugins/PluginPropolisPipe.java b/src/main/java/forestry/plugins/PluginPropolisPipe.java index f90d87cba..a068bb5f7 100755 --- a/src/main/java/forestry/plugins/PluginPropolisPipe.java +++ b/src/main/java/forestry/plugins/PluginPropolisPipe.java @@ -38,7 +38,7 @@ public class PluginPropolisPipe extends NativePlugin { @Override public boolean isAvailable() { - return Proxies.common.isModLoaded("BuildCraft|Transport"); + return Proxies.common.isModLoaded("BuildCraft|Transport", PluginBuildCraft.validVersionRange); } @Override @@ -62,7 +62,7 @@ public class PluginPropolisPipe extends NativePlugin { if (FMLCommonHandler.instance().getSide().isClient()) proxyClass = "forestry.pipes.proxy.ClientProxyPipes"; - proxy = (ProxyPipes) Proxies.common.instantiateIfModLoaded("BuildCraft|Transport", proxyClass); + proxy = (ProxyPipes) Proxies.common.instantiateIfModLoaded("BuildCraft|Transport", PluginBuildCraft.validVersionRange, proxyClass); if (proxy == null) return; diff --git a/src/main/java/forestry/plugins/PluginStorage.java b/src/main/java/forestry/plugins/PluginStorage.java index ba7aa18d2..853bc9900 100755 --- a/src/main/java/forestry/plugins/PluginStorage.java +++ b/src/main/java/forestry/plugins/PluginStorage.java @@ -589,6 +589,12 @@ public class PluginStorage extends NativePlugin implements IOreDictionaryHandler minerItems.add(ore); else if (name.startsWith("crystal")) minerItems.add(ore); + else if (name.startsWith("cluster")) + minerItems.add(ore); + else if (name.startsWith("shard")) + minerItems.add(ore); + else if (name.startsWith("clump")) + minerItems.add(ore); else if (name.matches("dropUranium")) minerItems.add(ore); else if (name.equals("treeLeaves") || name.equals("treeSapling") || name.equals("logWood")) diff --git a/src/main/java/forestry/storage/items/ItemBackpack.java b/src/main/java/forestry/storage/items/ItemBackpack.java index 3dbe05c69..b7e0d2c27 100755 --- a/src/main/java/forestry/storage/items/ItemBackpack.java +++ b/src/main/java/forestry/storage/items/ItemBackpack.java @@ -157,7 +157,8 @@ public class ItemBackpack extends ItemInventoried { // Create our own backpack inventory ItemInventory backpackInventory = new ItemInventory(ItemBackpack.class, getBackpackSize(), stack); - if (stack.getItemDamage() == 2) + BackpackMode mode = getMode(stack); + if (mode == BackpackMode.RECEIVE) tryChestReceive(player, backpackInventory, inventory); else tryChestTransfer(backpackInventory, inventory); diff --git a/src/main/resources/assets/forestry/textures/gui/beealyzer.png b/src/main/resources/assets/forestry/textures/gui/beealyzer.png deleted file mode 100755 index 726c4c757..000000000 Binary files a/src/main/resources/assets/forestry/textures/gui/beealyzer.png and /dev/null differ diff --git a/src/main/resources/assets/forestry/textures/gui/beealyzer2.png b/src/main/resources/assets/forestry/textures/gui/beealyzer2.png new file mode 100644 index 000000000..4bc31f73c Binary files /dev/null and b/src/main/resources/assets/forestry/textures/gui/beealyzer2.png differ diff --git a/src/main/resources/assets/forestry/textures/gui/mailtrader.png b/src/main/resources/assets/forestry/textures/gui/mailtrader.png deleted file mode 100755 index 534268b95..000000000 Binary files a/src/main/resources/assets/forestry/textures/gui/mailtrader.png and /dev/null differ diff --git a/src/main/resources/assets/forestry/textures/gui/mailtrader2.png b/src/main/resources/assets/forestry/textures/gui/mailtrader2.png new file mode 100644 index 000000000..9cc2bcb9b Binary files /dev/null and b/src/main/resources/assets/forestry/textures/gui/mailtrader2.png differ diff --git a/src/main/resources/assets/forestry/textures/gui/worktable.png b/src/main/resources/assets/forestry/textures/gui/worktable.png deleted file mode 100755 index dd59d8ff0..000000000 Binary files a/src/main/resources/assets/forestry/textures/gui/worktable.png and /dev/null differ diff --git a/src/main/resources/assets/forestry/textures/gui/worktable2.png b/src/main/resources/assets/forestry/textures/gui/worktable2.png new file mode 100644 index 000000000..48d18d27e Binary files /dev/null and b/src/main/resources/assets/forestry/textures/gui/worktable2.png differ diff --git a/src/main/resources/assets/forestry/textures/items/errors/noPaper.png b/src/main/resources/assets/forestry/textures/items/errors/noPaper.png new file mode 100644 index 000000000..da8fb928b Binary files /dev/null and b/src/main/resources/assets/forestry/textures/items/errors/noPaper.png differ diff --git a/src/main/resources/assets/forestry/textures/items/errors/notPostpaid.png b/src/main/resources/assets/forestry/textures/items/errors/notPostpaid.png deleted file mode 100755 index 2f373319d..000000000 Binary files a/src/main/resources/assets/forestry/textures/items/errors/notPostpaid.png and /dev/null differ