diff --git a/api/forestry b/api/forestry index 4c416da9d..a8e10de64 160000 --- a/api/forestry +++ b/api/forestry @@ -1 +1 @@ -Subproject commit 4c416da9d0d71002f9f9ea1c1603d8840a83f46f +Subproject commit a8e10de64200d2b66bf61f3c3ec30adb0e5a142b diff --git a/cla-signatures.txt b/cla-signatures.txt index 3bcb43807..4674d93ab 100644 --- a/cla-signatures.txt +++ b/cla-signatures.txt @@ -1,4 +1,5 @@ Account;Email;Date; samtrion;samtrion@gmail.com;2015-01-18 GenuineSounds;GenuineSoundsLtd@gmail.com;2015-02-26 -airbreather;airbreather@linux.com;2015-04-10 \ No newline at end of file +airbreather;airbreather@linux.com;2015-04-10 +ganymedes01;foka_12@hotmail.com;2015-05-27 diff --git a/lang b/lang index a626ae3d0..e111b835a 160000 --- a/lang +++ b/lang @@ -1 +1 @@ -Subproject commit a626ae3d0419d8e9537a9d34aabf095969a7f4be +Subproject commit e111b835ada3dde177bf2a54be6a641e74386eea diff --git a/src/main/java/forestry/apiculture/BeekeepingLogic.java b/src/main/java/forestry/apiculture/BeekeepingLogic.java index 48830daf8..1f3506988 100755 --- a/src/main/java/forestry/apiculture/BeekeepingLogic.java +++ b/src/main/java/forestry/apiculture/BeekeepingLogic.java @@ -36,6 +36,7 @@ public class BeekeepingLogic implements IBeekeepingLogic { private static final int MAX_POLLINATION_ATTEMPTS = 20; private static final int totalBreedingTime = Defaults.APIARY_BREEDING_TIME; + private static final int ticksPerCheckCanWork = 10; private final IBeeHousing housing; private final boolean housingSupportsMultipleErrorStates; @@ -49,6 +50,12 @@ public class BeekeepingLogic implements IBeekeepingLogic { private int attemptedPollinations = 0; private final Stack spawn = new Stack(); + // Cached flowers check + private boolean hasFlowersCached = false; + private int hasFlowersCooldown = 0; + private boolean canWorkCached = false; + private int canWorkCooldown = 0; + public BeekeepingLogic(IBeeHousing housing) { this.housing = housing; @@ -118,9 +125,19 @@ public class BeekeepingLogic implements IBeekeepingLogic { } /* UPDATING */ - @Override - public void update() { + @Override + public boolean canWork() { + if (canWorkCooldown > 0) { + canWorkCooldown--; + } else { + canWorkCached = checkCanWork(); + canWorkCooldown = ticksPerCheckCanWork; + } + return canWorkCached; + } + + private boolean checkCanWork() { if (housingSupportsMultipleErrorStates) { Set errorStates = housing.getErrorStates(); for (IErrorState errorState : errorStates) { @@ -128,24 +145,72 @@ public class BeekeepingLogic implements IBeekeepingLogic { } } - this.queen = null; + boolean hasSpace = addPendingProducts(); - if (!addPendingProducts()) { - return; - } - - if (tryBreedingPrincess() || !hasHealthyQueen()) { - return; + if (hasBreedablePrincess()) { + return hasSpace; } - if (!queenCanWork()) { - return; + if (hasHealthyQueen()) { + boolean canWork = queenCanWork(); + boolean hasFlowers = hasFlowers(); + return hasSpace && canWork && hasFlowers; } - queenWorkTick(); + return false; + } + + @Override + public void doWork() { + if (hasBreedablePrincess()) { + tickBreed(); + } else if (queen != null) { + queenWorkTick(); + } + } + + @Override + public void update() { + if (canWork()) { + doWork(); + } + } + + private boolean hasFlowers() { + if (queen == null) { + return true; + } + + if (hasFlowersCooldown <= 0) { + hasFlowersCached = queen.hasFlower(housing); + hasFlowersCooldown = PluginApiculture.ticksPerBeeWorkCycle / ticksPerCheckCanWork; + + // check more often if we haven't found flowers + if (!hasFlowersCached) { + hasFlowersCooldown /= 2; + } + } else { + hasFlowersCooldown--; + } + + if (housingSupportsMultipleErrorStates) { + housing.setErrorCondition(!hasFlowersCached, EnumErrorCode.NOFLOWER); + } else { + if (hasFlowersCached) { + housing.setErrorState(EnumErrorCode.OK); + } else { + housing.setErrorState(EnumErrorCode.NOFLOWER); + } + } + + return hasFlowersCached; } private void queenWorkTick() { + if (queen == null) { + return; + } + // Effects only fire when queen can work. effectData = queen.doEffect(effectData, housing); @@ -154,22 +219,6 @@ public class BeekeepingLogic implements IBeekeepingLogic { if (queenWorkCycleThrottle >= PluginApiculture.ticksPerBeeWorkCycle) { queenWorkCycleThrottle = 0; - boolean hasFlower = queen.hasFlower(housing); - - if (housingSupportsMultipleErrorStates) { - housing.setErrorCondition(!hasFlower, EnumErrorCode.NOFLOWER); - } else { - if (hasFlower) { - housing.setErrorState(EnumErrorCode.OK); - } else { - housing.setErrorState(EnumErrorCode.NOFLOWER); - } - } - - if (!hasFlower) { - return; - } - doProduction(); queen.plantFlowerRandom(housing); doPollination(); @@ -181,8 +230,15 @@ public class BeekeepingLogic implements IBeekeepingLogic { } private void doProduction() { + if (queen == null) { + return; + } + // Produce and add stacks ItemStack[] products = queen.produceStacks(housing); + if (products == null) { + return; + } housing.wearOutEquipment(1); for (ItemStack stack : products) { housing.addProduct(stack, false); @@ -190,6 +246,10 @@ public class BeekeepingLogic implements IBeekeepingLogic { } private void doPollination() { + if (queen == null) { + return; + } + // Get pollen if none available yet if (pollen == null) { pollen = queen.retrievePollen(housing); @@ -209,6 +269,10 @@ public class BeekeepingLogic implements IBeekeepingLogic { } private void updateQueenItemNBT() { + if (queen == null) { + return; + } + // Write the changed queen back into the item stack. NBTTagCompound nbttagcompound = new NBTTagCompound(); queen.writeToNBT(nbttagcompound); @@ -240,24 +304,32 @@ public class BeekeepingLogic implements IBeekeepingLogic { return housingErrorState != EnumErrorCode.NOSPACE; } - + + /** Checks if a queen is alive. Much faster than reading the whole bee nbt */ + private static boolean isQueenAlive(ItemStack queenStack) { + NBTTagCompound nbtTagCompound = queenStack.getTagCompound(); + int health = nbtTagCompound.getInteger("Health"); + return health > 0; + } + private boolean hasHealthyQueen() { boolean hasQueen = true; EnumErrorCode housingErrorState = null; - if (housing.getQueen() == null || !ForestryItem.beeQueenGE.isItemEqual(housing.getQueen())) { + ItemStack queenStack = housing.getQueen(); + + if (queenStack == null || !ForestryItem.beeQueenGE.isItemEqual(housing.getQueen())) { housingErrorState = EnumErrorCode.NOQUEEN; hasQueen = false; - } else { - IBee queen = BeeManager.beeRoot.getMember(housing.getQueen()); - // Kill dying queens - if (!queen.isAlive()) { - killQueen(queen); - housingErrorState = EnumErrorCode.OK; - hasQueen = false; - } else { - this.queen = queen; + queen = null; + } else if (!isQueenAlive(queenStack)) { + if (queen == null) { + queen = BeeManager.beeRoot.getMember(queenStack); } + killQueen(); + housingErrorState = EnumErrorCode.OK; + hasQueen = false; + queen = null; } if (housingSupportsMultipleErrorStates) { @@ -268,13 +340,15 @@ public class BeekeepingLogic implements IBeekeepingLogic { } } + if (hasQueen && queen == null) { + queen = BeeManager.beeRoot.getMember(queenStack); + } + return hasQueen; } - - private boolean tryBreedingPrincess() { - boolean isBreedingPrincess = false; - // Princess available? Try to breed! + private boolean hasBreedablePrincess() { + boolean isBreedingPrincess = false; if (ForestryItem.beePrincessGE.isItemEqual(housing.getQueen())) { boolean hasDrone = ForestryItem.beeDroneGE.isItemEqual(housing.getDrone()); if (housingSupportsMultipleErrorStates) { @@ -286,7 +360,6 @@ public class BeekeepingLogic implements IBeekeepingLogic { housing.setErrorState(EnumErrorCode.NODRONE); } } - tickBreed(); isBreedingPrincess = true; } @@ -294,6 +367,9 @@ public class BeekeepingLogic implements IBeekeepingLogic { } private boolean queenCanWork() { + if (queen == null) { + return false; + } if (housingSupportsMultipleErrorStates) { try { @@ -371,14 +447,15 @@ public class BeekeepingLogic implements IBeekeepingLogic { return false; } - if (!housing.canBreed()) { - return false; - } + return housing.canBreed(); - return true; } - private void killQueen(IBee queen) { + private void killQueen() { + if (queen == null) { + return; + } + if (queen.canSpawn()) { spawnOffspring(queen); housing.getQueen().stackSize = 0; diff --git a/src/main/java/forestry/apiculture/GuiHandlerApiculture.java b/src/main/java/forestry/apiculture/GuiHandlerApiculture.java index 5d45757de..b294c33a8 100755 --- a/src/main/java/forestry/apiculture/GuiHandlerApiculture.java +++ b/src/main/java/forestry/apiculture/GuiHandlerApiculture.java @@ -59,19 +59,19 @@ public class GuiHandlerApiculture extends GuiHandlerBase { switch (GuiId.values()[cleanId]) { case AlvearyGUI: - return new GuiAlveary(player.inventory, (TileAlvearyPlain) getTileForestry(world, x, y, z)); + return new GuiAlveary(player.inventory, getTileForestry(world, x, y, z, player, TileAlvearyPlain.class)); case AlvearySieveGUI: - return new GuiAlvearySieve(player.inventory, (TileAlvearySieve) getTileForestry(world, x, y, z)); + return new GuiAlvearySieve(player.inventory, getTileForestry(world, x, y, z, player, TileAlvearySieve.class)); case AlvearySwarmerGUI: - return new GuiAlvearySwarmer(player.inventory, (TileAlvearySwarmer) getTileForestry(world, x, y, z)); + return new GuiAlvearySwarmer(player.inventory, getTileForestry(world, x, y, z, player, TileAlvearySwarmer.class)); case ApiaristChestGUI: return getNaturalistChestGui(BeeHelper.UID, player, world, x, y, z, guiData); case ApiaryGUI: - return new GuiApiary(player.inventory, (TileApiary) getTileForestry(world, x, y, z)); + return new GuiApiary(player.inventory, getTileForestry(world, x, y, z, player, TileApiary.class)); case BeealyzerGUI: equipped = player.getCurrentEquippedItem(); @@ -82,7 +82,7 @@ public class GuiHandlerApiculture extends GuiHandlerBase { return new GuiBeealyzer(player, new BeealyzerInventory(player, equipped)); case BeehouseGUI: - return new GuiApiary(player.inventory, (TileBeehouse) getTileForestry(world, x, y, z)); + return new GuiApiary(player.inventory, getTileForestry(world, x, y, z, player, TileBeehouse.class)); case HabitatLocatorGUI: equipped = player.getCurrentEquippedItem(); @@ -93,7 +93,7 @@ public class GuiHandlerApiculture extends GuiHandlerBase { return new GuiHabitatLocator(player, new HabitatLocatorInventory(player, equipped)); case HygroregulatorGUI: - return new GuiAlvearyHygroregulator(player.inventory, (TileAlvearyHygroregulator) getTileForestry(world, x, y, z)); + return new GuiAlvearyHygroregulator(player.inventory, getTileForestry(world, x, y, z, player, TileAlvearyHygroregulator.class)); case ImprinterGUI: equipped = player.getCurrentEquippedItem(); @@ -122,20 +122,20 @@ public class GuiHandlerApiculture extends GuiHandlerBase { case AlvearyGUI: synchApiaristTracker(world, player); - return new ContainerAlveary(player.inventory, (TileAlvearyPlain) getTileForestry(world, x, y, z)); + return new ContainerAlveary(player.inventory, getTileForestry(world, x, y, z, player, TileAlvearyPlain.class)); case AlvearySieveGUI: - return new ContainerAlvearySieve(player.inventory, (TileAlvearySieve) getTileForestry(world, x, y, z)); + return new ContainerAlvearySieve(player.inventory, getTileForestry(world, x, y, z, player, TileAlvearySieve.class)); case AlvearySwarmerGUI: - return new ContainerAlvearySwarmer(player.inventory, (TileAlvearySwarmer) getTileForestry(world, x, y, z)); + return new ContainerAlvearySwarmer(player.inventory, getTileForestry(world, x, y, z, player, TileAlvearySwarmer.class)); case ApiaristChestGUI: return getNaturalistChestContainer(BeeHelper.UID, player, world, x, y, z, guiData); case ApiaryGUI: synchApiaristTracker(world, player); - return new ContainerApiary(player.inventory, (TileApiary) getTileForestry(world, x, y, z), true); + return new ContainerApiary(player.inventory, getTileForestry(world, x, y, z, player, TileApiary.class), true); case BeealyzerGUI: equipped = player.getCurrentEquippedItem(); @@ -148,7 +148,7 @@ public class GuiHandlerApiculture extends GuiHandlerBase { case BeehouseGUI: synchApiaristTracker(world, player); - return new ContainerApiary(player.inventory, (TileBeehouse) getTileForestry(world, x, y, z), false); + return new ContainerApiary(player.inventory, getTileForestry(world, x, y, z, player, TileBeehouse.class), false); case HabitatLocatorGUI: equipped = player.getCurrentEquippedItem(); @@ -159,7 +159,7 @@ public class GuiHandlerApiculture extends GuiHandlerBase { return new ContainerHabitatLocator(player, new HabitatLocatorInventory(player, equipped)); case HygroregulatorGUI: - return new ContainerAlvearyHygroregulator(player.inventory, (TileAlvearyHygroregulator) getTileForestry(world, x, y, z)); + return new ContainerAlvearyHygroregulator(player.inventory, getTileForestry(world, x, y, z, player, TileAlvearyHygroregulator.class)); case ImprinterGUI: synchApiaristTracker(world, player); diff --git a/src/main/java/forestry/apiculture/gadgets/StructureLogicAlveary.java b/src/main/java/forestry/apiculture/gadgets/StructureLogicAlveary.java old mode 100755 new mode 100644 index 76e03640a..29a4e80ec --- a/src/main/java/forestry/apiculture/gadgets/StructureLogicAlveary.java +++ b/src/main/java/forestry/apiculture/gadgets/StructureLogicAlveary.java @@ -11,14 +11,17 @@ package forestry.apiculture.gadgets; import java.util.HashSet; +import java.util.Set; import net.minecraft.block.Block; import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.oredict.OreDictionary; + import forestry.api.apiculture.IAlvearyComponent; import forestry.api.core.ITileStructure; -import forestry.core.config.ForestryBlock; import forestry.core.gadgets.BlockStructure.EnumStructureState; import forestry.core.gadgets.StructureLogic; import forestry.core.utils.Schemata; @@ -29,18 +32,19 @@ public class StructureLogicAlveary extends StructureLogic { /* CONSTANTS */ public static final String UID_ALVEARY = "alveary"; - public static final Schemata SCHEMATA_ALVEARY = new Schemata("alveary3x3", 5, 6, 5, "FFFFF", "FFFFF", "FFFFF", "FFFFF", "FFFFF", "FFFFF", "FFFFF", "FAAAF", - "FAAAF", "FABAF", "FCCCF", "FFFFF", "FFFFF", "FAAAF", "FAAAF", "FBMBF", "FCCCF", "FFFFF", "FFFFF", "FAAAF", "FAAAF", "FABAF", "FCCCF", "FFFFF", + public static final Schemata SCHEMATA_ALVEARY = new Schemata("alveary3x3", 5, 6, 5, + "FFFFF", "FFFFF", "FFFFF", "FFFFF", "FFFFF", "FFFFF", + "FFFFF", "FAAAF", "FAAAF", "FABAF", "FCCCF", "FFFFF", + "FFFFF", "FAAAF", "FAAAF", "FBMBF", "FCCCF", "FFFFF", + "FFFFF", "FAAAF", "FAAAF", "FABAF", "FCCCF", "FFFFF", "FFFFF", "FFFFF", "FFFFF", "FFFFF", "FFFFF", "FFFFF").setOffsets(-2, -3, -2); - public static final HashSet slabBlocks = new HashSet(); + private static final Set slabBlocks = new HashSet(); + private static final Set slabOreDictIds = new HashSet(); static { - slabBlocks.add(Blocks.wooden_slab); - slabBlocks.add(ForestryBlock.slabs1.block()); - slabBlocks.add(ForestryBlock.slabs2.block()); - slabBlocks.add(ForestryBlock.slabs3.block()); - slabBlocks.add(ForestryBlock.slabs4.block()); + int slabWoodId = OreDictionary.getOreID("slabWood"); + slabOreDictIds.add(slabWoodId); } public StructureLogicAlveary(ITileStructure structure) { @@ -100,7 +104,7 @@ public class StructureLogicAlveary extends StructureLogic { } break; case BLOCK_C: - if (!slabBlocks.contains(block)) { + if (!isWoodSlabBlock(block)) { return EnumStructureState.INVALID; } if ((structureTile.getWorldObj().getBlockMetadata(x, y, z) & 8) != 0) { @@ -127,4 +131,19 @@ public class StructureLogicAlveary extends StructureLogic { return EnumStructureState.VALID; } + private static boolean isWoodSlabBlock(Block block) { + int[] oreIds = OreDictionary.getOreIDs(new ItemStack(block)); + for (int oreId : oreIds) { + if (slabOreDictIds.contains(oreId)) { + return true; + } + } + + return slabBlocks.contains(block); + } + + public static void addSlabBlock(Block block) { + slabBlocks.add(block); + } + } diff --git a/src/main/java/forestry/apiculture/gadgets/TileAlveary.java b/src/main/java/forestry/apiculture/gadgets/TileAlveary.java index 933e4f9e9..91881eb11 100755 --- a/src/main/java/forestry/apiculture/gadgets/TileAlveary.java +++ b/src/main/java/forestry/apiculture/gadgets/TileAlveary.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.apiculture.gadgets; +import java.io.IOException; import java.util.Collection; import java.util.LinkedList; @@ -31,7 +32,8 @@ import forestry.core.config.ForestryBlock; import forestry.core.gadgets.TileForestry; import forestry.core.inventory.FakeInventoryAdapter; import forestry.core.inventory.IInventoryAdapter; -import forestry.core.network.PacketPayload; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; import forestry.core.proxy.Proxies; import buildcraft.api.statements.ITriggerExternal; @@ -106,24 +108,23 @@ public abstract class TileAlveary extends TileForestry implements IAlvearyCompon } @Override - public PacketPayload getPacketPayload() { - PacketPayload payload = new PacketPayload(0, 2); - payload.shortPayload[0] = (short) (isMaster() ? 1 : 0); + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeBoolean(isMaster); // so the client can know if it is part of an integrated structure - payload.shortPayload[1] = (short) this.masterY; - - return payload; + data.writeVarInt(masterY); } @Override - public void fromPacketPayload(PacketPayload payload) { - if (payload.shortPayload[0] > 0) { + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + if (data.readBoolean()) { makeMaster(); } // so the client can know if it is part of an integrated structure - this.masterY = payload.shortPayload[1]; + masterY = data.readVarInt(); } /* ITILESTRUCTURE */ @@ -145,6 +146,10 @@ public abstract class TileAlveary extends TileForestry implements IAlvearyCompon if (getInternalInventory() instanceof FakeInventoryAdapter) { createInventory(); } + + if (worldObj != null && !worldObj.isRemote) { + setNeedsNetworkUpdate(); + } } @Override diff --git a/src/main/java/forestry/apiculture/gadgets/TileAlvearyClimatiser.java b/src/main/java/forestry/apiculture/gadgets/TileAlvearyClimatiser.java index 7af6b1e1c..acdc58178 100755 --- a/src/main/java/forestry/apiculture/gadgets/TileAlvearyClimatiser.java +++ b/src/main/java/forestry/apiculture/gadgets/TileAlvearyClimatiser.java @@ -10,17 +10,23 @@ ******************************************************************************/ package forestry.apiculture.gadgets; +import java.io.IOException; + import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; import forestry.api.apiculture.IAlvearyComponent; -import forestry.core.network.PacketPayload; +import forestry.apiculture.network.PacketActiveUpdate; +import forestry.core.interfaces.IActivatable; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.proxy.Proxies; import forestry.energy.EnergyManager; import cofh.api.energy.IEnergyHandler; -public abstract class TileAlvearyClimatiser extends TileAlveary implements IEnergyHandler { +public abstract class TileAlvearyClimatiser extends TileAlveary implements IEnergyHandler, IActivatable { public static class ClimateControl { @@ -41,6 +47,9 @@ public abstract class TileAlvearyClimatiser extends TileAlveary implements IEner private final int textureOff; private final int textureOn; + // CLIENT + private boolean active; + public TileAlvearyClimatiser(ClimateControl control, int textureOff, int textureOn, int componentBlockMeta) { super(componentBlockMeta); this.climateControl = control; @@ -59,8 +68,6 @@ public abstract class TileAlvearyClimatiser extends TileAlveary implements IEner return; } - boolean wasInactive = (workingTime == 0); - if (workingTime < 20 && energyManager.consumeEnergyToDoWork()) { // consume 10 RF per tick of work workingTime += energyManager.getEnergyPerWork() / 10; @@ -74,9 +81,7 @@ public abstract class TileAlvearyClimatiser extends TileAlveary implements IEner } } - if ((wasInactive && workingTime > 0) || (!wasInactive && workingTime == 0)) { - setNeedsNetworkUpdate(); - } + setActive(workingTime > 0); } @Override @@ -87,7 +92,7 @@ public abstract class TileAlvearyClimatiser extends TileAlveary implements IEner /* TEXTURES */ @Override public int getIcon(int side, int metadata) { - if (workingTime > 0) { + if (active) { return textureOn; } else { return textureOff; @@ -100,6 +105,7 @@ public abstract class TileAlvearyClimatiser extends TileAlveary implements IEner super.readFromNBT(nbttagcompound); energyManager.readFromNBT(nbttagcompound); workingTime = nbttagcompound.getInteger("Heating"); + setActive(workingTime > 0); } @Override @@ -109,22 +115,37 @@ public abstract class TileAlvearyClimatiser extends TileAlveary implements IEner nbttagcompound.setInteger("Heating", workingTime); } - /* NETWORK */ @Override - public void fromPacketPayload(PacketPayload payload) { - short workingTime = payload.shortPayload[0]; - if (this.workingTime != workingTime) { - this.workingTime = workingTime; - worldObj.func_147479_m(xCoord, yCoord, zCoord); - } + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeBoolean(active); } @Override - public PacketPayload getPacketPayload() { - PacketPayload payload = new PacketPayload(0, 1); - payload.shortPayload[0] = (short) workingTime; - return payload; + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + setActive(data.readBoolean()); + } + + @Override + public boolean isActive() { + return active; + } + + @Override + public void setActive(boolean active) { + if (this.active == active) { + return; + } + + this.active = active; + + if (worldObj.isRemote) { + worldObj.func_147479_m(xCoord, yCoord, zCoord); + } else { + Proxies.net.sendNetworkPacket(new PacketActiveUpdate(this)); + } } /* IEnergyHandler */ diff --git a/src/main/java/forestry/apiculture/gadgets/TileAlvearyHygroregulator.java b/src/main/java/forestry/apiculture/gadgets/TileAlvearyHygroregulator.java index 207bbc49d..3d7632994 100755 --- a/src/main/java/forestry/apiculture/gadgets/TileAlvearyHygroregulator.java +++ b/src/main/java/forestry/apiculture/gadgets/TileAlvearyHygroregulator.java @@ -127,17 +127,14 @@ public class TileAlvearyHygroregulator extends TileAlveary implements IInventory } } - if (!updateOnInterval(20)) { - return; + if (updateOnInterval(20)) { + IInventoryAdapter canInventory = getInternalInventory(); + + // Check if we have suitable items waiting in the item slot + if (canInventory.getStackInSlot(0) != null) { + FluidHelper.drainContainers(tankManager, canInventory, 0); + } } - - IInventoryAdapter canInventory = getInternalInventory(); - - // Check if we have suitable items waiting in the item slot - if (canInventory.getStackInSlot(0) != null) { - FluidHelper.drainContainers(tankManager, canInventory, 0); - } - } @Override diff --git a/src/main/java/forestry/apiculture/gadgets/TileAlvearyPlain.java b/src/main/java/forestry/apiculture/gadgets/TileAlvearyPlain.java index 485f8c692..c39597b5a 100755 --- a/src/main/java/forestry/apiculture/gadgets/TileAlvearyPlain.java +++ b/src/main/java/forestry/apiculture/gadgets/TileAlvearyPlain.java @@ -10,12 +10,12 @@ ******************************************************************************/ package forestry.apiculture.gadgets; +import java.io.IOException; import java.util.LinkedHashSet; import java.util.Set; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.ICrafting; -import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -39,27 +39,28 @@ import forestry.api.core.IErrorState; import forestry.api.core.ITileStructure; import forestry.api.genetics.IIndividual; import forestry.apiculture.gui.ContainerAlveary; +import forestry.apiculture.network.PacketActiveUpdate; import forestry.core.EnumErrorCode; import forestry.core.config.Config; +import forestry.core.interfaces.IActivatable; import forestry.core.interfaces.IClimatised; import forestry.core.interfaces.IErrorSource; import forestry.core.interfaces.IHintSource; import forestry.core.inventory.IInventoryAdapter; import forestry.core.inventory.InvTools; import forestry.core.inventory.TileInventoryAdapter; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.GuiId; -import forestry.core.network.PacketIds; -import forestry.core.network.PacketInventoryStack; import forestry.core.proxy.Proxies; -import forestry.core.utils.Utils; -public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IBeeHousing, IClimatised, IHintSource { +public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IBeeHousing, IClimatised, IHintSource, IActivatable { // / CONSTANTS public static final int SLOT_QUEEN = 0; 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 SLOT_PRODUCT_COUNT = 7; public static final int BLOCK_META = 0; // / MEMBERS @@ -67,8 +68,12 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IB protected BiomeGenBase biome; protected float tempChange = 0.0f; protected float humidChange = 0.0f; + + // CLIENT + private boolean active; private int displayHealthMax = 0; private int displayHealth = 0; + private IBee displayQueen; public TileAlvearyPlain() { super(0); @@ -90,7 +95,7 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IB } private void setBiomeInformation() { - this.biome = Utils.getBiomeAt(worldObj, xCoord, zCoord); + this.biome = worldObj.getBiomeGenForCoordsBody(xCoord, zCoord); } /* LOADING & SAVING */ @@ -118,6 +123,43 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IB } } + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeBoolean(active); + if (active) { + ItemStack queen = getStackInSlot(SLOT_QUEEN); + data.writeItemStack(queen); + } + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + active = data.readBoolean(); + if (active) { + ItemStack queen = data.readItemStack(); + setInventorySlotContents(SLOT_QUEEN, queen); + } + } + + @Override + public boolean isActive() { + return active; + } + + @Override + public void setActive(boolean active) { + if (this.active == active) { + return; + } + this.active = active; + + if (!worldObj.isRemote) { + Proxies.net.sendNetworkPacket(new PacketActiveUpdate(this)); + } + } + /* UPDATING */ @Override public void initialize() { @@ -136,65 +178,33 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IB return; } - beekeepingLogic.update(); + boolean canWork = beekeepingLogic.canWork(); + setActive(canWork); + if (canWork) { + beekeepingLogic.doWork(); + } // Equalize humidity and temperature equalizeTemperature(); equalizeHumidity(); - - IBee queen = beekeepingLogic.getQueen(); - if (queen == null) { - return; - } - - // Add swarm effects - if (updateOnInterval(200)) { - ISidedInventory inventory = getStructureInventory(); - if (inventory != null) { - onQueenChange(inventory.getStackInSlot(SLOT_QUEEN)); - } - } - - if (!hasErrorState()) { - queen.doFX(beekeepingLogic.getEffectData(), this); - - if (updateOnInterval(50)) { - float f = xCoord + 0.5F; - float f1 = yCoord + 0.0F + (worldObj.rand.nextFloat() * 6F) / 16F; - float f2 = zCoord + 0.5F; - float f3 = 0.52F; - float f4 = worldObj.rand.nextFloat() * 0.6F - 0.3F; - - Proxies.common.addEntitySwarmFX(worldObj, (f - f3), f1, (f2 + f4), 0F, 0F, 0F); - Proxies.common.addEntitySwarmFX(worldObj, (f + f3), f1, (f2 + f4), 0F, 0F, 0F); - Proxies.common.addEntitySwarmFX(worldObj, (f + f4), f1, (f2 - f3), 0F, 0F, 0F); - Proxies.common.addEntitySwarmFX(worldObj, (f + f4), f1, (f2 + f3), 0F, 0F, 0F); - } - } } @Override protected void updateClientSide() { + if (isMaster() && active && (displayQueen != null) && updateOnInterval(2)) { + displayQueen.doFX(beekeepingLogic.getEffectData(), this); - if (!isMaster()) { - return; - } + if (updateOnInterval(50)) { + float fxX = xCoord + 0.5F; + float fxY = yCoord + 0.25F + (worldObj.rand.nextFloat() * 6F) / 16F; + float fxZ = zCoord + 0.5F; + float f3 = 1.6F; + float f4 = worldObj.rand.nextFloat() * f3 - 0.5F; - if (hasErrorState()) { - return; - } - - if (updateOnInterval(2)) { - ISidedInventory inventory = getStructureInventory(); - if (inventory == null) { - return; - } - - // / Multiplayer FX - ItemStack queenStack = inventory.getStackInSlot(SLOT_QUEEN); - if (BeeManager.beeRoot.isMated(queenStack)) { - IBee displayQueen = BeeManager.beeRoot.getMember(queenStack); - displayQueen.doFX(beekeepingLogic.getEffectData(), this); + Proxies.common.addEntitySwarmFX(worldObj, (fxX - f3), fxY, (fxZ + f4), 0F, 0F, 0F); + Proxies.common.addEntitySwarmFX(worldObj, (fxX + f3), fxY, (fxZ + f4), 0F, 0F, 0F); + Proxies.common.addEntitySwarmFX(worldObj, (fxX + f4), fxY, (fxZ - f3), 0F, 0F, 0F); + Proxies.common.addEntitySwarmFX(worldObj, (fxX + f4), fxY, (fxZ + f3), 0F, 0F, 0F); } } } @@ -223,32 +233,26 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IB /* STATE INFORMATION */ private int getHealthDisplay() { - IInventory inventory = getStructureInventory(); - if (inventory == null || inventory.getStackInSlot(SLOT_QUEEN) == null) { + if (displayQueen == null) { return 0; } - if (BeeManager.beeRoot.isMated(inventory.getStackInSlot(SLOT_QUEEN))) { - return BeeManager.beeRoot.getMember(inventory.getStackInSlot(SLOT_QUEEN)).getHealth(); - } else if (!BeeManager.beeRoot.isDrone(inventory.getStackInSlot(SLOT_QUEEN))) { - return displayHealth; + if (displayQueen.getMate() != null) { + return displayQueen.getHealth(); } else { - return 0; + return displayHealth; } } private int getMaxHealthDisplay() { - IInventory inventory = getStructureInventory(); - if (inventory == null || inventory.getStackInSlot(SLOT_QUEEN) == null) { + if (displayQueen == null) { return 0; } - if (BeeManager.beeRoot.isMated(inventory.getStackInSlot(SLOT_QUEEN))) { - return BeeManager.beeRoot.getMember(inventory.getStackInSlot(SLOT_QUEEN)).getMaxHealth(); - } else if (!BeeManager.beeRoot.isDrone(inventory.getStackInSlot(SLOT_QUEEN))) { - return displayHealthMax; + if (displayQueen.getMate() != null) { + return displayQueen.getMaxHealth(); } else { - return 0; + return displayHealthMax; } } @@ -279,6 +283,8 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IB super.onStructureReset(); modifiers.clear(); eventHandlers.clear(); + + setActive(false); } /* IALVEARYCOMPONENT */ @@ -307,7 +313,7 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IB @Override public void addTemperatureChange(float change, float boundaryDown, float boundaryUp) { - float temperature = biome.temperature; + float temperature = biome.getFloatTemperature(xCoord, yCoord, zCoord); tempChange = Math.min(boundaryUp - temperature, Math.max(boundaryDown - temperature, tempChange + change)); } @@ -348,6 +354,33 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IB setInventorySlotContents(SLOT_QUEEN, itemstack); } + @Override + public ItemStack decrStackSize(int slotIndex, int amount) { + ItemStack itemStack = super.decrStackSize(slotIndex, amount); + if (slotIndex == SLOT_QUEEN) { + handleQueenChange(); + } + return itemStack; + } + + @Override + public void setInventorySlotContents(int slotIndex, ItemStack itemStack) { + super.setInventorySlotContents(slotIndex, itemStack); + if (slotIndex == SLOT_QUEEN) { + handleQueenChange(); + } + } + + private void handleQueenChange() { + if (!Proxies.common.isSimulating(worldObj)) { + TileAlvearyPlain master = (TileAlvearyPlain) getCentralTE(); + if (master != null) { + ItemStack itemStack = getStackInSlot(SLOT_QUEEN); + master.displayQueen = BeeManager.beeRoot.getMember(itemStack); + } + } + } + @Override public void setDrone(ItemStack itemstack) { setInventorySlotContents(SLOT_DRONE, itemstack); @@ -360,7 +393,7 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IB @Override public EnumTemperature getTemperature() { - if (BiomeHelper.isBiomeHellish(biome) && tempChange >= 0) { + if (isHellish() && tempChange >= 0) { return EnumTemperature.HELLISH; } @@ -443,7 +476,7 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IB return false; } - return InvTools.tryAddStack(inventory, product, SLOT_PRODUCT_1, inventory.getSizeInventory() - SLOT_PRODUCT_1, all); + return InvTools.tryAddStack(inventory, product, SLOT_PRODUCT_1, SLOT_PRODUCT_COUNT, all); } @Deprecated @@ -468,9 +501,6 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IB return; } - Proxies.net.sendNetworkPacket(new PacketInventoryStack(PacketIds.IINVENTORY_STACK, xCoord, yCoord, zCoord, SLOT_QUEEN, queenStack), xCoord, yCoord, - zCoord); - for (IBeeListener eventHandler : eventHandlers) { eventHandler.onQueenChange(queenStack); } @@ -545,6 +575,10 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IB @Override public boolean isHellish() { + if (BiomeHelper.isBiomeHellish(biome)) { + return true; + } + for (IBeeModifier modifier : modifiers) { if (modifier.isHellish()) { return true; @@ -634,7 +668,7 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IB @Override public float getExactTemperature() { - return biome.temperature + this.tempChange; + return biome.getFloatTemperature(xCoord, yCoord, zCoord) + this.tempChange; } @Override @@ -653,16 +687,10 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IB return Config.hints.get("alveary"); } - /* IOWNABLE */ - @Override - public boolean isOwnable() { - return true; - } - /* IHousing */ @Override public GameProfile getOwnerName() { - return this.getOwnerProfile(); + return this.getOwner(); } private static class AlvearyInventoryAdapter extends TileInventoryAdapter { diff --git a/src/main/java/forestry/apiculture/gadgets/TileAlvearySwarmer.java b/src/main/java/forestry/apiculture/gadgets/TileAlvearySwarmer.java index 53f6b7adb..9ae809e2d 100755 --- a/src/main/java/forestry/apiculture/gadgets/TileAlvearySwarmer.java +++ b/src/main/java/forestry/apiculture/gadgets/TileAlvearySwarmer.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.apiculture.gadgets; +import java.io.IOException; import java.util.Map.Entry; import java.util.Stack; @@ -25,23 +26,27 @@ import forestry.api.apiculture.IAlvearyComponent; import forestry.api.apiculture.IBee; import forestry.api.apiculture.IBeeHousing; import forestry.api.core.ForestryAPI; +import forestry.apiculture.network.PacketActiveUpdate; import forestry.apiculture.worldgen.Hive; import forestry.apiculture.worldgen.HiveDecorator; import forestry.apiculture.worldgen.HiveDescriptionSwarmer; +import forestry.core.interfaces.IActivatable; import forestry.core.inventory.TileInventoryAdapter; import forestry.core.inventory.wrappers.IInvSlot; import forestry.core.inventory.wrappers.InventoryIterator; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.GuiId; -import forestry.core.network.PacketPayload; +import forestry.core.proxy.Proxies; import forestry.core.utils.StackUtils; -public class TileAlvearySwarmer extends TileAlveary implements ISidedInventory { +public class TileAlvearySwarmer extends TileAlveary implements ISidedInventory, IActivatable { /* CONSTANTS */ public static final int BLOCK_META = 2; private final Stack pendingSpawns = new Stack(); - private boolean isActive; + private boolean active; public TileAlvearySwarmer() { super(BLOCK_META); @@ -59,12 +64,12 @@ public class TileAlvearySwarmer extends TileAlveary implements ISidedInventory { super.updateServerSide(); if (pendingSpawns.size() > 0) { - setIsActive(true); + setActive(true); if (updateOnInterval(1000)) { trySpawnSwarm(); } } else { - setIsActive(false); + setActive(false); } if (!updateOnInterval(500)) { @@ -143,30 +148,24 @@ public class TileAlvearySwarmer extends TileAlveary implements ISidedInventory { } } - private void setIsActive(boolean isActive) { - if (this.isActive != isActive) { - this.isActive = isActive; - setNeedsNetworkUpdate(); - } + /* NETWORK */ + + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeBoolean(active); } - /* NETWORK */ @Override - public void fromPacketPayload(PacketPayload payload) { - boolean act = payload.shortPayload[0] > 0; - if (this.isActive != act) { - this.isActive = act; + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + boolean active = data.readBoolean(); + if (this.active != active) { + this.active = active; worldObj.func_147479_m(xCoord, yCoord, zCoord); } } - @Override - public PacketPayload getPacketPayload() { - PacketPayload payload = new PacketPayload(0, 1); - payload.shortPayload[0] = (short) (isActive ? 1 : 0); - return payload; - } - @Override public boolean hasFunction() { return true; @@ -179,7 +178,7 @@ public class TileAlvearySwarmer extends TileAlveary implements ISidedInventory { return BlockAlveary.BOTTOM; } - if (isActive) { + if (active) { return BlockAlveary.ALVEARY_SWARMER_ON; } else { return BlockAlveary.ALVEARY_SWARMER_OFF; @@ -217,6 +216,24 @@ public class TileAlvearySwarmer extends TileAlveary implements ISidedInventory { } + @Override + public boolean isActive() { + return active; + } + + @Override + public void setActive(boolean active) { + if (this.active == active) { + return; + } + + this.active = active; + + if (!worldObj.isRemote) { + Proxies.net.sendNetworkPacket(new PacketActiveUpdate(this)); + } + } + private static class SwarmerInventoryAdapter extends TileInventoryAdapter { public SwarmerInventoryAdapter(TileAlvearySwarmer alvearySwarmer) { super(alvearySwarmer, 4, "SwarmInv"); diff --git a/src/main/java/forestry/apiculture/gadgets/TileBeehouse.java b/src/main/java/forestry/apiculture/gadgets/TileBeehouse.java index ba1f95fd1..a864f50e9 100755 --- a/src/main/java/forestry/apiculture/gadgets/TileBeehouse.java +++ b/src/main/java/forestry/apiculture/gadgets/TileBeehouse.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.apiculture.gadgets; +import java.io.IOException; import java.util.Set; import net.minecraft.entity.player.EntityPlayer; @@ -33,24 +34,21 @@ import forestry.api.core.EnumTemperature; import forestry.api.core.ForestryAPI; import forestry.api.core.IErrorState; import forestry.api.genetics.IIndividual; +import forestry.apiculture.network.PacketActiveUpdate; import forestry.core.EnumErrorCode; import forestry.core.config.Config; -import forestry.core.config.ForestryItem; import forestry.core.gadgets.TileBase; -import forestry.core.gadgets.TileForestry; +import forestry.core.interfaces.IActivatable; import forestry.core.interfaces.IClimatised; -import forestry.core.inventory.IInventoryAdapter; import forestry.core.inventory.InvTools; import forestry.core.inventory.TileInventoryAdapter; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.GuiId; -import forestry.core.network.PacketIds; -import forestry.core.network.PacketInventoryStack; -import forestry.core.network.PacketTileUpdate; import forestry.core.proxy.Proxies; import forestry.core.utils.GuiUtil; -import forestry.core.utils.Utils; -public class TileBeehouse extends TileBase implements IBeeHousing, IClimatised { +public class TileBeehouse extends TileBase implements IBeeHousing, IClimatised, IActivatable { // CONSTANTS public static final int SLOT_QUEEN = 0; public static final int SLOT_DRONE = 1; @@ -58,10 +56,15 @@ public class TileBeehouse extends TileBase implements IBeeHousing, IClimatised { public static final int SLOT_PRODUCT_COUNT = 7; public static final int SLOT_FRAMES_1 = 9; public static final int SLOT_FRAMES_COUNT = 3; + private final IBeekeepingLogic logic; private BiomeGenBase biome; + + // CLIENT + private boolean active; private int displayHealthMax = 0; private int displayHealth = 0; + private IBee displayQueen; public TileBeehouse() { setHints(Config.hints.get("apiary")); @@ -92,7 +95,26 @@ public class TileBeehouse extends TileBase implements IBeeHousing, IClimatised { int biomeId = nbttagcompound.getInteger("BiomeId"); biome = BiomeGenBase.getBiome(biomeId); logic.readFromNBT(nbttagcompound); + } + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeBoolean(active); + if (active) { + ItemStack queen = getStackInSlot(SLOT_QUEEN); + data.writeItemStack(queen); + } + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + active = data.readBoolean(); + if (active) { + ItemStack queen = data.readItemStack(); + setInventorySlotContents(SLOT_QUEEN, queen); + } } @Override @@ -114,7 +136,7 @@ public class TileBeehouse extends TileBase implements IBeeHousing, IClimatised { @Override public EnumTemperature getTemperature() { - return EnumTemperature.getFromBiome(biome); + return EnumTemperature.getFromBiome(biome, xCoord, yCoord, zCoord); } @Override @@ -144,7 +166,7 @@ public class TileBeehouse extends TileBase implements IBeeHousing, IClimatised { @Override public float getExactTemperature() { - return biome.temperature; + return biome.getFloatTemperature(xCoord, yCoord, zCoord); } @Override @@ -155,30 +177,30 @@ public class TileBeehouse extends TileBase implements IBeeHousing, IClimatised { /* UPDATING */ @Override public void updateClientSide() { + if (isActive() && (displayQueen != null) && updateOnInterval(4)) { + displayQueen.doFX(logic.getEffectData(), this); - // / Multiplayer FX - if (BeeManager.beeRoot.isMated(getInternalInventory().getStackInSlot(SLOT_QUEEN))) { - if (!hasErrorState() && updateOnInterval(2)) { - IBee displayQueen = BeeManager.beeRoot.getMember(getInternalInventory().getStackInSlot(SLOT_QUEEN)); - displayQueen.doFX(logic.getEffectData(), this); + if (updateOnInterval(50)) { + float fxX = xCoord + 0.5F; + float fxY = yCoord + 0.25F + (worldObj.rand.nextFloat() * 6F) / 16F; + float fxZ = zCoord + 0.5F; + float f3 = 0.6F; + float f4 = worldObj.rand.nextFloat() * f3 - 0.5F; + + Proxies.common.addEntitySwarmFX(worldObj, (fxX - f3), fxY, (fxZ + f4), 0F, 0F, 0F); + Proxies.common.addEntitySwarmFX(worldObj, (fxX + f3), fxY, (fxZ + f4), 0F, 0F, 0F); + Proxies.common.addEntitySwarmFX(worldObj, (fxX + f4), fxY, (fxZ - f3), 0F, 0F, 0F); + Proxies.common.addEntitySwarmFX(worldObj, (fxX + f4), fxY, (fxZ + f3), 0F, 0F, 0F); } } - } @Override public void updateServerSide() { - - logic.update(); - - IBee queen = logic.getQueen(); - if (queen == null) { - return; - } - - // Add swarm effects - if (updateOnInterval(200)) { - onQueenChange(getInternalInventory().getStackInSlot(SLOT_QUEEN)); + boolean canWork = logic.canWork(); + setActive(canWork); + if (canWork) { + logic.doWork(); } } @@ -195,43 +217,30 @@ public class TileBeehouse extends TileBase implements IBeeHousing, IClimatised { /* NETWORK SYNCH */ @Override public void onQueenChange(ItemStack queenStack) { - if (!Proxies.common.isSimulating(worldObj)) { - return; - } - - Proxies.net.sendNetworkPacket(new PacketInventoryStack(PacketIds.IINVENTORY_STACK, xCoord, yCoord, zCoord, SLOT_QUEEN, queenStack), xCoord, yCoord, - zCoord); - Proxies.net.sendNetworkPacket(new PacketTileUpdate(this), xCoord, yCoord, zCoord); } /* STATE INFORMATION */ private int getHealthDisplay() { - IInventoryAdapter inventory = getInternalInventory(); - if (inventory.getStackInSlot(SLOT_QUEEN) == null) { + if (displayQueen == null) { return 0; } - if (ForestryItem.beeQueenGE.isItemEqual(inventory.getStackInSlot(SLOT_QUEEN))) { - return BeeManager.beeRoot.getMember(inventory.getStackInSlot(SLOT_QUEEN)).getHealth(); - } else if (ForestryItem.beePrincessGE.isItemEqual(inventory.getStackInSlot(SLOT_QUEEN))) { - return displayHealth; + if (displayQueen.getMate() != null) { + return displayQueen.getHealth(); } else { - return 0; + return displayHealth; } } private int getMaxHealthDisplay() { - IInventoryAdapter inventory = getInternalInventory(); - if (inventory.getStackInSlot(SLOT_QUEEN) == null) { + if (displayQueen == null) { return 0; } - if (ForestryItem.beeQueenGE.isItemEqual(inventory.getStackInSlot(SLOT_QUEEN))) { - return BeeManager.beeRoot.getMember(inventory.getStackInSlot(SLOT_QUEEN)).getMaxHealth(); - } else if (ForestryItem.beePrincessGE.isItemEqual(inventory.getStackInSlot(SLOT_QUEEN))) { - return displayHealthMax; + if (displayQueen.getMate() != null) { + return displayQueen.getMaxHealth(); } else { - return 0; + return displayHealthMax; } } @@ -248,7 +257,7 @@ public class TileBeehouse extends TileBase implements IBeeHousing, IClimatised { public void updateBiome() { if (worldObj != null) { - BiomeGenBase biome = Utils.getBiomeAt(worldObj, xCoord, zCoord); + BiomeGenBase biome = worldObj.getBiomeGenForCoordsBody(xCoord, zCoord); if (biome != null) { this.biome = biome; } @@ -318,6 +327,30 @@ public class TileBeehouse extends TileBase implements IBeeHousing, IClimatised { setInventorySlotContents(SLOT_QUEEN, itemstack); } + @Override + public ItemStack decrStackSize(int slotIndex, int amount) { + ItemStack itemStack = super.decrStackSize(slotIndex, amount); + if (slotIndex == SLOT_QUEEN) { + handleQueenChange(); + } + return itemStack; + } + + @Override + public void setInventorySlotContents(int slotIndex, ItemStack itemStack) { + super.setInventorySlotContents(slotIndex, itemStack); + if (slotIndex == SLOT_QUEEN) { + handleQueenChange(); + } + } + + private void handleQueenChange() { + if (!Proxies.common.isSimulating(worldObj)) { + ItemStack itemStack = getStackInSlot(SLOT_QUEEN); + displayQueen = BeeManager.beeRoot.getMember(itemStack); + } + } + @Override public void setDrone(ItemStack itemstack) { setInventorySlotContents(SLOT_DRONE, itemstack); @@ -408,7 +441,24 @@ public class TileBeehouse extends TileBase implements IBeeHousing, IClimatised { /* IHousing */ @Override public GameProfile getOwnerName() { - return this.getOwnerProfile(); + return this.getOwner(); + } + + @Override + public boolean isActive() { + return active; + } + + @Override + public void setActive(boolean active) { + if (this.active == active) { + return; + } + this.active = active; + + if (!worldObj.isRemote) { + Proxies.net.sendNetworkPacket(new PacketActiveUpdate(this)); + } } protected static class BeehouseInventoryAdapter extends TileInventoryAdapter { diff --git a/src/main/java/forestry/apiculture/genetics/AlleleEffectGlacial.java b/src/main/java/forestry/apiculture/genetics/AlleleEffectGlacial.java index be4d91384..2430c3e7f 100755 --- a/src/main/java/forestry/apiculture/genetics/AlleleEffectGlacial.java +++ b/src/main/java/forestry/apiculture/genetics/AlleleEffectGlacial.java @@ -37,8 +37,7 @@ public class AlleleEffectGlacial extends AlleleEffectThrottled { return storedData; } - BiomeGenBase biome = housing.getBiome(); - EnumTemperature temp = EnumTemperature.getFromBiome(biome); + EnumTemperature temp = housing.getTemperature(); switch (temp) { case HELLISH: diff --git a/src/main/java/forestry/apiculture/genetics/AlleleEffectSnowing.java b/src/main/java/forestry/apiculture/genetics/AlleleEffectSnowing.java index 3a4d5712f..224cd9a90 100755 --- a/src/main/java/forestry/apiculture/genetics/AlleleEffectSnowing.java +++ b/src/main/java/forestry/apiculture/genetics/AlleleEffectSnowing.java @@ -38,8 +38,7 @@ public class AlleleEffectSnowing extends AlleleEffectThrottled { return storedData; } - BiomeGenBase biome = housing.getBiome(); - EnumTemperature temp = EnumTemperature.getFromBiome(biome); + EnumTemperature temp = housing.getTemperature(); switch (temp) { case HELLISH: diff --git a/src/main/java/forestry/apiculture/genetics/Bee.java b/src/main/java/forestry/apiculture/genetics/Bee.java index 6e95641a2..88fa4e56b 100644 --- a/src/main/java/forestry/apiculture/genetics/Bee.java +++ b/src/main/java/forestry/apiculture/genetics/Bee.java @@ -10,9 +10,8 @@ ******************************************************************************/ package forestry.apiculture.genetics; -import com.google.common.collect.ImmutableSet; - import java.util.ArrayList; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; @@ -246,7 +245,7 @@ public class Bee extends IndividualLiving implements IBee { World world = housing.getWorld(); BiomeGenBase biome = housing.getBiome(); - ImmutableSet.Builder errorStates = ImmutableSet.builder(); + Set errorStates = new HashSet(); // / Rain needs tolerant flyers if (world.isRaining() && !genome.getTolerantFlyer() && BiomeHelper.canRainOrSnow(biome) && !housing.isSealed()) { @@ -281,7 +280,7 @@ public class Bee extends IndividualLiving implements IBee { errorStates.add(EnumErrorCode.INVALIDBIOME); } - return errorStates.build(); + return errorStates; } @Override @@ -467,10 +466,6 @@ public class Bee extends IndividualLiving implements IBee { @Override public ItemStack[] produceStacks(IBeeHousing housing) { - if (!hasFlower(housing)) { - return null; - } - if (housing == null) { Proxies.log.warning("Failed to produce in an apiary because the beehousing was null."); return null; @@ -481,7 +476,7 @@ public class Bee extends IndividualLiving implements IBee { return null; } - ArrayList products = new ArrayList(); + List products = new ArrayList(); IAlleleBeeSpecies primary = genome.getPrimary(); IAlleleBeeSpecies secondary = genome.getSecondary(); @@ -507,20 +502,17 @@ public class Bee extends IndividualLiving implements IBee { } } - // We are done if the we are not jubilant. - if (!primary.isJubilant(genome, housing) || !secondary.isJubilant(genome, housing)) { - return products.toArray(new ItemStack[products.size()]); - } - // / Specialty products - for (Map.Entry entry : primary.getSpecialty().entrySet()) { - if (housing.getWorld().rand.nextInt(100) < entry.getValue() * speed) { - products.add(entry.getKey().copy()); + if (primary.isJubilant(genome, housing) && secondary.isJubilant(genome, housing)) { + for (Map.Entry entry : primary.getSpecialty().entrySet()) { + if (housing.getWorld().rand.nextInt(100) < entry.getValue() * speed) { + products.add(entry.getKey().copy()); + } } } - return genome.getFlowerProvider().affectProducts(housing.getWorld(), this, housing.getXCoord(), housing.getYCoord(), housing.getZCoord(), - products.toArray(new ItemStack[products.size()])); + ItemStack[] productsArray = products.toArray(new ItemStack[products.size()]); + return genome.getFlowerProvider().affectProducts(housing.getWorld(), this, housing.getXCoord(), housing.getYCoord(), housing.getZCoord(), productsArray); } /* REPRODUCTION */ diff --git a/src/main/java/forestry/apiculture/genetics/BeeGenome.java b/src/main/java/forestry/apiculture/genetics/BeeGenome.java index b0ab98f36..c4b61e455 100755 --- a/src/main/java/forestry/apiculture/genetics/BeeGenome.java +++ b/src/main/java/forestry/apiculture/genetics/BeeGenome.java @@ -12,19 +12,24 @@ package forestry.apiculture.genetics; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeChromosome; import forestry.api.apiculture.IAlleleBeeEffect; import forestry.api.apiculture.IAlleleBeeSpecies; import forestry.api.apiculture.IBeeGenome; +import forestry.api.genetics.AlleleManager; import forestry.api.genetics.EnumTolerance; +import forestry.api.genetics.IAllele; import forestry.api.genetics.IAlleleFloat; import forestry.api.genetics.IAlleleFlowers; import forestry.api.genetics.IAlleleInteger; +import forestry.api.genetics.IAlleleSpecies; import forestry.api.genetics.IChromosome; import forestry.api.genetics.IFlowerProvider; import forestry.api.genetics.ISpeciesRoot; +import forestry.core.genetics.Chromosome; import forestry.core.genetics.Genome; import forestry.core.genetics.alleles.AlleleArea; import forestry.core.genetics.alleles.AlleleBoolean; @@ -72,6 +77,11 @@ public class BeeGenome extends Genome implements IBeeGenome { // NBT RETRIEVAL public static IAlleleBeeSpecies getSpecies(ItemStack itemStack) { + IAlleleSpecies species = getSpeciesDirectly(itemStack); + if (species instanceof IAlleleBeeSpecies) { + return (IAlleleBeeSpecies) species; + } + return (IAlleleBeeSpecies) getActiveAllele(itemStack, EnumBeeChromosome.SPECIES, BeeManager.beeRoot); } diff --git a/src/main/java/forestry/apiculture/genetics/BeeHelper.java b/src/main/java/forestry/apiculture/genetics/BeeHelper.java index 3db802983..43ca7cdd7 100755 --- a/src/main/java/forestry/apiculture/genetics/BeeHelper.java +++ b/src/main/java/forestry/apiculture/genetics/BeeHelper.java @@ -157,8 +157,8 @@ public class BeeHelper extends SpeciesRoot implements IBeeRoot { return false; } - IBee bee = getMember(stack); - return bee.getMate() != null; + NBTTagCompound nbt = stack.getTagCompound(); + return nbt != null && nbt.hasKey("Mate"); } @Override diff --git a/src/main/java/forestry/apiculture/genetics/JubilanceDefault.java b/src/main/java/forestry/apiculture/genetics/JubilanceDefault.java index 1d7f44b03..fced9cdaa 100755 --- a/src/main/java/forestry/apiculture/genetics/JubilanceDefault.java +++ b/src/main/java/forestry/apiculture/genetics/JubilanceDefault.java @@ -10,16 +10,12 @@ ******************************************************************************/ package forestry.apiculture.genetics; -import net.minecraft.util.AxisAlignedBB; -import net.minecraft.world.biome.BiomeGenBase; - import forestry.api.apiculture.IAlleleBeeSpecies; import forestry.api.apiculture.IBeeGenome; import forestry.api.apiculture.IBeeHousing; import forestry.api.apiculture.IJubilanceProvider; import forestry.api.core.EnumHumidity; import forestry.api.core.EnumTemperature; -import forestry.core.vect.Vect; public class JubilanceDefault implements IJubilanceProvider { @@ -38,24 +34,10 @@ public class JubilanceDefault implements IJubilanceProvider { @Override public boolean isJubilant(IAlleleBeeSpecies species, IBeeGenome genome, IBeeHousing housing) { - BiomeGenBase biome = housing.getBiome(); - - EnumTemperature temperature = EnumTemperature.getFromBiome(biome); - EnumHumidity humidity = EnumHumidity.getFromValue(biome.rainfall); + EnumTemperature temperature = housing.getTemperature(); + EnumHumidity humidity = housing.getHumidity(); return temperature == species.getTemperature() && humidity == species.getHumidity(); - - } - - protected static AxisAlignedBB getBounding(IBeeGenome genome, IBeeHousing housing, float modifier) { - int[] areaAr = genome.getTerritory(); - Vect area = new Vect(areaAr[0], areaAr[1], areaAr[2]).multiply(modifier); - Vect offset = new Vect(-Math.round(area.x / 2), -Math.round(area.y / 2), -Math.round(area.z / 2)); - - Vect min = new Vect(housing.getXCoord() + offset.x, housing.getYCoord() + offset.y, housing.getZCoord() + offset.z); - Vect max = new Vect(housing.getXCoord() + offset.x + area.x, housing.getYCoord() + offset.y + area.y, housing.getZCoord() + offset.z + area.z); - - return AxisAlignedBB.getBoundingBox(min.x, min.y, min.z, max.x, max.y, max.z); } } diff --git a/src/main/java/forestry/apiculture/genetics/JubilanceProviderHermit.java b/src/main/java/forestry/apiculture/genetics/JubilanceProviderHermit.java index 0e7770fe9..e0b80efdf 100755 --- a/src/main/java/forestry/apiculture/genetics/JubilanceProviderHermit.java +++ b/src/main/java/forestry/apiculture/genetics/JubilanceProviderHermit.java @@ -18,6 +18,7 @@ import net.minecraft.util.AxisAlignedBB; import forestry.api.apiculture.IAlleleBeeSpecies; import forestry.api.apiculture.IBeeGenome; import forestry.api.apiculture.IBeeHousing; +import forestry.core.vect.Vect; /** * Hermits will not produce if there are any other living creatures nearby. @@ -33,4 +34,15 @@ public class JubilanceProviderHermit extends JubilanceDefault { return list.size() <= 0; } + private static AxisAlignedBB getBounding(IBeeGenome genome, IBeeHousing housing, float modifier) { + int[] areaAr = genome.getTerritory(); + Vect area = new Vect(areaAr[0], areaAr[1], areaAr[2]).multiply(modifier); + Vect offset = new Vect(-Math.round(area.x / 2), -Math.round(area.y / 2), -Math.round(area.z / 2)); + + Vect min = new Vect(housing.getXCoord() + offset.x, housing.getYCoord() + offset.y, housing.getZCoord() + offset.z); + Vect max = new Vect(housing.getXCoord() + offset.x + area.x, housing.getYCoord() + offset.y + area.y, housing.getZCoord() + offset.z + area.z); + + return AxisAlignedBB.getBoundingBox(min.x, min.y, min.z, max.x, max.y, max.z); + } + } diff --git a/src/main/java/forestry/apiculture/gui/ContainerAlveary.java b/src/main/java/forestry/apiculture/gui/ContainerAlveary.java index bbf4e6a2e..6f35b3a98 100755 --- a/src/main/java/forestry/apiculture/gui/ContainerAlveary.java +++ b/src/main/java/forestry/apiculture/gui/ContainerAlveary.java @@ -23,8 +23,6 @@ public class ContainerAlveary extends ContainerTile { public ContainerAlveary(InventoryPlayer player, TileAlvearyPlain tile) { super(tile, player, 8, 108); - tile.sendNetworkUpdate(); - // Queen/Princess this.addSlotToContainer(new SlotFiltered(tile, TileAlvearyPlain.SLOT_QUEEN, 29, 39)); diff --git a/src/main/java/forestry/apiculture/gui/ContainerApiary.java b/src/main/java/forestry/apiculture/gui/ContainerApiary.java index 8c0cdcb31..637b37293 100755 --- a/src/main/java/forestry/apiculture/gui/ContainerApiary.java +++ b/src/main/java/forestry/apiculture/gui/ContainerApiary.java @@ -23,8 +23,6 @@ public class ContainerApiary extends ContainerTile { public ContainerApiary(InventoryPlayer player, TileBeehouse tile, boolean hasFrames) { super(tile, player, 8, 108); - tile.sendNetworkUpdate(); - // Queen/Princess this.addSlotToContainer(new SlotFiltered(tile, TileBeehouse.SLOT_QUEEN, 29, 39)); diff --git a/src/main/java/forestry/apiculture/gui/ContainerImprinter.java b/src/main/java/forestry/apiculture/gui/ContainerImprinter.java index 624514c41..bb6ec36b6 100755 --- a/src/main/java/forestry/apiculture/gui/ContainerImprinter.java +++ b/src/main/java/forestry/apiculture/gui/ContainerImprinter.java @@ -20,9 +20,9 @@ import forestry.core.gui.ContainerItemInventory; import forestry.core.gui.IGuiSelectable; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotOutput; -import forestry.core.network.PacketIds; -import forestry.core.network.PacketPayload; -import forestry.core.network.PacketUpdate; +import forestry.core.network.ForestryPacket; +import forestry.core.network.PacketGuiSelect; +import forestry.core.network.PacketId; import forestry.core.proxy.Proxies; public class ContainerImprinter extends ContainerItemInventory implements IGuiSelectable { @@ -57,50 +57,36 @@ public class ContainerImprinter extends ContainerItemInventory { + private final HabitatSlot[] habitatSlots = new HabitatSlot[]{ + new HabitatSlot(0, "Ocean"), // ocean, beach + new HabitatSlot(1, "Plains"), + new HabitatSlot(2, "Desert"), // desert, desert hills + new HabitatSlot(3, "Forest"), // forest, forestHills, river + new HabitatSlot(4, "Jungle"), // jungle, jungleHills + new HabitatSlot(5, "Taiga"), // taiga, taigaHills + new HabitatSlot(6, "Hills"), // extremeHills, extremeHillsEdge + new HabitatSlot(7, "Swamp"), + new HabitatSlot(8, "Snow"), // Ice plains, mountains, frozen rivers, frozen oceans + new HabitatSlot(9, "Mushroom"), + new HabitatSlot(10, "Nether"), + new HabitatSlot(11, "End")}; + private final Map biomeToHabitat = new EnumMap(BiomeDictionary.Type.class); + + private int startX; + private int startY; + + public GuiHabitatLocator(EntityPlayer player, HabitatLocatorInventory item) { + super(Defaults.TEXTURE_PATH_GUI + "/biomefinder.png", new ContainerHabitatLocator(player, item), item); + + xSize = 176; + ySize = 184; + + int x; + int y; + for (HabitatSlot slot : habitatSlots) { + + if (slot.slot > 5) { + x = 18 + (slot.slot - 6) * 20; + y = 50; + } else { + x = 18 + slot.slot * 20; + y = 32; + } + + slot.setPosition(x, y); + this.widgetManager.add(slot); + } + + biomeToHabitat.put(BiomeDictionary.Type.OCEAN, habitatSlots[0]); + biomeToHabitat.put(BiomeDictionary.Type.BEACH, habitatSlots[0]); + biomeToHabitat.put(BiomeDictionary.Type.PLAINS, habitatSlots[1]); + biomeToHabitat.put(BiomeDictionary.Type.SANDY, habitatSlots[2]); + biomeToHabitat.put(BiomeDictionary.Type.FOREST, habitatSlots[3]); + biomeToHabitat.put(BiomeDictionary.Type.RIVER, habitatSlots[3]); + biomeToHabitat.put(BiomeDictionary.Type.JUNGLE, habitatSlots[4]); + biomeToHabitat.put(BiomeDictionary.Type.CONIFEROUS, habitatSlots[5]); + biomeToHabitat.put(BiomeDictionary.Type.MOUNTAIN, habitatSlots[6]); + biomeToHabitat.put(BiomeDictionary.Type.SWAMP, habitatSlots[7]); + biomeToHabitat.put(BiomeDictionary.Type.SNOWY, habitatSlots[8]); + biomeToHabitat.put(BiomeDictionary.Type.MUSHROOM, habitatSlots[9]); + biomeToHabitat.put(BiomeDictionary.Type.NETHER, habitatSlots[10]); + biomeToHabitat.put(BiomeDictionary.Type.END, habitatSlots[11]); + } + + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + + String str = StatCollector.translateToLocal("item.for.habitatLocator.name").toUpperCase(); + fontRendererObj.drawString(str, startX + 8 + getCenteredOffset(str, 138), startY + 16, fontColor.get("gui.screen")); + + // Set active according to valid biomes. + Set activeBiomeTypes = EnumSet.noneOf(BiomeDictionary.Type.class); + + for (HabitatSlot habitatSlot : habitatSlots) { + habitatSlot.isActive = false; + } + + for (BiomeGenBase biome : inventory.getBiomesToSearch()) { + Collections.addAll(activeBiomeTypes, BiomeDictionary.getTypesForBiome(biome)); + } + + for (BiomeDictionary.Type biomeType : activeBiomeTypes) { + HabitatSlot habitatSlot = biomeToHabitat.get(biomeType); + if (habitatSlot != null) { + habitatSlot.isActive = true; + } + } + + for (HabitatSlot slot : habitatSlots) { + slot.draw(startX, startY); + } + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); // Reset afterwards. + + } + + @Override + public void initGui() { + super.initGui(); + + startX = (this.width - this.xSize) / 2; + startY = (this.height - this.ySize) / 2; + } + public class HabitatSlot extends Widget { private final int slot; @@ -84,101 +180,4 @@ public class GuiHabitatLocator extends GuiForestry biomeToHabitat = new HashMap(); - - private int startX; - private int startY; - - public GuiHabitatLocator(EntityPlayer player, HabitatLocatorInventory item) { - super(Defaults.TEXTURE_PATH_GUI + "/biomefinder.png", new ContainerHabitatLocator(player, item), item); - - this.inventory.tryAnalyze(); - xSize = 176; - ySize = 184; - - int x; - int y; - for (HabitatSlot slot : habitatSlots) { - - if (slot.slot > 5) { - x = 18 + (slot.slot - 6) * 20; - y = 50; - } else { - x = 18 + slot.slot * 20; - y = 32; - } - - slot.setPosition(x, y); - this.widgetManager.add(slot); - } - - biomeToHabitat.put(BiomeDictionary.Type.OCEAN, habitatSlots[0]); - biomeToHabitat.put(BiomeDictionary.Type.BEACH, habitatSlots[0]); - biomeToHabitat.put(BiomeDictionary.Type.PLAINS, habitatSlots[1]); - biomeToHabitat.put(BiomeDictionary.Type.SANDY, habitatSlots[2]); - biomeToHabitat.put(BiomeDictionary.Type.FOREST, habitatSlots[3]); - biomeToHabitat.put(BiomeDictionary.Type.RIVER, habitatSlots[3]); - biomeToHabitat.put(BiomeDictionary.Type.JUNGLE, habitatSlots[4]); - biomeToHabitat.put(BiomeDictionary.Type.CONIFEROUS, habitatSlots[5]); - biomeToHabitat.put(BiomeDictionary.Type.MOUNTAIN, habitatSlots[6]); - biomeToHabitat.put(BiomeDictionary.Type.SWAMP, habitatSlots[7]); - biomeToHabitat.put(BiomeDictionary.Type.SNOWY, habitatSlots[8]); - biomeToHabitat.put(BiomeDictionary.Type.MUSHROOM, habitatSlots[9]); - biomeToHabitat.put(BiomeDictionary.Type.NETHER, habitatSlots[10]); - biomeToHabitat.put(BiomeDictionary.Type.END, habitatSlots[11]); - } - - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - - String str = StatCollector.translateToLocal("item.for.habitatLocator.name").toUpperCase(); - fontRendererObj.drawString(str, startX + 8 + getCenteredOffset(str, 138), startY + 16, fontColor.get("gui.screen")); - - // Set active according to valid biomes. - Set activeBiomeTypes = new HashSet(); - - for (HabitatSlot habitatSlot : habitatSlots) { - habitatSlot.isActive = false; - } - - for (BiomeGenBase biome : inventory.biomesToSearch) { - Collections.addAll(activeBiomeTypes, BiomeDictionary.getTypesForBiome(biome)); - } - - for (BiomeDictionary.Type biomeType : activeBiomeTypes) { - HabitatSlot habitatSlot = biomeToHabitat.get(biomeType); - if (habitatSlot != null) { - habitatSlot.isActive = true; - } - } - - for (HabitatSlot slot : habitatSlots) { - slot.draw(startX, startY); - } - GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); // Reset afterwards. - - } - - @Override - public void initGui() { - super.initGui(); - - startX = (this.width - this.xSize) / 2; - startY = (this.height - this.ySize) / 2; - } - } diff --git a/src/main/java/forestry/apiculture/gui/GuiImprinter.java b/src/main/java/forestry/apiculture/gui/GuiImprinter.java index 7ec6b3acb..6262d7cc9 100755 --- a/src/main/java/forestry/apiculture/gui/GuiImprinter.java +++ b/src/main/java/forestry/apiculture/gui/GuiImprinter.java @@ -106,9 +106,9 @@ public class GuiImprinter extends GuiForestry biomesToSearch = new HashSet(); - private final ItemHabitatLocator habitatLocator; - - public HabitatLocatorInventory(EntityPlayer player, ItemStack itemstack) { - super(player, 3, itemstack); - this.habitatLocator = (ItemHabitatLocator) itemstack.getItem(); - } - - private static boolean isEnergy(ItemStack itemstack) { - if (itemstack == null || itemstack.stackSize <= 0) { - return false; - } - - return ForestryItem.honeyDrop.isItemEqual(itemstack) || ForestryItem.honeydew.isItemEqual(itemstack); - } - - public void tryAnalyze() { - - if (getStackInSlot(SLOT_SPECIMEN) != null) { - // Requires energy - if (!isEnergy(getStackInSlot(SLOT_ENERGY))) { - return; - } - - // Decrease energy - decrStackSize(SLOT_ENERGY, 1); - - setInventorySlotContents(SLOT_ANALYZED, getStackInSlot(SLOT_SPECIMEN)); - setInventorySlotContents(SLOT_SPECIMEN, null); - } - - IBee bee = BeeManager.beeRoot.getMember(getStackInSlot(SLOT_ANALYZED)); - - // No bee, abort - if (bee == null) { - return; - } - - biomesToSearch = new HashSet(bee.getSuitableBiomes()); - habitatLocator.startBiomeSearch(biomesToSearch); - } - - @Override - public void markDirty() { - tryAnalyze(); - } - - // / IHINTSOURCE - @Override - public boolean hasHints() { - return Config.hints.get("habitatlocator") != null && Config.hints.get("habitatlocator").length > 0; - } - - @Override - public String[] getHints() { - return Config.hints.get("habitatlocator"); - } - - // / IERRORSOURCE - @Override - public ImmutableSet getErrorStates() { - if (getStackInSlot(SLOT_ANALYZED) != null) { - return ImmutableSet.of(); - } - - ImmutableSet.Builder errorStates = ImmutableSet.builder(); - - ItemStack specimen = getStackInSlot(SLOT_SPECIMEN); - if (!BeeManager.beeRoot.isMember(specimen)) { - errorStates.add(EnumErrorCode.NOTHINGANALYZE); - } - - if (!isEnergy(getStackInSlot(SLOT_ENERGY))) { - errorStates.add(EnumErrorCode.NOHONEY); - } - - return errorStates.build(); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (slotIndex == SLOT_ENERGY) { - Item item = itemStack.getItem(); - return item == ForestryItem.honeydew.item() || item == ForestryItem.honeyDrop.item(); - } else if (slotIndex == SLOT_SPECIMEN) { - return BeeManager.beeRoot.isMember(itemStack); - } - return false; - } - - } - private static final String iconName = "forestry:biomefinder"; - private Set biomesToSearch = new HashSet(); + private Set targetBiomes = new HashSet(); private boolean biomeFound = false; private int searchRadiusIteration = 0; private int searchAngleIteration = 0; @@ -204,13 +106,16 @@ public class ItemHabitatLocator extends ItemInventoried { list.add(StringUtil.localize("gui.humidity") + ": " + AlleleManager.climateHelper.toDisplay(humidity)); } - public void startBiomeSearch(Set biomesToSearch) { + public void startBiomeSearch(IBee bee, EntityPlayer player) { - this.biomesToSearch = biomesToSearch; + this.targetBiomes = new HashSet(bee.getSuitableBiomes()); this.searchAngleIteration = 0; this.searchRadiusIteration = 0; this.biomeFound = false; - this.searchCenter = null; + this.searchCenter = new Vect(player); + + BiomeGenBase currentBiome = player.worldObj.getBiomeGenForCoords(searchCenter.x, searchCenter.z); + removeInvalidBiomes(currentBiome, targetBiomes); // reset the locator coordinates Proxies.common.setHabitatLocatorCoordinates(null, null); @@ -223,14 +128,7 @@ public class ItemHabitatLocator extends ItemInventoried { return; } - if (this.searchCenter == null) { - this.searchCenter = new Vect((int) player.posX, (int) player.posY, (int) player.posZ); - - BiomeGenBase currentBiome = world.getBiomeGenForCoords(searchCenter.x, searchCenter.z); - removeInvalidBiomes(currentBiome, biomesToSearch); - } - - if (biomesToSearch.isEmpty()) { + if (targetBiomes.isEmpty()) { return; } @@ -239,7 +137,7 @@ public class ItemHabitatLocator extends ItemInventoried { return; } - ChunkCoordinates target = findNearestBiome(player, biomesToSearch); + ChunkCoordinates target = findNearestBiome(player, targetBiomes); // send an update if we find the biome if (target != null) { @@ -254,7 +152,7 @@ public class ItemHabitatLocator extends ItemInventoried { final int maxSearchRadiusIterations = 500; final int spacing = 20; - Vect playerPos = new Vect((int) player.posX, (int) player.posY, (int) player.posZ); + Vect playerPos = new Vect(player); // If we are in a valid spot, we point to ourselves. ChunkCoordinates coordinates = getChunkCoordinates(playerPos, player.worldObj, biomesToSearch); @@ -369,4 +267,105 @@ public class ItemHabitatLocator extends ItemInventoried { biomesToSearch.removeAll(endBiomes); } } + + public static class HabitatLocatorInventory extends ItemInventory implements IErrorSource, IHintSource { + + private static final short SLOT_ENERGY = 2; + private static final short SLOT_SPECIMEN = 0; + private static final short SLOT_ANALYZED = 1; + + private final ItemHabitatLocator habitatLocator; + + public HabitatLocatorInventory(EntityPlayer player, ItemStack itemstack) { + super(player, 3, itemstack); + this.habitatLocator = (ItemHabitatLocator) itemstack.getItem(); + } + + private static boolean isEnergy(ItemStack itemstack) { + if (itemstack == null || itemstack.stackSize <= 0) { + return false; + } + + return ForestryItem.honeyDrop.isItemEqual(itemstack) || ForestryItem.honeydew.isItemEqual(itemstack); + } + + @Override + public void onSlotClick(EntityPlayer player) { + + if (getStackInSlot(SLOT_ANALYZED) != null) { + if (habitatLocator.biomeFound) { + return; + } + } else if (getStackInSlot(SLOT_SPECIMEN) != null) { + // Requires energy + if (!isEnergy(getStackInSlot(SLOT_ENERGY))) { + return; + } + + // Decrease energy + decrStackSize(SLOT_ENERGY, 1); + + setInventorySlotContents(SLOT_ANALYZED, getStackInSlot(SLOT_SPECIMEN)); + setInventorySlotContents(SLOT_SPECIMEN, null); + } + + IBee bee = BeeManager.beeRoot.getMember(getStackInSlot(SLOT_ANALYZED)); + + // No bee, abort + if (bee == null) { + return; + } + + habitatLocator.startBiomeSearch(bee, player); + } + + public Set getBiomesToSearch() { + return habitatLocator.targetBiomes; + } + + // / IHINTSOURCE + @Override + public boolean hasHints() { + return Config.hints.get("habitatlocator") != null && Config.hints.get("habitatlocator").length > 0; + } + + @Override + public String[] getHints() { + return Config.hints.get("habitatlocator"); + } + + // / IERRORSOURCE + @Override + public ImmutableSet getErrorStates() { + if (getStackInSlot(SLOT_ANALYZED) != null) { + return ImmutableSet.of(); + } + + ImmutableSet.Builder errorStates = ImmutableSet.builder(); + + ItemStack specimen = getStackInSlot(SLOT_SPECIMEN); + if (!BeeManager.beeRoot.isMember(specimen)) { + errorStates.add(EnumErrorCode.NOTHINGANALYZE); + } + + if (!isEnergy(getStackInSlot(SLOT_ENERGY))) { + errorStates.add(EnumErrorCode.NOHONEY); + } + + return errorStates.build(); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + if (slotIndex == SLOT_ENERGY) { + Item item = itemStack.getItem(); + return item == ForestryItem.honeydew.item() || item == ForestryItem.honeyDrop.item(); + } else if (slotIndex == SLOT_SPECIMEN) { + return BeeManager.beeRoot.isMember(itemStack); + } + return false; + } + + } + } diff --git a/src/main/java/forestry/apiculture/items/ItemImprinter.java b/src/main/java/forestry/apiculture/items/ItemImprinter.java index 5e2a671c2..e2c07f804 100755 --- a/src/main/java/forestry/apiculture/items/ItemImprinter.java +++ b/src/main/java/forestry/apiculture/items/ItemImprinter.java @@ -102,8 +102,8 @@ public class ItemImprinter extends ItemForestry { secondaryIndex = index; } - private void tryImprint() { - + @Override + public void onSlotClick(EntityPlayer player) { ItemStack specimen = getStackInSlot(specimenSlot); if (specimen == null) { return; @@ -132,11 +132,6 @@ public class ItemImprinter extends ItemForestry { setInventorySlotContents(specimenSlot, null); } - @Override - public void markDirty() { - tryImprint(); - } - @Override public String getInventoryName() { return "Imprinter"; diff --git a/src/main/java/forestry/apiculture/network/PacketActiveUpdate.java b/src/main/java/forestry/apiculture/network/PacketActiveUpdate.java new file mode 100644 index 000000000..cfbf8d6a7 --- /dev/null +++ b/src/main/java/forestry/apiculture/network/PacketActiveUpdate.java @@ -0,0 +1,59 @@ +/******************************************************************************* + * 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.apiculture.network; + +import java.io.IOException; + +import net.minecraft.tileentity.TileEntity; + +import forestry.core.gadgets.TileForestry; +import forestry.core.interfaces.IActivatable; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.PacketCoordinates; +import forestry.core.network.PacketId; +import forestry.core.proxy.Proxies; + +public class PacketActiveUpdate extends PacketCoordinates { + + private IActivatable activatable; + + public static void onPacketData(DataInputStreamForestry data) throws IOException { + new PacketActiveUpdate(data); + } + + private PacketActiveUpdate(DataInputStreamForestry data) throws IOException { + super(data); + } + + public PacketActiveUpdate(T tile) { + super(PacketId.TILE_FORESTRY_ACTIVE, tile); + this.activatable = tile; + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeBoolean(activatable.isActive()); + } + + @Override + protected void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + + boolean active = data.readBoolean(); + + TileEntity tile = getTarget(Proxies.common.getRenderWorld()); + if (tile instanceof IActivatable) { + ((IActivatable) tile).setActive(active); + } + } +} diff --git a/src/main/java/forestry/apiculture/network/PacketHandlerApiculture.java b/src/main/java/forestry/apiculture/network/PacketHandlerApiculture.java index ad4c6f3a9..babf10cc5 100644 --- a/src/main/java/forestry/apiculture/network/PacketHandlerApiculture.java +++ b/src/main/java/forestry/apiculture/network/PacketHandlerApiculture.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.apiculture.network; -import java.io.DataInputStream; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; @@ -18,30 +17,29 @@ import net.minecraft.tileentity.TileEntity; import forestry.apiculture.gadgets.TileCandle; import forestry.apiculture.gui.ContainerImprinter; -import forestry.core.interfaces.IPacketHandler; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.IPacketHandler; import forestry.core.network.PacketCoordinates; -import forestry.core.network.PacketIds; +import forestry.core.network.PacketId; import forestry.core.proxy.Proxies; public class PacketHandlerApiculture implements IPacketHandler { @Override - public boolean onPacketData(int packetID, DataInputStream data, EntityPlayer player) throws IOException { + public boolean onPacketData(PacketId packetID, DataInputStreamForestry data, EntityPlayer player) throws IOException { switch (packetID) { - case PacketIds.HABITAT_BIOME_POINTER: { - PacketCoordinates packetC = new PacketCoordinates(); - packetC.readData(data); - Proxies.common.setHabitatLocatorCoordinates(player, packetC.getCoordinates()); + case HABITAT_BIOME_POINTER: { + PacketCoordinates packet = new PacketCoordinates(data); + Proxies.common.setHabitatLocatorCoordinates(player, packet.getCoordinates()); return true; } - case PacketIds.IMPRINT_SELECTION_GET: { + case IMPRINT_SELECTION_GET: { onImprintSelectionGet(player); return true; } - case PacketIds.CANDLE: { - PacketUpdateCandle updateCandle = new PacketUpdateCandle(); - updateCandle.readData(data); + case CANDLE: { + PacketUpdateCandle updateCandle = new PacketUpdateCandle(data); onCandleUpdate(updateCandle); return true; } diff --git a/src/main/java/forestry/apiculture/network/PacketUpdateCandle.java b/src/main/java/forestry/apiculture/network/PacketUpdateCandle.java index dd39017be..7c825f734 100644 --- a/src/main/java/forestry/apiculture/network/PacketUpdateCandle.java +++ b/src/main/java/forestry/apiculture/network/PacketUpdateCandle.java @@ -1,38 +1,38 @@ package forestry.apiculture.network; -import java.io.DataInputStream; -import java.io.DataOutputStream; import java.io.IOException; import forestry.apiculture.gadgets.TileCandle; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.PacketCoordinates; -import forestry.core.network.PacketIds; +import forestry.core.network.PacketId; public class PacketUpdateCandle extends PacketCoordinates { private int colour; private boolean lit; - public PacketUpdateCandle() { - + public PacketUpdateCandle(DataInputStreamForestry data) throws IOException { + super(data); } public PacketUpdateCandle(TileCandle tileCandle) { - super(PacketIds.CANDLE, tileCandle); + super(PacketId.CANDLE, tileCandle); colour = tileCandle.getColour(); lit = tileCandle.isLit(); } @Override - public void writeData(DataOutputStream data) throws IOException { + public void writeData(DataOutputStreamForestry data) throws IOException { super.writeData(data); data.writeInt(colour); data.writeBoolean(lit); } @Override - public void readData(DataInputStream data) throws IOException { + public void readData(DataInputStreamForestry data) throws IOException { super.readData(data); colour = data.readInt(); lit = data.readBoolean(); diff --git a/src/main/java/forestry/apiculture/proxy/ClientProxyApiculture.java b/src/main/java/forestry/apiculture/proxy/ClientProxyApiculture.java index 9c6cacff4..5fda06750 100755 --- a/src/main/java/forestry/apiculture/proxy/ClientProxyApiculture.java +++ b/src/main/java/forestry/apiculture/proxy/ClientProxyApiculture.java @@ -22,9 +22,9 @@ import forestry.apiculture.render.BeeItemRenderer; import forestry.apiculture.render.EntityBeeFX; import forestry.apiculture.render.ParticleRenderer; import forestry.apiculture.render.RenderBee; -import forestry.core.config.Config; import forestry.core.config.ForestryItem; import forestry.core.interfaces.IBlockRenderer; +import forestry.core.proxy.ClientProxyRender; import forestry.core.render.RenderAnalyzer; import forestry.core.render.TextureManager; import forestry.plugins.PluginApiculture; @@ -44,7 +44,7 @@ public class ClientProxyApiculture extends ProxyApiculture { @Override public void addBeeHiveFX(String icon, World world, double xCoord, double yCoord, double zCoord, int color, int areaX, int areaY, int areaZ) { - if (!Config.enableParticleFX) { + if (!ClientProxyRender.shouldSpawnParticle(world)) { return; } @@ -66,7 +66,7 @@ public class ClientProxyApiculture extends ProxyApiculture { @Override public void addBeeSwarmFX(String icon, World world, double xCoord, double yCoord, double zCoord, int color) { - if (!Config.enableParticleFX) { + if (!ClientProxyRender.shouldSpawnParticle(world)) { return; } diff --git a/src/main/java/forestry/apiculture/worldgen/ComponentVillageBeeHouse.java b/src/main/java/forestry/apiculture/worldgen/ComponentVillageBeeHouse.java index 90748d92d..24d2a12d6 100755 --- a/src/main/java/forestry/apiculture/worldgen/ComponentVillageBeeHouse.java +++ b/src/main/java/forestry/apiculture/worldgen/ComponentVillageBeeHouse.java @@ -30,6 +30,7 @@ import net.minecraftforge.common.ChestGenHooks; import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeType; import forestry.api.apiculture.FlowerManager; +import forestry.api.apiculture.IAlleleBeeSpecies; import forestry.api.apiculture.IBee; import forestry.api.apiculture.IBeeGenome; import forestry.api.core.EnumHumidity; @@ -328,7 +329,7 @@ public class ComponentVillageBeeHouse extends StructureVillagePieces.House1 { } } - private IBee getVillageBee(World world, int xCoord, int yCoord, int zCoord) { + private static IBee getVillageBee(World world, int xCoord, int yCoord, int zCoord) { // Get current biome BiomeGenBase biome = world.getBiomeGenForCoords(xCoord, zCoord); @@ -340,10 +341,13 @@ public class ComponentVillageBeeHouse extends StructureVillagePieces.House1 { candidates = BeeManager.villageBees[0]; } + EnumTemperature biomeTemperature = EnumTemperature.getFromBiome(biome, xCoord, yCoord, zCoord); + EnumHumidity biomeHumidity = EnumHumidity.getFromValue(biome.rainfall); + // Add bees that can live in this environment - ArrayList valid = new ArrayList(); + List valid = new ArrayList(); for (IBeeGenome genome : candidates) { - if (checkBiomeHazard(genome, biome.temperature, biome.rainfall)) { + if (checkBiomeHazard(genome, biomeTemperature, biomeHumidity)) { valid.add(genome); } } @@ -356,23 +360,11 @@ public class ComponentVillageBeeHouse extends StructureVillagePieces.House1 { return BeeManager.beeRoot.getBee(world, valid.get(world.rand.nextInt(valid.size()))); } - private boolean checkBiomeHazard(IBeeGenome genome, float temperature, float humidity) { - - EnumTemperature beeTemperature = genome.getPrimary().getTemperature(); - EnumTolerance temperatureTolerance = genome.getToleranceTemp(); - - Collection toleratedTemperatures = AlleleManager.climateHelper.getToleratedTemperature(beeTemperature, temperatureTolerance); - - if (!toleratedTemperatures.contains(EnumTemperature.getFromValue(temperature))) { - return false; - } - - EnumHumidity beeHumidity = genome.getPrimary().getHumidity(); - EnumTolerance humidityTolerance = genome.getToleranceHumid(); - - Collection toleratedHumidity = AlleleManager.climateHelper.getToleratedHumidity(beeHumidity, humidityTolerance); - - return toleratedHumidity.contains(EnumHumidity.getFromValue(humidity)); + private static boolean checkBiomeHazard(IBeeGenome genome, EnumTemperature biomeTemperature, EnumHumidity biomeHumidity) { + IAlleleBeeSpecies species = genome.getPrimary(); + return AlleleManager.climateHelper.isWithinLimits(biomeTemperature, biomeHumidity, + species.getTemperature(), genome.getToleranceTemp(), + species.getHumidity(), genome.getToleranceHumid()); } protected void fillBoxWith(World world, StructureBoundingBox box, int par3, int par4, int par5, int par6, int par7, int par8, ItemStack buildingBlock, diff --git a/src/main/java/forestry/arboriculture/PacketHandlerArboriculture.java b/src/main/java/forestry/arboriculture/PacketHandlerArboriculture.java deleted file mode 100755 index 186668e9b..000000000 --- a/src/main/java/forestry/arboriculture/PacketHandlerArboriculture.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.arboriculture; - -import java.io.DataInputStream; -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; - -import forestry.arboriculture.gadgets.TileLeaves; -import forestry.arboriculture.gadgets.TileSapling; -import forestry.arboriculture.network.PacketLeaf; -import forestry.arboriculture.network.PacketRipeningUpdate; -import forestry.arboriculture.network.PacketSapling; -import forestry.core.interfaces.IPacketHandler; -import forestry.core.network.PacketIds; -import forestry.core.proxy.Proxies; - -public class PacketHandlerArboriculture implements IPacketHandler { - - @Override - public boolean onPacketData(int packetID, DataInputStream data, EntityPlayer player) throws IOException { - - switch (packetID) { - case PacketIds.SAPLING: { - PacketSapling packet = new PacketSapling(); - packet.readData(data); - onSaplingPacket(packet); - return true; - } - case PacketIds.LEAF: { - PacketLeaf packet = new PacketLeaf(); - packet.readData(data); - onLeafPacket(packet); - return true; - } - case PacketIds.RIPENING_UPDATE: { - PacketRipeningUpdate packet = new PacketRipeningUpdate(); - packet.readData(data); - onRipeningUpdate(packet); - return true; - } - } - - return false; - } - - private void onSaplingPacket(PacketSapling packet) { - TileEntity tile = packet.getTarget(Proxies.common.getRenderWorld()); - if (tile instanceof TileSapling) { - ((TileSapling) tile).fromPacket(packet); - } - } - - private void onLeafPacket(PacketLeaf packet) { - - TileEntity tile = packet.getTarget(Proxies.common.getRenderWorld()); - if (tile instanceof TileLeaves) { - ((TileLeaves) tile).fromPacket(packet); - } - - } - - private void onRipeningUpdate(PacketRipeningUpdate packet) { - - TileEntity tile = packet.getTarget(Proxies.common.getRenderWorld()); - if (tile instanceof TileLeaves) { - ((TileLeaves) tile).fromRipeningPacket(packet); - } - - } - -} diff --git a/src/main/java/forestry/arboriculture/gadgets/BlockArbStairs.java b/src/main/java/forestry/arboriculture/gadgets/BlockArbStairs.java index 66b336f05..1896a1a54 100755 --- a/src/main/java/forestry/arboriculture/gadgets/BlockArbStairs.java +++ b/src/main/java/forestry/arboriculture/gadgets/BlockArbStairs.java @@ -79,7 +79,7 @@ public class BlockArbStairs extends BlockStairs { ItemStack stack = new ItemStack(this, 1, 0); NBTTagCompound compound = new NBTTagCompound(); - stairs.getType().saveToCompound(compound); + stairs.getWoodType().saveToCompound(compound); stack.setTagCompound(compound); StackUtils.dropItemStackAsEntity(stack, world, x, y, z); } @@ -122,11 +122,11 @@ public class BlockArbStairs extends BlockStairs { TileStairs stairs = getStairTile(world, x, y, z); NBTTagCompound nbttagcompound = new NBTTagCompound(); - if (stairs == null || stairs.getType() == null) { + if (stairs == null || stairs.getWoodType() == null) { return nbttagcompound; } - stairs.getType().saveToCompound(nbttagcompound); + stairs.getWoodType().saveToCompound(nbttagcompound); return nbttagcompound; } @@ -141,8 +141,8 @@ public class BlockArbStairs extends BlockStairs { @Override public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { TileStairs stairs = getStairTile(world, x, y, z); - if (stairs != null && stairs.getType() != null) { - return stairs.getType().getPlankIcon(); + if (stairs != null && stairs.getWoodType() != null) { + return stairs.getWoodType().getPlankIcon(); } else { return WoodType.LARCH.getPlankIcon(); } diff --git a/src/main/java/forestry/arboriculture/gadgets/TileFruitPod.java b/src/main/java/forestry/arboriculture/gadgets/TileFruitPod.java index 8cf5ddfcc..8f9865a9f 100755 --- a/src/main/java/forestry/arboriculture/gadgets/TileFruitPod.java +++ b/src/main/java/forestry/arboriculture/gadgets/TileFruitPod.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.gadgets; +import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -28,15 +29,15 @@ import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAllele; import forestry.api.genetics.IFruitBearer; import forestry.api.genetics.IFruitFamily; -import forestry.core.network.ForestryPacket; -import forestry.core.network.INetworkedEntity; -import forestry.core.network.PacketIds; -import forestry.core.network.PacketPayload; -import forestry.core.network.PacketUpdate; +import forestry.arboriculture.network.PacketRipeningUpdate; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IStreamable; +import forestry.core.network.PacketTileStream; import forestry.core.proxy.Proxies; import forestry.core.render.TextureManager; -public class TileFruitPod extends TileEntity implements INetworkedEntity, IFruitBearer { +public class TileFruitPod extends TileEntity implements IFruitBearer, IStreamable { private static final short MAX_MATURITY = 2; @@ -130,37 +131,11 @@ public class TileFruitPod extends TileEntity implements INetworkedEntity, IFruit /* NETWORK */ @Override public Packet getDescriptionPacket() { - return toPacket().getPacket(); - } - - @Override - public void sendNetworkUpdate() { - Proxies.net.sendNetworkPacket(toPacket(), xCoord, yCoord, zCoord); + return new PacketTileStream(this).getPacket(); } private void sendNetworkUpdateRipening() { - Proxies.net.sendNetworkPacket(new PacketUpdate(PacketIds.TILE_UPDATE, xCoord, yCoord, zCoord, maturity), xCoord, yCoord, zCoord); - } - - private ForestryPacket toPacket() { - - PacketPayload payload = new PacketPayload(indices.length, 1); - payload.shortPayload[0] = maturity; - payload.intPayload = indices; - - return new PacketUpdate(PacketIds.TILE_UPDATE, xCoord, yCoord, zCoord, payload); - } - - @Override - public void fromPacket(ForestryPacket packetRaw) { - PacketUpdate packet = (PacketUpdate) packetRaw; - maturity = packet.payload.shortPayload[0]; - - if (packet.payload.intPayload != null && packet.payload.intPayload.length > 0) { - indices = packet.payload.intPayload; - } - - worldObj.func_147479_m(xCoord, yCoord, zCoord); + Proxies.net.sendNetworkPacket(new PacketRipeningUpdate(this)); } /* IFRUITBEARER */ @@ -183,7 +158,6 @@ public class TileFruitPod extends TileEntity implements INetworkedEntity, IFruit return new ArrayList(); } - Collection fruits = Arrays.asList(getDrop()); maturity = 0; sendNetworkUpdateRipening(); @@ -201,4 +175,24 @@ public class TileFruitPod extends TileEntity implements INetworkedEntity, IFruit sendNetworkUpdateRipening(); } + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + data.writeShort(maturity); + data.writeShort(indices.length); + for (int i : indices) { + data.writeInt(i); + } + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + maturity = data.readShort(); + int indicesLength = data.readShort(); + indices = new int[indicesLength]; + for (int i = 0; i < indicesLength; i++) { + indices[i] = data.readInt(); + } + + worldObj.func_147479_m(xCoord, yCoord, zCoord); + } } diff --git a/src/main/java/forestry/arboriculture/gadgets/TileLeaves.java b/src/main/java/forestry/arboriculture/gadgets/TileLeaves.java index c33782844..a7acb60bf 100755 --- a/src/main/java/forestry/arboriculture/gadgets/TileLeaves.java +++ b/src/main/java/forestry/arboriculture/gadgets/TileLeaves.java @@ -12,6 +12,7 @@ package forestry.arboriculture.gadgets; import com.google.common.collect.ImmutableSet; +import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; @@ -33,6 +34,7 @@ import net.minecraftforge.common.EnumPlantType; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.arboriculture.EnumTreeChromosome; import forestry.api.arboriculture.IAlleleTreeSpecies; import forestry.api.arboriculture.IFruitProvider; import forestry.api.arboriculture.ILeafTickHandler; @@ -43,6 +45,7 @@ import forestry.api.core.EnumHumidity; import forestry.api.core.EnumTemperature; import forestry.api.core.IErrorState; import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IAllele; import forestry.api.genetics.IEffectData; import forestry.api.genetics.IFruitBearer; import forestry.api.genetics.IFruitFamily; @@ -52,11 +55,12 @@ import forestry.api.lepidopterology.IButterfly; import forestry.api.lepidopterology.IButterflyGenome; import forestry.api.lepidopterology.IButterflyNursery; import forestry.api.lepidopterology.IButterflyRoot; -import forestry.arboriculture.network.PacketLeaf; import forestry.arboriculture.network.PacketRipeningUpdate; import forestry.core.EnumErrorCode; import forestry.core.genetics.alleles.Allele; -import forestry.core.network.ForestryPacket; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.PacketTileStream; import forestry.core.proxy.Proxies; import forestry.core.render.TextureManager; import forestry.core.utils.GeneticsUtil; @@ -91,7 +95,7 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru if (worldObj == null) { return; } - biome = Utils.getBiomeAt(worldObj, xCoord, zCoord); + biome = worldObj.getBiomeGenForCoordsBody(xCoord, zCoord); } /* SAVING & LOADING */ @@ -330,13 +334,11 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru /* NETWORK */ @Override public Packet getDescriptionPacket() { - return new PacketLeaf(this).getPacket(); + return new PacketTileStream(this).getPacket(); } - @Override public void sendNetworkUpdate() { - PacketLeaf packet = new PacketLeaf(this); - Proxies.net.sendNetworkPacket(packet, xCoord, yCoord, zCoord); + Proxies.net.sendNetworkPacket(new PacketTileStream(this)); } private void sendNetworkUpdateRipening() { @@ -347,31 +349,76 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru colourFruits = newColourFruits; PacketRipeningUpdate ripeningUpdate = new PacketRipeningUpdate(this); - Proxies.net.sendNetworkPacket(ripeningUpdate, xCoord, yCoord, zCoord); + Proxies.net.sendNetworkPacket(ripeningUpdate); + } + + private static final short hasFruitFlag = 1; + private static final short isPollinatedFlag = 1 << 1; + + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + + byte leafState = 0; + boolean hasFruit = hasFruit(); + + if (isPollinated()) { + leafState |= isPollinatedFlag; + } + + if (hasFruit) { + leafState |= hasFruitFlag; + } + + data.writeByte(leafState); + + if (hasFruit) { + String fruitAlleleUID = getTree().getGenome().getActiveAllele(EnumTreeChromosome.FRUITS).getUID(); + int colourFruits = getFruitColour(); + + data.writeUTF(fruitAlleleUID); + data.writeInt(colourFruits); + } } @Override - public void fromPacket(ForestryPacket packetRaw) { - PacketLeaf packet = (PacketLeaf) packetRaw; + public void readData(DataInputStreamForestry data) throws IOException { - isFruitLeaf = packet.isFruitLeaf(); - isPollinatedState = packet.isPollinated(); + String speciesUID = data.readUTF(); // this is called instead of super.readData, be careful! - colourFruits = packet.getColourFruits(); + byte leafState = data.readByte(); + isFruitLeaf = (leafState & hasFruitFlag) > 0; + isPollinatedState = (leafState & isPollinatedFlag) > 0; + String fruitAlleleUID = null; - ITree tree = getTree(); - if (!packet.matchesTree(tree)) { - ITree newTree = packet.getTree(); - if (newTree != null) { - setTree(newTree); + if (isFruitLeaf) { + fruitAlleleUID = data.readUTF(); + colourFruits = data.readInt(); + } + + IAllele[] treeTemplate = PluginArboriculture.treeInterface.getTemplate(speciesUID); + + if (fruitAlleleUID != null) { + IAllele fruitAllele = AlleleManager.alleleRegistry.getAllele(fruitAlleleUID); + if (fruitAllele != null) { + treeTemplate[EnumTreeChromosome.FRUITS.ordinal()] = fruitAllele; } } - worldObj.func_147479_m(xCoord, yCoord, zCoord); + if (treeTemplate != null) { + ITree tree = PluginArboriculture.treeInterface.templateAsIndividual(treeTemplate); + if (isPollinatedState) { + tree.mate(tree); + } + + setTree(tree); + + worldObj.func_147479_m(xCoord, yCoord, zCoord); + } } public void fromRipeningPacket(PacketRipeningUpdate packet) { - int newColourFruits = packet.getColourFruits(); + int newColourFruits = packet.getValue(); if (newColourFruits == colourFruits) { return; } @@ -465,7 +512,7 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru } } - private void attemptButterflySpawn(World world, IButterfly butterfly, double x, double y, double z) { + private static void attemptButterflySpawn(World world, IButterfly butterfly, double x, double y, double z) { IButterflyRoot butterflyRoot = (IButterflyRoot) AlleleManager.alleleRegistry.getSpeciesRoot("rootButterflies"); if (butterflyRoot.spawnButterflyInWorld(world, butterfly.copy(), x, y + 0.1f, z) != null) { Proxies.log.finest("A caterpillar '%s' hatched at %s/%s/%s.", butterfly.getDisplayName(), x, y, z); @@ -560,6 +607,6 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru /* IHousing */ @Override public GameProfile getOwnerName() { - return this.getOwnerProfile(); + return this.getOwner(); } } diff --git a/src/main/java/forestry/arboriculture/gadgets/TileSapling.java b/src/main/java/forestry/arboriculture/gadgets/TileSapling.java index e2953144f..10dbdec2c 100755 --- a/src/main/java/forestry/arboriculture/gadgets/TileSapling.java +++ b/src/main/java/forestry/arboriculture/gadgets/TileSapling.java @@ -14,10 +14,7 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.Packet; import net.minecraft.world.gen.feature.WorldGenerator; -import forestry.api.arboriculture.ITree; -import forestry.arboriculture.network.PacketSapling; -import forestry.core.network.ForestryPacket; -import forestry.core.proxy.Proxies; +import forestry.core.network.PacketTileStream; import forestry.plugins.PluginArboriculture; public class TileSapling extends TileTreeContainer { @@ -67,7 +64,7 @@ public class TileSapling extends TileTreeContainer { WorldGenerator generator = this.getTree().getTreeGenerator(worldObj, xCoord, yCoord, zCoord, bonemealed); if (generator.generate(worldObj, worldObj.rand, xCoord, yCoord, zCoord)) { - PluginArboriculture.treeInterface.getBreedingTracker(worldObj, getOwnerProfile()).registerBirth(getTree()); + PluginArboriculture.treeInterface.getBreedingTracker(worldObj, getOwner()).registerBirth(getTree()); return 2; } @@ -76,31 +73,6 @@ public class TileSapling extends TileTreeContainer { @Override public Packet getDescriptionPacket() { - return new PacketSapling(this).getPacket(); + return new PacketTileStream(this).getPacket(); } - - @Override - public void sendNetworkUpdate() { - PacketSapling saplingPacket = new PacketSapling(this); - Proxies.net.sendNetworkPacket(saplingPacket, xCoord, yCoord, zCoord); - } - - @Override - public void fromPacket(ForestryPacket packetRaw) { - PacketSapling packet = (PacketSapling) packetRaw; - - ITree tree = getTree(); - if (packet.matchesTree(tree)) { - return; - } - - ITree newTree = packet.getTree(); - if (newTree == null) { - return; - } - - setTree(newTree); - worldObj.func_147479_m(xCoord, yCoord, zCoord); - } - } diff --git a/src/main/java/forestry/arboriculture/gadgets/TileStairs.java b/src/main/java/forestry/arboriculture/gadgets/TileStairs.java index acc451eb0..3b1a032fc 100755 --- a/src/main/java/forestry/arboriculture/gadgets/TileStairs.java +++ b/src/main/java/forestry/arboriculture/gadgets/TileStairs.java @@ -10,27 +10,29 @@ ******************************************************************************/ package forestry.arboriculture.gadgets; +import java.io.IOException; + import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.Packet; import net.minecraft.tileentity.TileEntity; import forestry.arboriculture.WoodType; -import forestry.core.network.ForestryPacket; -import forestry.core.network.INetworkedEntity; -import forestry.core.network.PacketIds; -import forestry.core.network.PacketTileNBT; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IStreamable; +import forestry.core.network.PacketTileStream; import forestry.core.proxy.Proxies; -public class TileStairs extends TileEntity implements INetworkedEntity { +public class TileStairs extends TileEntity implements IStreamable { - private WoodType type; + private WoodType woodType; - public WoodType getType() { - return this.type; + public WoodType getWoodType() { + return this.woodType; } - public void setType(WoodType type) { - this.type = type; + public void setWoodType(WoodType woodType) { + this.woodType = woodType; sendNetworkUpdate(); } @@ -40,7 +42,7 @@ public class TileStairs extends TileEntity implements INetworkedEntity { super.readFromNBT(nbttagcompound); if (nbttagcompound.hasKey("WT")) { - type = WoodType.VALUES[nbttagcompound.getShort("WT")]; + woodType = WoodType.VALUES[nbttagcompound.getShort("WT")]; } } @@ -48,8 +50,8 @@ public class TileStairs extends TileEntity implements INetworkedEntity { public void writeToNBT(NBTTagCompound nbttagcompound) { super.writeToNBT(nbttagcompound); - if (type != null) { - nbttagcompound.setShort("WT", (short) type.ordinal()); + if (woodType != null) { + nbttagcompound.setShort("WT", (short) woodType.ordinal()); } } @@ -66,19 +68,22 @@ public class TileStairs extends TileEntity implements INetworkedEntity { /* INETWORKEDENTITY */ @Override public Packet getDescriptionPacket() { - return new PacketTileNBT(PacketIds.TILE_NBT, this).getPacket(); + return new PacketTileStream(this).getPacket(); } - @Override public void sendNetworkUpdate() { - Proxies.net.sendNetworkPacket(new PacketTileNBT(PacketIds.TILE_NBT, this), xCoord, yCoord, zCoord); + Proxies.net.sendNetworkPacket(new PacketTileStream(this)); } @Override - public void fromPacket(ForestryPacket packetRaw) { - PacketTileNBT packet = (PacketTileNBT) packetRaw; - this.readFromNBT(packet.getTagCompound()); + public void writeData(DataOutputStreamForestry data) throws IOException { + data.writeVarInt(woodType.ordinal()); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + int woodTypeOrdinal = data.readVarInt(); + woodType = WoodType.values()[woodTypeOrdinal]; worldObj.func_147479_m(xCoord, yCoord, zCoord); } - } diff --git a/src/main/java/forestry/arboriculture/gadgets/TileTreeContainer.java b/src/main/java/forestry/arboriculture/gadgets/TileTreeContainer.java index 242c93523..019424df7 100755 --- a/src/main/java/forestry/arboriculture/gadgets/TileTreeContainer.java +++ b/src/main/java/forestry/arboriculture/gadgets/TileTreeContainer.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.arboriculture.gadgets; +import java.io.IOException; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTUtil; @@ -19,17 +21,21 @@ import net.minecraft.tileentity.TileEntity; import com.mojang.authlib.GameProfile; import forestry.api.arboriculture.ITree; +import forestry.api.genetics.IAllele; import forestry.arboriculture.genetics.Tree; import forestry.core.interfaces.IOwnable; -import forestry.core.network.INetworkedEntity; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IStreamable; import forestry.core.utils.PlayerUtil; +import forestry.plugins.PluginArboriculture; /** * This is the base TE class for any block that needs to contain tree genome information. * * @author SirSengir */ -public abstract class TileTreeContainer extends TileEntity implements INetworkedEntity, IOwnable { +public abstract class TileTreeContainer extends TileEntity implements IStreamable, IOwnable { private ITree containedTree; @@ -44,7 +50,6 @@ public abstract class TileTreeContainer extends TileEntity implements INetworked if (nbttagcompound.hasKey("owner")) { owner = NBTUtil.func_152459_a(nbttagcompound.getCompoundTag("owner")); } - } @Override @@ -61,7 +66,31 @@ public abstract class TileTreeContainer extends TileEntity implements INetworked NBTUtil.func_152460_a(nbt, owner); nbttagcompound.setTag("owner", nbt); } + } + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + String speciesUID = ""; + ITree tree = getTree(); + if (tree != null) { + speciesUID = tree.getIdent(); + } + data.writeUTF(speciesUID); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + String speciesUID = data.readUTF(); + ITree tree = getTree(speciesUID); + setTree(tree); + } + + public static ITree getTree(String speciesUID) { + IAllele[] treeTemplate = PluginArboriculture.treeInterface.getTemplate(speciesUID); + if (treeTemplate == null) { + return null; + } + return PluginArboriculture.treeInterface.templateAsIndividual(treeTemplate); } /* CLIENT INFORMATION */ @@ -102,18 +131,13 @@ public abstract class TileTreeContainer extends TileEntity implements INetworked return true; } - @Override - public boolean isOwnable() { - return false; - } - @Override public boolean isOwned() { return owner != null; } @Override - public GameProfile getOwnerProfile() { + public GameProfile getOwner() { return owner; } diff --git a/src/main/java/forestry/arboriculture/genetics/GrowthProvider.java b/src/main/java/forestry/arboriculture/genetics/GrowthProvider.java index aa083509b..ab442b873 100755 --- a/src/main/java/forestry/arboriculture/genetics/GrowthProvider.java +++ b/src/main/java/forestry/arboriculture/genetics/GrowthProvider.java @@ -47,7 +47,7 @@ public class GrowthProvider implements IGrowthProvider { return new String[0]; } - protected EnumGrowthConditions getConditionsFromRainfall(World world, int xPos, int yPos, int zPos, float min, float max) { + protected static EnumGrowthConditions getConditionsFromRainfall(World world, int xPos, int yPos, int zPos, float min, float max) { BiomeGenBase biome = world.getWorldChunkManager().getBiomeGenAt(xPos, zPos); if (biome.rainfall < min || biome.rainfall > max) { @@ -57,17 +57,18 @@ public class GrowthProvider implements IGrowthProvider { return EnumGrowthConditions.EXCELLENT; } - protected EnumGrowthConditions getConditionsFromTemperature(World world, int xPos, int yPos, int zPos, float min, float max) { + protected static EnumGrowthConditions getConditionsFromTemperature(World world, int xPos, int yPos, int zPos, float min, float max) { BiomeGenBase biome = world.getWorldChunkManager().getBiomeGenAt(xPos, zPos); - if (biome.temperature < min || biome.temperature > max) { + float biomeTemperature = biome.getFloatTemperature(xPos, yPos, zPos); + if (biomeTemperature < min || biomeTemperature > max) { return EnumGrowthConditions.HOSTILE; } return EnumGrowthConditions.EXCELLENT; } - protected EnumGrowthConditions getConditionFromLight(World world, int xPos, int yPos, int zPos) { + protected static EnumGrowthConditions getConditionFromLight(World world, int xPos, int yPos, int zPos) { int lightvalue = world.getBlockLightValue(xPos, yPos + 1, zPos); if (lightvalue > 13) { @@ -93,7 +94,7 @@ public class GrowthProvider implements IGrowthProvider { * return EnumGrowthConditions.HOSTILE; } */ - protected boolean hasRoom(ITreeGenome genome, World world, int xPos, int yPos, int zPos, int expectedGirth, int expectedHeight) { + protected static boolean hasRoom(ITreeGenome genome, World world, int xPos, int yPos, int zPos, int expectedGirth, int expectedHeight) { int offset = (expectedGirth - 1) / 2; // if(offset <= 0) @@ -103,7 +104,7 @@ public class GrowthProvider implements IGrowthProvider { new Vect(-offset + expectedGirth, expectedHeight + 1, -offset + expectedGirth)); } - protected final boolean checkArea(World world, Vect start, Vect area) { + protected static boolean checkArea(World world, Vect start, Vect area) { for (int x = start.x; x < start.x + area.x; x++) { for (int y = start.y; y < start.y + area.y; y++) { for (int z = start.z; z < start.z + area.z; z++) { @@ -116,7 +117,7 @@ public class GrowthProvider implements IGrowthProvider { return true; } - protected boolean hasSufficientSaplings(ITreeGenome genome, World world, int xPos, int yPos, int zPos, int expectedGirth) { + protected static boolean hasSufficientSaplings(ITreeGenome genome, World world, int xPos, int yPos, int zPos, int expectedGirth) { if (expectedGirth == 1) { return true; diff --git a/src/main/java/forestry/arboriculture/genetics/GrowthProviderTropical.java b/src/main/java/forestry/arboriculture/genetics/GrowthProviderTropical.java index 763496b64..2e02d6c01 100755 --- a/src/main/java/forestry/arboriculture/genetics/GrowthProviderTropical.java +++ b/src/main/java/forestry/arboriculture/genetics/GrowthProviderTropical.java @@ -25,7 +25,10 @@ public class GrowthProviderTropical extends GrowthProvider { 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, BiomeGenBase.jungle.rainfall, 2.0f); - EnumGrowthConditions temperature = getConditionsFromTemperature(world, xPos, yPos, zPos, BiomeGenBase.jungle.temperature, BiomeGenBase.desert.temperature - 0.1f); + + float jungleTemperature = BiomeGenBase.jungle.getFloatTemperature(xPos, yPos, zPos); + float desertTemperature = BiomeGenBase.desert.getFloatTemperature(xPos, yPos, zPos); + EnumGrowthConditions temperature = getConditionsFromTemperature(world, xPos, yPos, zPos, jungleTemperature, desertTemperature - 0.1f); EnumSet conditions = EnumSet.of(light, moisture, temperature); diff --git a/src/main/java/forestry/arboriculture/genetics/TreeGenome.java b/src/main/java/forestry/arboriculture/genetics/TreeGenome.java index 5201239a5..0ad9f99d2 100755 --- a/src/main/java/forestry/arboriculture/genetics/TreeGenome.java +++ b/src/main/java/forestry/arboriculture/genetics/TreeGenome.java @@ -27,6 +27,7 @@ import forestry.api.arboriculture.IGrowthProvider; import forestry.api.arboriculture.ITreeGenome; import forestry.api.genetics.IAlleleFloat; import forestry.api.genetics.IAlleleInteger; +import forestry.api.genetics.IAlleleSpecies; import forestry.api.genetics.IChromosome; import forestry.api.genetics.ISpeciesRoot; import forestry.core.genetics.Genome; @@ -45,6 +46,11 @@ public class TreeGenome extends Genome implements ITreeGenome { // NBT RETRIEVAL public static IAlleleTreeSpecies getSpecies(ItemStack itemStack) { + IAlleleSpecies species = getSpeciesDirectly(itemStack); + if (species instanceof IAlleleTreeSpecies) { + return (IAlleleTreeSpecies) species; + } + return (IAlleleTreeSpecies) getActiveAllele(itemStack, EnumTreeChromosome.SPECIES, PluginArboriculture.treeInterface); } diff --git a/src/main/java/forestry/arboriculture/items/ItemStairs.java b/src/main/java/forestry/arboriculture/items/ItemStairs.java index 0b24e6b6c..eec9357dc 100755 --- a/src/main/java/forestry/arboriculture/items/ItemStairs.java +++ b/src/main/java/forestry/arboriculture/items/ItemStairs.java @@ -60,7 +60,7 @@ public class ItemStairs extends ItemForestryBlock { return false; } - ((TileStairs) tile).setType(type); + ((TileStairs) tile).setWoodType(type); return true; } diff --git a/src/main/java/forestry/arboriculture/items/ItemTreealyzer.java b/src/main/java/forestry/arboriculture/items/ItemTreealyzer.java index f6ca5c9a8..726ee4ab0 100755 --- a/src/main/java/forestry/arboriculture/items/ItemTreealyzer.java +++ b/src/main/java/forestry/arboriculture/items/ItemTreealyzer.java @@ -40,7 +40,8 @@ public class ItemTreealyzer extends ItemInventoried { return GeneticsUtil.getGeneticEquivalent(itemStack) instanceof ITree; } - private void tryAnalyze() { + @Override + public void onSlotClick(EntityPlayer player) { // Source slot to analyze empty if (getStackInSlot(SLOT_SPECIMEN) == null) { return; @@ -83,11 +84,6 @@ public class ItemTreealyzer extends ItemInventoried { setInventorySlotContents(SLOT_SPECIMEN, null); } - @Override - public void markDirty() { - tryAnalyze(); - } - // / IHINTSOURCE @Override public boolean hasHints() { diff --git a/src/main/java/forestry/arboriculture/network/PacketHandlerArboriculture.java b/src/main/java/forestry/arboriculture/network/PacketHandlerArboriculture.java new file mode 100644 index 000000000..e08c417cc --- /dev/null +++ b/src/main/java/forestry/arboriculture/network/PacketHandlerArboriculture.java @@ -0,0 +1,46 @@ +/******************************************************************************* + * 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.arboriculture.network; + +import java.io.IOException; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; + +import forestry.arboriculture.gadgets.TileLeaves; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.IPacketHandler; +import forestry.core.network.PacketId; +import forestry.core.proxy.Proxies; + +public class PacketHandlerArboriculture implements IPacketHandler { + + @Override + public boolean onPacketData(PacketId packetID, DataInputStreamForestry data, EntityPlayer player) throws IOException { + + switch (packetID) { + case RIPENING_UPDATE: { + PacketRipeningUpdate packet = new PacketRipeningUpdate(data); + onRipeningUpdate(packet); + return true; + } + } + + return false; + } + + private static void onRipeningUpdate(PacketRipeningUpdate packet) { + TileEntity tile = packet.getTarget(Proxies.common.getRenderWorld()); + if (tile instanceof TileLeaves) { + ((TileLeaves) tile).fromRipeningPacket(packet); + } + } +} diff --git a/src/main/java/forestry/arboriculture/network/PacketLeaf.java b/src/main/java/forestry/arboriculture/network/PacketLeaf.java deleted file mode 100644 index 1e85d6f15..000000000 --- a/src/main/java/forestry/arboriculture/network/PacketLeaf.java +++ /dev/null @@ -1,105 +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.arboriculture.network; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import forestry.api.arboriculture.EnumTreeChromosome; -import forestry.api.arboriculture.ITree; -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.IAllele; -import forestry.arboriculture.gadgets.TileLeaves; -import forestry.core.network.PacketIds; -import forestry.plugins.PluginArboriculture; - -public class PacketLeaf extends PacketTreeContainer { - - private static final short hasFruitFlag = 1; - private static final short isPollinatedFlag = 1 << 1; - - private byte leafState = 0; - private int colourFruits = -1; - private String fruitAlleleUID; - - public PacketLeaf() { - - } - - public PacketLeaf(TileLeaves leaves) { - super(PacketIds.LEAF, leaves); - - if (leaves.hasFruit()) { - leafState |= hasFruitFlag; - fruitAlleleUID = leaves.getTree().getGenome().getActiveAllele(EnumTreeChromosome.FRUITS).getUID(); - colourFruits = leaves.getFruitColour(); - } - if (leaves.isPollinated()) { - leafState |= isPollinatedFlag; - } - } - - @Override - public void writeData(DataOutputStream data) throws IOException { - super.writeData(data); - data.writeByte(leafState); - - if (isFruitLeaf()) { - data.writeUTF(fruitAlleleUID); - data.writeInt(colourFruits); - } - } - - @Override - public void readData(DataInputStream data) throws IOException { - super.readData(data); - leafState = data.readByte(); - - if (isFruitLeaf()) { - fruitAlleleUID = data.readUTF(); - colourFruits = data.readInt(); - } - } - - public boolean isFruitLeaf() { - return (leafState & hasFruitFlag) > 0; - } - - public boolean isPollinated() { - return (leafState & isPollinatedFlag) > 0; - } - - public int getColourFruits() { - return colourFruits; - } - - @Override - public ITree getTree() { - IAllele[] treeTemplate = PluginArboriculture.treeInterface.getTemplate(speciesUID); - if (treeTemplate == null) { - return null; - } - - if (fruitAlleleUID != null) { - IAllele fruitAllele = AlleleManager.alleleRegistry.getAllele(fruitAlleleUID); - if (fruitAllele != null) { - treeTemplate[EnumTreeChromosome.FRUITS.ordinal()] = fruitAllele; - } - } - - ITree tree = PluginArboriculture.treeInterface.templateAsIndividual(treeTemplate); - if (isPollinated()) { - tree.mate(tree); - } - return tree; - } -} diff --git a/src/main/java/forestry/arboriculture/network/PacketRipeningUpdate.java b/src/main/java/forestry/arboriculture/network/PacketRipeningUpdate.java index 04c28b822..138d83f3f 100644 --- a/src/main/java/forestry/arboriculture/network/PacketRipeningUpdate.java +++ b/src/main/java/forestry/arboriculture/network/PacketRipeningUpdate.java @@ -10,58 +10,46 @@ ******************************************************************************/ package forestry.arboriculture.network; -import java.io.DataInputStream; -import java.io.DataOutputStream; import java.io.IOException; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; - +import forestry.arboriculture.gadgets.TileFruitPod; import forestry.arboriculture.gadgets.TileLeaves; -import forestry.core.network.ForestryPacket; -import forestry.core.network.PacketIds; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.PacketCoordinates; +import forestry.core.network.PacketId; -public class PacketRipeningUpdate extends ForestryPacket { +public class PacketRipeningUpdate extends PacketCoordinates { - private int colourFruits; - private int posX, posY, posZ; + private int value; - public PacketRipeningUpdate() { + public PacketRipeningUpdate(DataInputStreamForestry data) throws IOException { + super(data); + } + + public PacketRipeningUpdate(TileFruitPod fruitPod) { + super(PacketId.RIPENING_UPDATE, fruitPod); + value = fruitPod.getMaturity(); } public PacketRipeningUpdate(TileLeaves leaves) { - super(PacketIds.RIPENING_UPDATE); - posX = leaves.xCoord; - posY = leaves.yCoord; - posZ = leaves.zCoord; - colourFruits = leaves.getFruitColour(); + super(PacketId.RIPENING_UPDATE, leaves); + value = leaves.getFruitColour(); } @Override - public void writeData(DataOutputStream data) throws IOException { + public void writeData(DataOutputStreamForestry data) throws IOException { super.writeData(data); - - data.writeInt(posX); - data.writeInt(posY); - data.writeInt(posZ); - data.writeInt(colourFruits); + data.writeInt(value); } @Override - public void readData(DataInputStream data) throws IOException { + public void readData(DataInputStreamForestry data) throws IOException { super.readData(data); - - posX = data.readInt(); - posY = data.readInt(); - posZ = data.readInt(); - colourFruits = data.readInt(); + value = data.readInt(); } - public int getColourFruits() { - return colourFruits; - } - - public TileEntity getTarget(World world) { - return world.getTileEntity(posX, posY, posZ); + public int getValue() { + return value; } } diff --git a/src/main/java/forestry/arboriculture/network/PacketSapling.java b/src/main/java/forestry/arboriculture/network/PacketSapling.java deleted file mode 100644 index 71a50964d..000000000 --- a/src/main/java/forestry/arboriculture/network/PacketSapling.java +++ /dev/null @@ -1,16 +0,0 @@ -package forestry.arboriculture.network; - -import forestry.arboriculture.gadgets.TileSapling; -import forestry.core.network.PacketIds; - -public class PacketSapling extends PacketTreeContainer { - - public PacketSapling() { - - } - - public PacketSapling(TileSapling sapling) { - super(PacketIds.SAPLING, sapling); - } - -} diff --git a/src/main/java/forestry/arboriculture/network/PacketTreeContainer.java b/src/main/java/forestry/arboriculture/network/PacketTreeContainer.java deleted file mode 100644 index 4fafd8dc0..000000000 --- a/src/main/java/forestry/arboriculture/network/PacketTreeContainer.java +++ /dev/null @@ -1,57 +0,0 @@ -package forestry.arboriculture.network; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import forestry.api.arboriculture.ITree; -import forestry.api.genetics.IAllele; -import forestry.arboriculture.gadgets.TileTreeContainer; -import forestry.core.network.PacketCoordinates; -import forestry.plugins.PluginArboriculture; - -public class PacketTreeContainer extends PacketCoordinates { - - protected String speciesUID = ""; - - public PacketTreeContainer() { - - } - - public PacketTreeContainer(int id, TileTreeContainer treeContainer) { - super(id, treeContainer); - - ITree tree = treeContainer.getTree(); - if (tree != null) { - speciesUID = tree.getIdent(); - } - } - - @Override - public void writeData(DataOutputStream data) throws IOException { - super.writeData(data); - data.writeUTF(speciesUID); - } - - @Override - public void readData(DataInputStream data) throws IOException { - super.readData(data); - speciesUID = data.readUTF(); - } - - public boolean matchesTree(ITree tree) { - if (tree == null) { - return speciesUID.isEmpty(); - } else { - return tree.getIdent().equals(speciesUID); - } - } - - public ITree getTree() { - IAllele[] treeTemplate = PluginArboriculture.treeInterface.getTemplate(speciesUID); - if (treeTemplate != null) { - return PluginArboriculture.treeInterface.templateAsIndividual(treeTemplate); - } - return null; - } -} diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenArboriculture.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenArboriculture.java index f2b61e9a8..833745702 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenArboriculture.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenArboriculture.java @@ -65,7 +65,7 @@ public abstract class WorldGenArboriculture extends WorldGenBase { private GameProfile getOwner() { TileEntity tile = world.getTileEntity(startX, startY, startZ); if (tile instanceof TileSapling) { - return ((TileSapling) tile).getOwnerProfile(); + return ((TileSapling) tile).getOwner(); } else { return null; } diff --git a/src/main/java/forestry/core/EventHandlerCore.java b/src/main/java/forestry/core/EventHandlerCore.java index 7d3c429ca..20dc42a3c 100755 --- a/src/main/java/forestry/core/EventHandlerCore.java +++ b/src/main/java/forestry/core/EventHandlerCore.java @@ -10,12 +10,9 @@ ******************************************************************************/ package forestry.core; -import net.minecraft.item.ItemStack; - import net.minecraftforge.client.event.TextureStitchEvent; import net.minecraftforge.event.entity.player.EntityItemPickupEvent; import net.minecraftforge.event.world.WorldEvent; -import net.minecraftforge.oredict.OreDictionary; import cpw.mods.fml.common.eventhandler.Event.Result; import cpw.mods.fml.common.eventhandler.SubscribeEvent; @@ -23,7 +20,6 @@ import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import forestry.api.core.ErrorStateRegistry; -import forestry.core.interfaces.IOreDictionaryHandler; import forestry.core.interfaces.IPickupHandler; import forestry.core.interfaces.ISaveEventHandler; import forestry.core.render.TextureManager; @@ -32,11 +28,6 @@ import forestry.plugins.PluginManager; public class EventHandlerCore { public EventHandlerCore() { - for (String name : OreDictionary.getOreNames()) { - for (ItemStack ore : OreDictionary.getOres(name)) { - handleOreRegistration(name, ore); - } - } } @SubscribeEvent @@ -54,22 +45,6 @@ public class EventHandlerCore { } } - @SubscribeEvent - public void handleOreRegistration(OreDictionary.OreRegisterEvent event) { - - if (event.isCanceled()) { - return; - } - - handleOreRegistration(event.Name, event.Ore); - } - - private void handleOreRegistration(String name, ItemStack ore) { - for (IOreDictionaryHandler handler : PluginManager.dictionaryHandlers) { - handler.onOreRegistration(name, ore); - } - } - @SubscribeEvent public void handleWorldLoad(WorldEvent.Load event) { for (ISaveEventHandler handler : PluginManager.saveEventHandlers) { @@ -100,9 +75,4 @@ public class EventHandlerCore { } } - @SubscribeEvent - @SideOnly(Side.CLIENT) - public void handleTexturePostmap(TextureStitchEvent.Post event) { - } - } diff --git a/src/main/java/forestry/core/ForestryCore.java b/src/main/java/forestry/core/ForestryCore.java index b016b6271..68a8ff71d 100755 --- a/src/main/java/forestry/core/ForestryCore.java +++ b/src/main/java/forestry/core/ForestryCore.java @@ -37,9 +37,6 @@ import forestry.core.config.Defaults; import forestry.core.config.ForestryItem; import forestry.core.config.Version; import forestry.core.fluids.Fluids; -import forestry.core.gadgets.TileEngine; -import forestry.core.gadgets.TileMachine; -import forestry.core.gadgets.TileMill; import forestry.core.proxy.Proxies; import forestry.plugins.PluginManager; @@ -106,11 +103,6 @@ public class ForestryCore { // Register gui handler NetworkRegistry.INSTANCE.registerGuiHandler(basemod, new GuiHandler()); - // Register machines - GameRegistry.registerTileEntity(TileMill.class, "forestry.Grower"); - GameRegistry.registerTileEntity(TileEngine.class, "forestry.Engine"); - GameRegistry.registerTileEntity(TileMachine.class, "forestry.Machine"); - PluginManager.runInit(); } diff --git a/src/main/java/forestry/core/GuiHandler.java b/src/main/java/forestry/core/GuiHandler.java index e07e78de2..9f9a013a5 100755 --- a/src/main/java/forestry/core/GuiHandler.java +++ b/src/main/java/forestry/core/GuiHandler.java @@ -38,10 +38,10 @@ public class GuiHandler extends GuiHandlerBase { switch (GuiId.values()[cleanId]) { case AnalyzerGUI: - return new GuiAnalyzer(player.inventory, (TileAnalyzer) getTileForestry(world, x, y, z)); + return new GuiAnalyzer(player.inventory, getTileForestry(world, x, y, z, player, TileAnalyzer.class)); case NaturalistBenchGUI: - return new GuiEscritoire(player, (TileEscritoire) getTileForestry(world, x, y, z)); + return new GuiEscritoire(player, getTileForestry(world, x, y, z, player, TileEscritoire.class)); case SolderingIronGUI: ItemStack equipped = player.getCurrentEquippedItem(); @@ -73,10 +73,10 @@ public class GuiHandler extends GuiHandlerBase { switch (GuiId.values()[cleanId]) { case AnalyzerGUI: - return new ContainerAnalyzer(player.inventory, (TileAnalyzer) getTileForestry(world, x, y, z)); + return new ContainerAnalyzer(player.inventory, getTileForestry(world, x, y, z, player, TileAnalyzer.class)); case NaturalistBenchGUI: - return new ContainerEscritoire(player, (TileEscritoire) getTileForestry(world, x, y, z)); + return new ContainerEscritoire(player, getTileForestry(world, x, y, z, player, TileEscritoire.class)); case SolderingIronGUI: ItemStack equipped = player.getCurrentEquippedItem(); diff --git a/src/main/java/forestry/core/GuiHandlerBase.java b/src/main/java/forestry/core/GuiHandlerBase.java index 1192e1faf..465537173 100755 --- a/src/main/java/forestry/core/GuiHandlerBase.java +++ b/src/main/java/forestry/core/GuiHandlerBase.java @@ -25,18 +25,23 @@ import forestry.core.proxy.Proxies; public abstract class GuiHandlerBase implements IGuiHandler { - public TileForestry getTileForestry(World world, int x, int y, int z) { + public T getTileForestry(World world, int x, int y, int z, EntityPlayer player, Class tileClass) { + T tileForestry = null; try { - return (TileForestry) world.getTileEntity(x, y, z); - } catch (Exception ex) { - Proxies.log.warning("Failed to cast a tile entity to a TileForestry at " + x + "/" + y + "/" + z); + tileForestry = tileClass.cast(world.getTileEntity(x, y, z)); + } catch (ClassCastException ex) { + Proxies.log.warning("Failed to cast a tile entity to a TileForestry at " + x + '/' + y + '/' + z); } - return null; + if (tileForestry != null && !world.isRemote) { + tileForestry.sendGuiOpened(player); + } + + return tileForestry; } public GuiNaturalistInventory getNaturalistChestGui(String rootUID, EntityPlayer player, World world, int x, int y, int z, int page) { - TileNaturalistChest tile = (TileNaturalistChest) getTileForestry(world, x, y, z); + TileNaturalistChest tile = getTileForestry(world, x, y, z, player, TileNaturalistChest.class); ISpeciesRoot speciesRoot = AlleleManager.alleleRegistry.getSpeciesRoot(rootUID); return new GuiNaturalistInventory(speciesRoot, player, new ContainerNaturalistInventory(player.inventory, tile, page, 25), tile, page, 5); } @@ -44,7 +49,7 @@ public abstract class GuiHandlerBase implements IGuiHandler { public ContainerNaturalistInventory getNaturalistChestContainer(String rootUID, EntityPlayer player, World world, int x, int y, int z, int page) { ISpeciesRoot speciesRoot = AlleleManager.alleleRegistry.getSpeciesRoot(rootUID); speciesRoot.getBreedingTracker(world, player.getGameProfile()).synchToPlayer(player); - return new ContainerNaturalistInventory(player.inventory, (TileNaturalistChest) getTileForestry(world, x, y, z), page, 25); + return new ContainerNaturalistInventory(player.inventory, getTileForestry(world, x, y, z, player, TileNaturalistChest.class), page, 25); } public static int encodeGuiData(int guiId, int data) { diff --git a/src/main/java/forestry/core/circuits/ContainerSolderingIron.java b/src/main/java/forestry/core/circuits/ContainerSolderingIron.java index 77e543d6f..c150efde5 100755 --- a/src/main/java/forestry/core/circuits/ContainerSolderingIron.java +++ b/src/main/java/forestry/core/circuits/ContainerSolderingIron.java @@ -18,9 +18,9 @@ import forestry.core.gui.ContainerItemInventory; import forestry.core.gui.IGuiSelectable; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotOutput; -import forestry.core.network.PacketIds; -import forestry.core.network.PacketPayload; -import forestry.core.network.PacketUpdate; +import forestry.core.network.PacketGuiSelect; +import forestry.core.network.PacketId; +import forestry.core.network.PacketString; import forestry.core.proxy.Proxies; public class ContainerSolderingIron extends ContainerItemInventory implements IGuiSelectable { @@ -46,38 +46,26 @@ public class ContainerSolderingIron extends ContainerItemInventory getErrorStates() { ImmutableSet.Builder errorStates = ImmutableSet.builder(); diff --git a/src/main/java/forestry/core/commands/CommandSaveStats.java b/src/main/java/forestry/core/commands/CommandSaveStats.java index 2931c997f..dfbcef60b 100644 --- a/src/main/java/forestry/core/commands/CommandSaveStats.java +++ b/src/main/java/forestry/core/commands/CommandSaveStats.java @@ -115,7 +115,7 @@ public final class CommandSaveStats extends SubCommand { } } - File file = new File(Proxies.common.getForestryRoot(), "config/" + Defaults.MOD.toLowerCase(Locale.ENGLISH) + "/stats/" + player.getDisplayName() + "-" + saveHelper.getFileSuffix() + ".log"); + File file = new File(Proxies.common.getForestryRoot(), "config/" + Defaults.MOD.toLowerCase(Locale.ENGLISH) + "/stats/" + player.getDisplayName() + '-' + saveHelper.getFileSuffix() + ".log"); try { File folder = file.getParentFile(); if (folder != null && !folder.exists()) { diff --git a/src/main/java/forestry/core/config/Defaults.java b/src/main/java/forestry/core/config/Defaults.java index d071b9bba..e42e51296 100755 --- a/src/main/java/forestry/core/config/Defaults.java +++ b/src/main/java/forestry/core/config/Defaults.java @@ -100,27 +100,6 @@ public class Defaults { public static final int DEFINITION_ARBCHEST_META = 0; - // Package Ids - public static final int ID_PACKAGE_MACHINE_FERMENTER = 0; - public static final int ID_PACKAGE_MACHINE_STILL = 1; - public static final int ID_PACKAGE_MACHINE_BOTTLER = 2; - public static final int ID_PACKAGE_MACHINE_RAINTANK = 3; - public static final int ID_PACKAGE_MACHINE_GENERATOR = 4; - public static final int ID_PACKAGE_MACHINE_CARPENTER = 5; - public static final int ID_PACKAGE_MACHINE_MOISTENER = 6; - public static final int ID_PACKAGE_MACHINE_APIARY = 7; - public static final int ID_PACKAGE_MACHINE_CENTRIFUGE = 8; - public static final int ID_PACKAGE_MACHINE_SQUEEZER = 9; - public static final int ID_PACKAGE_MACHINE_ALVEARY = 10; - public static final int ID_PACKAGE_MACHINE_FABRICATOR = 11; - - public static final int ID_PACKAGE_MILL_RAINMAKER = 1; - public static final int ID_PACKAGE_MILL_APIARIST_CHEST = 3; - public static final int ID_PACKAGE_MILL_ANALYZER = 4; - public static final int ID_PACKAGE_MILL_MAILBOX = 5; - public static final int ID_PACKAGE_MILL_TRADER = 6; - public static final int ID_PACKAGE_MILL_PHILATELIST = 7; - // Item Ids public static final int SLOTS_BACKPACK_DEFAULT = 15; diff --git a/src/main/java/forestry/core/gadgets/BlockBase.java b/src/main/java/forestry/core/gadgets/BlockBase.java index c16b5ee61..664b40c25 100755 --- a/src/main/java/forestry/core/gadgets/BlockBase.java +++ b/src/main/java/forestry/core/gadgets/BlockBase.java @@ -216,7 +216,7 @@ public class BlockBase extends BlockForestry { return world.setBlockToAir(x, y, z); } - if (tile.isOwnable() && !tile.allowsRemoval(player)) { + if (tile.isOwned() && !tile.allowsRemoval(player)) { return false; } diff --git a/src/main/java/forestry/core/gadgets/BlockForestry.java b/src/main/java/forestry/core/gadgets/BlockForestry.java index 661a8a80b..67a6a5c47 100755 --- a/src/main/java/forestry/core/gadgets/BlockForestry.java +++ b/src/main/java/forestry/core/gadgets/BlockForestry.java @@ -37,7 +37,7 @@ public abstract class BlockForestry extends BlockContainer { @Override public boolean removedByPlayer(World world, EntityPlayer player, int x, int y, int z) { IOwnable tile = (IOwnable) world.getTileEntity(x, y, z); - if (!tile.isOwnable() || tile.allowsRemoval(player)) { + if (!tile.isOwned() || tile.allowsRemoval(player)) { return super.removedByPlayer(world, player, x, y, z); } else { return false; diff --git a/src/main/java/forestry/core/gadgets/BlockResource.java b/src/main/java/forestry/core/gadgets/BlockResource.java index 2aa679fef..13f17562a 100755 --- a/src/main/java/forestry/core/gadgets/BlockResource.java +++ b/src/main/java/forestry/core/gadgets/BlockResource.java @@ -73,6 +73,11 @@ public class BlockResource extends Block { return world.getBlockMetadata(x, y, z); } + @Override + public int damageDropped(int meta) { + return meta; + } + // / CREATIVE INVENTORY @SuppressWarnings({"rawtypes", "unchecked"}) @Override diff --git a/src/main/java/forestry/core/gadgets/Engine.java b/src/main/java/forestry/core/gadgets/Engine.java index 28c297eb5..5c5bb201f 100755 --- a/src/main/java/forestry/core/gadgets/Engine.java +++ b/src/main/java/forestry/core/gadgets/Engine.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.gadgets; +import java.io.IOException; + import net.minecraft.entity.EntityLivingBase; import net.minecraft.inventory.Container; import net.minecraft.inventory.ICrafting; @@ -20,44 +22,22 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; +import forestry.apiculture.network.PacketActiveUpdate; import forestry.core.EnumErrorCode; import forestry.core.TemperatureState; import forestry.core.config.Defaults; -import forestry.core.network.PacketPayload; +import forestry.core.interfaces.IActivatable; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.proxy.Proxies; import forestry.core.utils.BlockUtil; import forestry.energy.EnergyManager; import cofh.api.energy.IEnergyConnection; -public abstract class Engine extends TileBase implements IEnergyConnection { +public abstract class Engine extends TileBase implements IEnergyConnection, IActivatable { - @Override - public PacketPayload getPacketPayload() { - PacketPayload payload = new PacketPayload(3, 1, 0); - - if (this.isActive) { - payload.intPayload[0] = 1; - } else { - payload.intPayload[0] = 0; - } - payload.intPayload[1] = energyManager.toPacketInt(); - payload.intPayload[2] = heat; - - payload.floatPayload[0] = pistonSpeedServer; - return payload; - } - - @Override - public void fromPacketPayload(PacketPayload payload) { - - isActive = payload.intPayload[0] > 0; - energyManager.fromPacketInt(payload.intPayload[1]); - heat = payload.intPayload[2]; - - pistonSpeedServer = payload.floatPayload[0]; - } - - public boolean isActive = false; // Used for smp. + public boolean active = false; // Used for smp. /** * Indicates whether the piston is receding from or approaching the * combustion chamber @@ -118,7 +98,7 @@ public abstract class Engine extends TileBase implements IEnergyConnection { stagePiston = 0; progress = 0; } - } else if (this.isActive) { + } else if (this.active) { stagePiston = 1; } } @@ -180,13 +160,21 @@ public abstract class Engine extends TileBase implements IEnergyConnection { } } - private void setActive(boolean isActive) { - if (this.isActive == isActive) { + @Override + public boolean isActive() { + return active; + } + + @Override + public void setActive(boolean active) { + if (this.active == active) { return; } + this.active = active; - this.isActive = isActive; - setNeedsNetworkUpdate(); + if (!worldObj.isRemote) { + Proxies.net.sendNetworkPacket(new PacketActiveUpdate(this)); + } } /* INTERACTION */ @@ -296,6 +284,25 @@ public abstract class Engine extends TileBase implements IEnergyConnection { nbt.setBoolean("ForceCooldown", forceCooldown); } + /* NETWORK */ + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeBoolean(active); + data.writeInt(heat); + data.writeFloat(pistonSpeedServer); + energyManager.writeData(data); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + active = data.readBoolean(); + heat = data.readInt(); + pistonSpeedServer = data.readFloat(); + energyManager.readData(data); + } + /* SMP GUI */ public abstract void getGUINetworkData(int i, int j); diff --git a/src/main/java/forestry/core/gadgets/Mill.java b/src/main/java/forestry/core/gadgets/Mill.java index 270b2d445..505b27f7f 100755 --- a/src/main/java/forestry/core/gadgets/Mill.java +++ b/src/main/java/forestry/core/gadgets/Mill.java @@ -10,7 +10,10 @@ ******************************************************************************/ package forestry.core.gadgets; -import forestry.core.network.PacketPayload; +import java.io.IOException; + +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; public abstract class Mill extends TileBase { @@ -34,21 +37,19 @@ public abstract class Mill extends TileBase { } @Override - public PacketPayload getPacketPayload() { - PacketPayload payload = new PacketPayload(2, 1, 0); - payload.intPayload[0] = charge; - payload.intPayload[1] = stage; - - payload.floatPayload[0] = speed; - return payload; + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeInt(charge); + data.writeFloat(speed); + data.writeInt(stage); } @Override - public void fromPacketPayload(PacketPayload payload) { - charge = payload.intPayload[0]; - stage = payload.intPayload[1]; - - speed = payload.floatPayload[0]; + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + charge = data.readInt(); + speed = data.readFloat(); + stage = data.readInt(); } private void update(boolean isSimulating) { diff --git a/src/main/java/forestry/core/gadgets/NaturalistGame.java b/src/main/java/forestry/core/gadgets/NaturalistGame.java index 4f25ac960..ad5e2864c 100755 --- a/src/main/java/forestry/core/gadgets/NaturalistGame.java +++ b/src/main/java/forestry/core/gadgets/NaturalistGame.java @@ -10,8 +10,11 @@ ******************************************************************************/ package forestry.core.gadgets; +import java.io.IOException; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; +import java.util.List; import java.util.Random; import net.minecraft.inventory.IInventory; @@ -23,14 +26,17 @@ import forestry.api.core.INBTTagable; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IIndividual; import forestry.api.genetics.ISpeciesRoot; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IStreamable; import forestry.core.utils.StringUtil; import forestry.core.utils.Utils; -public class NaturalistGame implements INBTTagable { +public class NaturalistGame implements INBTTagable, IStreamable { public static final int BOUNTY_MAX = 16; - public static class GameToken implements INBTTagable { + public static class GameToken implements INBTTagable, IStreamable { private static final String[] OVERLAY_NONE = new String[0]; private static final String[] OVERLAY_FAILED = new String[]{"errors/errored"}; @@ -41,6 +47,10 @@ public class NaturalistGame implements INBTTagable { protected boolean isProbed = false; protected boolean isRevealed = false; + public GameToken() { + + } + public GameToken(ItemStack tokenStack) { this.tokenStack = tokenStack; } @@ -73,6 +83,23 @@ public class NaturalistGame implements INBTTagable { } } + /* NETWORK */ + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + data.writeBoolean(isFailed); + data.writeBoolean(isProbed); + data.writeBoolean(isRevealed); + data.writeItemStack(tokenStack); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + isFailed = data.readBoolean(); + isProbed = data.readBoolean(); + isRevealed = data.readBoolean(); + tokenStack = data.readItemStack(); + } + public boolean isVisible() { return isRevealed; } @@ -163,6 +190,29 @@ public class NaturalistGame implements INBTTagable { lastUpdate = System.currentTimeMillis(); } + /* NETWORK */ + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + data.writeBoolean(isEnded); + data.writeInt(bountyLevel); + data.writeLong(lastUpdate); + + List gameTokensList = gameTokens == null ? null : Arrays.asList(gameTokens); + data.writeStreamables(gameTokensList); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + isEnded = data.readBoolean(); + bountyLevel = data.readInt(); + lastUpdate = data.readLong(); + + List gameTokensList = data.readStreamables(GameToken.class); + if (gameTokensList != null) { + this.gameTokens = gameTokensList.toArray(new GameToken[gameTokensList.size()]); + } + } + /* INTERACTION */ public void initialize(ItemStack specimen) { IIndividual individual = AlleleManager.alleleRegistry.getIndividual(specimen); @@ -174,7 +224,11 @@ public class NaturalistGame implements INBTTagable { if (boardSize % 2 != 0) { boardSize = Math.round((float) boardSize / 2) * 2; } - boardSize = boardSize <= 22 ? boardSize >= 6 ? boardSize : 6 : 22; + if (boardSize > 22) { + boardSize = 22; + } else if (boardSize < 6) { + boardSize = 6; + } isEnded = false; bountyLevel = BOUNTY_MAX; @@ -284,8 +338,9 @@ public class NaturalistGame implements INBTTagable { continue; } - gameTokens[tokenIndices[processedTokens]].isProbed = true; - gameTokens[tokenIndices[processedTokens]].isRevealed = true; + GameToken token = gameTokens[tokenIndices[processedTokens]]; + token.isProbed = true; + token.isRevealed = true; processedTokens++; if (processedTokens >= tokenIndices.length) { @@ -296,32 +351,34 @@ public class NaturalistGame implements INBTTagable { lastUpdate = System.currentTimeMillis(); } - public void choose(int tokenIndex) { + public void choose(final int tokenIndex) { if (isEnded) { return; } if (gameTokens == null || tokenIndex >= gameTokens.length) { return; } - if (gameTokens[tokenIndex].isRevealed && !gameTokens[tokenIndex].isProbed) { + + GameToken token = gameTokens[tokenIndex]; + if (token.isRevealed && !token.isProbed) { return; } hideProbedTokens(); - Collection singles = getRevealedSingles(gameTokens[tokenIndex]); + Collection singles = getRevealedSingles(token); if (singles.size() > 0) { boolean matched = false; for (GameToken single : singles) { - if (single.matches(gameTokens[tokenIndex])) { + if (single.matches(token)) { matched = true; break; } } if (!matched) { - gameTokens[tokenIndex].isFailed = true; + token.isFailed = true; } } - gameTokens[tokenIndex].isRevealed = true; + token.isRevealed = true; checkGameEnd(); lastUpdate = System.currentTimeMillis(); } @@ -393,10 +450,7 @@ public class NaturalistGame implements INBTTagable { ArrayList singles = new ArrayList(); for (GameToken token : gameTokens) { - if (!token.isRevealed) { - continue; - } - if (token == exclude) { + if (!token.isRevealed || token == exclude) { continue; } @@ -420,27 +474,20 @@ public class NaturalistGame implements INBTTagable { } /* RETRIEVAL */ - public int getBoardSize() { - return gameTokens != null ? gameTokens.length : 0; - } - public int getSampleSize() { if (gameTokens == null) { return 0; } int samples = gameTokens.length / 4; - return samples >= 2 ? samples : 2; + return Math.max(samples, 2); } public GameToken getToken(int index) { - return gameTokens != null ? index < gameTokens.length ? gameTokens[index] : null : null; - } - - public void setToken(int index, NBTTagCompound nbttagcompound) { - if (gameTokens == null) { - gameTokens = new GameToken[24]; + if (gameTokens != null && index < gameTokens.length) { + return gameTokens[index]; } - gameTokens[index] = new GameToken(nbttagcompound); + + return null; } } diff --git a/src/main/java/forestry/core/gadgets/StructureLogic.java b/src/main/java/forestry/core/gadgets/StructureLogic.java index 345f68de4..5254f28aa 100755 --- a/src/main/java/forestry/core/gadgets/StructureLogic.java +++ b/src/main/java/forestry/core/gadgets/StructureLogic.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.core.gadgets; -import java.util.HashMap; +import java.util.EnumMap; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; @@ -32,7 +32,7 @@ public abstract class StructureLogic implements IStructureLogic { protected Schemata[] schematas; protected short activeSchemata = -1; protected boolean isRotated = false; - protected HashMap metaOnValid = new HashMap(); + protected EnumMap metaOnValid = new EnumMap(EnumStructureBlock.class); public StructureLogic(String uid, ITileStructure structure) { this.uid = uid; diff --git a/src/main/java/forestry/core/gadgets/TileAnalyzer.java b/src/main/java/forestry/core/gadgets/TileAnalyzer.java index 2f2eaf0fd..3e7d06b21 100755 --- a/src/main/java/forestry/core/gadgets/TileAnalyzer.java +++ b/src/main/java/forestry/core/gadgets/TileAnalyzer.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.core.gadgets; +import java.io.IOException; import java.util.HashSet; import java.util.Set; @@ -38,15 +39,15 @@ import forestry.core.fluids.FluidHelper; import forestry.core.fluids.Fluids; import forestry.core.fluids.TankManager; import forestry.core.fluids.tanks.FilteredTank; -import forestry.core.interfaces.IErrorSource; import forestry.core.interfaces.ILiquidTankContainer; import forestry.core.inventory.InvTools; import forestry.core.inventory.TileInventoryAdapter; import forestry.core.inventory.wrappers.IInvSlot; import forestry.core.inventory.wrappers.InventoryIterator; import forestry.core.inventory.wrappers.InventoryMapper; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.GuiId; -import forestry.core.network.PacketPayload; import forestry.core.utils.GeneticsUtil; import forestry.core.utils.GuiUtil; @@ -197,30 +198,33 @@ public class TileAnalyzer extends TilePowered implements ISidedInventory, ILiqui } /* Network */ - public PacketPayload getPacketPayload() { + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); ItemStack displayStack = getIndividualOnDisplay(); if (displayStack == null) { - return null; + data.writeBoolean(false); + } else { + data.writeBoolean(true); + + IIndividual displayIndividual = AlleleManager.alleleRegistry.getIndividual(displayStack); + int type = BeeManager.beeRoot.getType(displayStack).ordinal(); + + data.writeUTF(displayIndividual.getIdent()); + data.writeShort(type); + data.writeShort(displayStack.stackSize); } - - IIndividual displayIndividual = AlleleManager.alleleRegistry.getIndividual(displayStack); - int type = BeeManager.beeRoot.getType(displayStack).ordinal(); - - PacketPayload payload = new PacketPayload(); - payload.stringPayload = new String[1]; - payload.shortPayload = new short[2]; - payload.stringPayload[0] = displayIndividual.getIdent(); - payload.shortPayload[0] = (short) type; - payload.shortPayload[1] = (short) displayStack.stackSize; - return payload; } - public void fromPacketPayload(PacketPayload payload) { + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + ItemStack newIndividualOnDisplay = null; - if (!payload.isEmpty()) { - String individualUID = payload.stringPayload[0]; - int type = payload.shortPayload[0]; - int stackSize = payload.shortPayload[1]; + if (data.readBoolean()) { + String individualUID = data.readUTF(); + int type = data.readShort(); + int stackSize = data.readShort(); IAllele[] template = BeeManager.beeRoot.getTemplate(individualUID); IIndividual individual = BeeManager.beeRoot.templateAsIndividual(template); diff --git a/src/main/java/forestry/core/gadgets/TileBase.java b/src/main/java/forestry/core/gadgets/TileBase.java index 4179262b6..76e01aaf0 100755 --- a/src/main/java/forestry/core/gadgets/TileBase.java +++ b/src/main/java/forestry/core/gadgets/TileBase.java @@ -13,31 +13,14 @@ package forestry.core.gadgets; import net.minecraft.entity.player.EntityPlayer; import forestry.core.interfaces.IHintSource; -import forestry.core.network.PacketPayload; -import forestry.core.proxy.Proxies; public abstract class TileBase extends TileForestry implements IHintSource { - @Override - public boolean isOwnable() { - return true; - } - /* UPDATING */ @Override public void initialize() { } - /* NETWORK */ - @Override - public PacketPayload getPacketPayload() { - return null; - } - - @Override - public void fromPacketPayload(PacketPayload payload) { - } - /* INTERACTION */ public abstract void openGui(EntityPlayer player, TileBase tile); diff --git a/src/main/java/forestry/core/gadgets/TileEscritoire.java b/src/main/java/forestry/core/gadgets/TileEscritoire.java index f3d3cebc2..227d23947 100755 --- a/src/main/java/forestry/core/gadgets/TileEscritoire.java +++ b/src/main/java/forestry/core/gadgets/TileEscritoire.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.gadgets; +import java.io.IOException; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; @@ -24,11 +26,10 @@ import forestry.core.interfaces.ICrafter; import forestry.core.interfaces.IRenderableMachine; import forestry.core.inventory.InvTools; import forestry.core.inventory.TileInventoryAdapter; -import forestry.core.network.ForestryPacket; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.GuiId; -import forestry.core.network.PacketIds; -import forestry.core.network.PacketTileNBT; -import forestry.core.network.PacketTileUpdate; +import forestry.core.network.PacketTileStream; import forestry.core.proxy.Proxies; import forestry.core.utils.EnumTankLevel; import forestry.core.utils.GeneticsUtil; @@ -56,13 +57,6 @@ public class TileEscritoire extends TileBase implements ISidedInventory, IRender } /* SAVING & LOADING */ - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - - game.writeToNBT(nbttagcompound); - } - @Override public void readFromNBT(NBTTagCompound nbttagcompound) { super.readFromNBT(nbttagcompound); @@ -70,6 +64,13 @@ public class TileEscritoire extends TileBase implements ISidedInventory, IRender game.readFromNBT(nbttagcompound); } + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + + game.writeToNBT(nbttagcompound); + } + /* GAME */ public NaturalistGame getGame() { return game; @@ -109,19 +110,21 @@ public class TileEscritoire extends TileBase implements ISidedInventory, IRender } /* NETWORK */ - @Override - public void fromPacket(ForestryPacket packetRaw) { - if (packetRaw instanceof PacketTileUpdate) { - super.fromPacket(packetRaw); - return; - } - PacketTileNBT packet = (PacketTileNBT) packetRaw; - readFromNBT(packet.getTagCompound()); + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + game.writeData(data); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + game.readData(data); } public void sendBoard(EntityPlayer player) { - Proxies.net.sendToPlayer(new PacketTileNBT(PacketIds.TILE_NBT, this), player); + Proxies.net.sendToPlayer(new PacketTileStream(this), player); } @Override diff --git a/src/main/java/forestry/core/gadgets/TileForestry.java b/src/main/java/forestry/core/gadgets/TileForestry.java index d7e3670c7..c5abd33ab 100755 --- a/src/main/java/forestry/core/gadgets/TileForestry.java +++ b/src/main/java/forestry/core/gadgets/TileForestry.java @@ -12,10 +12,12 @@ package forestry.core.gadgets; import com.google.common.collect.ImmutableSet; +import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.Random; import java.util.Set; +import java.util.UUID; import net.minecraft.block.Block; import net.minecraft.entity.EntityLivingBase; @@ -35,18 +37,22 @@ import net.minecraftforge.common.util.ForgeDirection; import cpw.mods.fml.common.Optional; +import forestry.api.core.ErrorStateRegistry; import forestry.api.core.IErrorState; import forestry.core.config.Config; import forestry.core.config.Defaults; +import forestry.core.fluids.TankManager; import forestry.core.interfaces.IErrorSource; import forestry.core.interfaces.IFilterSlotDelegate; +import forestry.core.interfaces.ILiquidTankContainer; import forestry.core.interfaces.IRestrictedAccess; import forestry.core.inventory.FakeInventoryAdapter; import forestry.core.inventory.IInventoryAdapter; -import forestry.core.network.ForestryPacket; -import forestry.core.network.INetworkedEntity; -import forestry.core.network.PacketPayload; -import forestry.core.network.PacketTileUpdate; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IStreamable; +import forestry.core.network.PacketTileGuiOpened; +import forestry.core.network.PacketTileStream; import forestry.core.proxy.Proxies; import forestry.core.utils.AdjacentTileCache; import forestry.core.utils.EnumAccess; @@ -59,15 +65,17 @@ import buildcraft.api.statements.ITriggerInternal; import buildcraft.api.statements.ITriggerProvider; @Optional.Interface(iface = "buildcraft.api.statements.ITriggerProvider", modid = "BuildCraftAPI|statements") -public abstract class TileForestry extends TileEntity implements INetworkedEntity, IRestrictedAccess, IErrorSource, ITriggerProvider, ISidedInventory, IFilterSlotDelegate { +public abstract class TileForestry extends TileEntity implements IStreamable, IRestrictedAccess, IErrorSource, ITriggerProvider, ISidedInventory, IFilterSlotDelegate { private static final Random rand = new Random(); - protected final AdjacentTileCache tileCache = new AdjacentTileCache(this); - protected boolean isInited = false; private IInventoryAdapter inventory = FakeInventoryAdapter.instance(); private int tickCount = rand.nextInt(256); private boolean needsNetworkUpdate = false; + private ForgeDirection orientation = ForgeDirection.WEST; + + protected final AdjacentTileCache tileCache = new AdjacentTileCache(this); + protected boolean isInited = false; public AdjacentTileCache getTileCache() { return tileCache; @@ -184,37 +192,84 @@ public abstract class TileForestry extends TileEntity implements INetworkedEntit } @Override - public Packet getDescriptionPacket() { - PacketTileUpdate packet = new PacketTileUpdate(this); + public final Packet getDescriptionPacket() { + PacketTileStream packet = new PacketTileStream(this); return packet.getPacket(); } /* INetworkedEntity */ - @Override - public void sendNetworkUpdate() { - PacketTileUpdate packet = new PacketTileUpdate(this); - Proxies.net.sendNetworkPacket(packet, xCoord, yCoord, zCoord); + public final void sendNetworkUpdate() { + PacketTileStream packet = new PacketTileStream(this); + Proxies.net.sendNetworkPacket(packet); } - @Override - public void fromPacket(ForestryPacket packetRaw) { - PacketTileUpdate packet = (PacketTileUpdate) packetRaw; - if (orientation != packet.getOrientation()) { - orientation = packet.getOrientation(); - worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); + public void writeData(DataOutputStreamForestry data) throws IOException { + data.writeByte(orientation.ordinal()); + + if (this instanceof ILiquidTankContainer) { + TankManager tankManager = ((ILiquidTankContainer) this).getTankManager(); + if (tankManager != null) { + tankManager.writePacketData(data); + } } - - errorStates.clear(); - errorStates.addAll(packet.getErrorStates()); - - owner = packet.getOwner(); - access = packet.getAccess(); - fromPacketPayload(packet.payload); } - public abstract PacketPayload getPacketPayload(); + public void readData(DataInputStreamForestry data) throws IOException { + orientation = ForgeDirection.getOrientation(data.readByte()); - public abstract void fromPacketPayload(PacketPayload payload); + if (this instanceof ILiquidTankContainer) { + TankManager tankManager = ((ILiquidTankContainer) this).getTankManager(); + if (tankManager != null) { + tankManager.readPacketData(data); + } + } + } + + public final void writeErrorData(DataOutputStreamForestry data) throws IOException { + data.writeShort(errorStates.size()); + for (IErrorState errorState : errorStates) { + data.writeShort(errorState.getID()); + } + } + + public final void readErrorData(DataInputStreamForestry data) throws IOException { + errorStates.clear(); + + short errorStateCount = data.readShort(); + for (int i = 0; i < errorStateCount; i++) { + short errorStateId = data.readShort(); + IErrorState errorState = ErrorStateRegistry.getErrorState(errorStateId); + errorStates.add(errorState); + } + } + + public final void sendGuiOpened(EntityPlayer player) { + PacketTileGuiOpened packet = new PacketTileGuiOpened(this); + Proxies.net.sendToPlayer(packet, player); + } + + public final void writeGuiData(DataOutputStreamForestry data) throws IOException { + writeErrorData(data); + + if (owner == null) { + data.writeByte(-1); + } else { + data.writeByte(access.ordinal()); + data.writeLong(owner.getId().getMostSignificantBits()); + data.writeLong(owner.getId().getLeastSignificantBits()); + data.writeUTF(owner.getName()); + } + } + + public final void readGuiData(DataInputStreamForestry data) throws IOException { + readErrorData(data); + + byte accessOrdinal = data.readByte(); + if (accessOrdinal >= 0) { + access = EnumAccess.values()[accessOrdinal]; + owner = new GameProfile(new UUID(data.readLong(), data.readLong()), data.readUTF()); + } + } public void onRemoval() { } @@ -233,17 +288,11 @@ public abstract class TileForestry extends TileEntity implements INetworkedEntit } // / REDSTONE INFO - - /** - * @return true if tile is activated by redstone current. - */ public boolean isRedstoneActivated() { return worldObj.isBlockIndirectlyGettingPowered(xCoord, yCoord, zCoord); } // / ORIENTATION - private ForgeDirection orientation = ForgeDirection.WEST; - public ForgeDirection getOrientation() { return this.orientation; } @@ -253,7 +302,7 @@ public abstract class TileForestry extends TileEntity implements INetworkedEntit return; } this.orientation = orientation; - this.sendNetworkUpdate(); + this.setNeedsNetworkUpdate(); } protected final void setNeedsNetworkUpdate() { @@ -265,29 +314,20 @@ public abstract class TileForestry extends TileEntity implements INetworkedEntit public final boolean setErrorCondition(boolean condition, IErrorState errorState) { if (condition) { - if (errorStates.add(errorState)) { - setNeedsNetworkUpdate(); - } + errorStates.add(errorState); } else { - if (errorStates.remove(errorState)) { - setNeedsNetworkUpdate(); - } + errorStates.remove(errorState); } return condition; } @Deprecated protected final void addErrorState(IErrorState state) { - if (errorStates.add(state)) { - setNeedsNetworkUpdate(); - } + errorStates.add(state); } @Deprecated protected final void removeErrorStates() { - if (errorStates.size() > 0) { - setNeedsNetworkUpdate(); - } errorStates.clear(); } @@ -310,7 +350,7 @@ public abstract class TileForestry extends TileEntity implements INetworkedEntit @Override public final boolean allowsRemoval(EntityPlayer player) { - return Config.disablePermissions || getAccess() == EnumAccess.SHARED || !isOwnable() || !isOwned() || isOwner(player) || Proxies.common.isOp(player); + return Config.disablePermissions || getAccess() == EnumAccess.SHARED || !isOwned() || isOwner(player) || Proxies.common.isOp(player); } @Override @@ -332,18 +372,13 @@ public abstract class TileForestry extends TileEntity implements INetworkedEntit return access; } - @Override - public boolean isOwnable() { - return false; - } - @Override public boolean isOwned() { return owner != null; } @Override - public GameProfile getOwnerProfile() { + public GameProfile getOwner() { return owner; } @@ -371,14 +406,14 @@ public abstract class TileForestry extends TileEntity implements INetworkedEntit int ordinal = (access.ordinal() + 1) % EnumAccess.values().length; access = EnumAccess.values()[ordinal]; if (!this.worldObj.isRemote) { - sendNetworkUpdate(); - } + sendGuiOpened(player); - boolean canPipesConnect = allowsPipeConnections(); - if (couldPipesConnect != canPipesConnect) { - // pipes connected to this need to update - worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, blockType); - markDirty(); + boolean canPipesConnect = allowsPipeConnections(); + if (couldPipesConnect != canPipesConnect) { + // pipes connected to this need to update + worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, blockType); + markDirty(); + } } return true; @@ -391,7 +426,7 @@ public abstract class TileForestry extends TileEntity implements INetworkedEntit */ public String getUnlocalizedName() { String blockUnlocalizedName = getBlockType().getUnlocalizedName().replace("tile.for.", ""); - return blockUnlocalizedName + "." + getBlockMetadata() + ".name"; + return blockUnlocalizedName + '.' + getBlockMetadata() + ".name"; } /* INVENTORY BASICS */ @@ -418,7 +453,7 @@ public abstract class TileForestry extends TileEntity implements INetworkedEntit } @Override - public final ItemStack decrStackSize(int slotIndex, int amount) { + public ItemStack decrStackSize(int slotIndex, int amount) { return getInternalInventory().decrStackSize(slotIndex, amount); } @@ -428,7 +463,7 @@ public abstract class TileForestry extends TileEntity implements INetworkedEntit } @Override - public final void setInventorySlotContents(int slotIndex, ItemStack itemstack) { + public void setInventorySlotContents(int slotIndex, ItemStack itemstack) { getInternalInventory().setInventorySlotContents(slotIndex, itemstack); } diff --git a/src/main/java/forestry/core/gadgets/TileMachine.java b/src/main/java/forestry/core/gadgets/TileMachine.java deleted file mode 100755 index e2cca1f57..000000000 --- a/src/main/java/forestry/core/gadgets/TileMachine.java +++ /dev/null @@ -1,259 +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.gadgets; - -import java.util.HashMap; - -import net.minecraft.block.Block; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; - -import forestry.api.core.EnumHumidity; -import forestry.api.core.EnumTemperature; -import forestry.core.config.Defaults; -import forestry.core.config.ForestryBlock; -import forestry.core.interfaces.IClimatised; -import forestry.core.interfaces.IHintSource; -import forestry.core.network.PacketPayload; -import forestry.core.proxy.Proxies; -import forestry.core.utils.EnumTankLevel; -import forestry.plugins.PluginApiculture; -import forestry.plugins.PluginEnergy; -import forestry.plugins.PluginFactory; -import forestry.plugins.PluginIC2; -import forestry.plugins.PluginMail; - -public abstract class TileMachine extends TileForestry implements IClimatised, IHintSource { - - public TileMachine() { - } - - // / IHINTSOURCE - @Override - public boolean hasHints() { - return false; - } - - @Override - public String[] getHints() { - return null; - } - - // / ICLIMATISED - @Override - public boolean isClimatized() { - return false; - } - - @Override - public EnumTemperature getTemperature() { - return EnumTemperature.NORMAL; - } - - @Override - public EnumHumidity getHumidity() { - return EnumHumidity.NORMAL; - } - - @Override - public float getExactTemperature() { - return 0; - } - - @Override - public float getExactHumidity() { - return 0; - } - - // / IOWNABLE - @Override - public boolean isOwnable() { - return true; - } - - int oldkind; - NBTTagCompound olddata; - - @Override - public void initialize() { - - if (!Proxies.common.isSimulating(worldObj)) { - return; - } - - if (olddata != null) { - legacyConversion(oldkind, olddata); - } - - } - - /** - * Read saved data - */ - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - - super.readFromNBT(nbttagcompound); - - oldkind = nbttagcompound.getInteger("Kind"); - olddata = nbttagcompound; - - } - - private HashMap> definitionMap; - - private void createDefinitionMap() { - definitionMap = new HashMap>(); - - HashMap machineMap = new HashMap(); - machineMap.put(Defaults.ID_PACKAGE_MACHINE_BOTTLER, PluginFactory.definitionBottler); - machineMap.put(Defaults.ID_PACKAGE_MACHINE_CARPENTER, PluginFactory.definitionCarpenter); - machineMap.put(Defaults.ID_PACKAGE_MACHINE_CENTRIFUGE, PluginFactory.definitionCentrifuge); - machineMap.put(Defaults.ID_PACKAGE_MACHINE_FABRICATOR, PluginFactory.definitionFabricator); - machineMap.put(Defaults.ID_PACKAGE_MACHINE_FERMENTER, PluginFactory.definitionFermenter); - machineMap.put(Defaults.ID_PACKAGE_MACHINE_MOISTENER, PluginFactory.definitionMoistener); - machineMap.put(Defaults.ID_PACKAGE_MACHINE_RAINTANK, PluginFactory.definitionRaintank); - machineMap.put(Defaults.ID_PACKAGE_MACHINE_SQUEEZER, PluginFactory.definitionSqueezer); - machineMap.put(Defaults.ID_PACKAGE_MACHINE_STILL, PluginFactory.definitionStill); - machineMap.put(Defaults.ID_PACKAGE_MACHINE_APIARY, PluginApiculture.definitionApiary); - if (PluginIC2.instance.isAvailable()) { - machineMap.put(Defaults.ID_PACKAGE_MACHINE_GENERATOR, PluginIC2.definitionGenerator); - } - definitionMap.put(ForestryBlock.factoryTESR.block(), machineMap); - - HashMap millMap = new HashMap(); - millMap.put(Defaults.ID_PACKAGE_MILL_MAILBOX, PluginMail.definitionMailbox); - millMap.put(Defaults.ID_PACKAGE_MILL_TRADER, PluginMail.definitionTradestation); - millMap.put(Defaults.ID_PACKAGE_MILL_PHILATELIST, PluginMail.definitionPhilatelist); - millMap.put(Defaults.ID_PACKAGE_MILL_APIARIST_CHEST, PluginApiculture.definitionChest); - millMap.put(Defaults.ID_PACKAGE_MILL_ANALYZER, PluginApiculture.definitionAnalyzer); - millMap.put(Defaults.ID_PACKAGE_MILL_RAINMAKER, PluginFactory.definitionRainmaker); - definitionMap.put(ForestryBlock.factoryPlain.block(), millMap); - - HashMap engineMap = new HashMap(); - engineMap.put(0, PluginEnergy.definitionEngineBronze); - engineMap.put(1, PluginEnergy.definitionEngineCopper); - if (PluginIC2.instance.isAvailable()) { - engineMap.put(2, PluginIC2.definitionEngineTin); - } - definitionMap.put(ForestryBlock.engine.block(), engineMap); - - } - - private void legacyConversion(int kind, NBTTagCompound nbttagcompound) { - if (definitionMap == null) { - createDefinitionMap(); - } - - Block block = worldObj.getBlock(xCoord, yCoord, zCoord); - if (!definitionMap.containsKey(block) || !definitionMap.get(block).containsKey(kind)) { - commitSeppuku(block, kind); - return; - } - - MachineDefinition definition = definitionMap.get(block).get(kind); - Proxies.log.info("Converting obsolete gadget %s-%s to new '%s' %s-%s", block.getUnlocalizedName(), kind, definition.teIdent, definition.block.getUnlocalizedName(), definition.meta); - - Proxies.log.info("Removing old tile entity..."); - worldObj.removeTileEntity(xCoord, yCoord, zCoord); - worldObj.setBlockToAir(xCoord, yCoord, zCoord); - Proxies.log.info("Setting to new block id..."); - worldObj.setBlock(xCoord, yCoord, zCoord, definition.block, definition.meta, Defaults.FLAG_BLOCK_SYNCH); - TileEntity tile = worldObj.getTileEntity(xCoord, yCoord, zCoord); - if (tile == null) { - throw new RuntimeException("Failed to set new block tile entity!"); - } else if (tile.getClass() != definition.teClass) { - throw new RuntimeException(String.format("Converted tile entity was '%s' instead of expected '%s'", tile.getClass(), definition.teClass)); - } - Proxies.log.info("Refreshing converted tile entity %s with nbt data...", tile.getClass()); - if (nbttagcompound.hasKey("Machine")) { - tile.readFromNBT(complementNBT(nbttagcompound, nbttagcompound.getCompoundTag("Machine"), definition)); - } else { - tile.readFromNBT(nbttagcompound); - } - } - - private NBTTagCompound complementNBT(NBTTagCompound parent, NBTTagCompound inner, MachineDefinition definition) { - - inner.setString("id", definition.teIdent); - inner.setInteger("x", this.xCoord); - inner.setInteger("y", this.yCoord); - inner.setInteger("z", this.zCoord); - - inner.setInteger("Access", parent.getInteger("Access")); - if (parent.hasKey("Owner")) { - inner.setString("Owner", parent.getString("Owner")); - } - if (parent.hasKey("Orientation")) { - inner.setInteger("Orientation", parent.getInteger("Orientation")); - } - - return inner; - } - - private void commitSeppuku(Block block, int meta) { - Proxies.log.info("Obsolete gadget %s-%s has no replacement defined. Committing sepukku.", block.getUnlocalizedName(), meta); - worldObj.removeTileEntity(xCoord, yCoord, zCoord); - worldObj.setBlockToAir(xCoord, yCoord, zCoord); - } - - /** - * Write save data - */ - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - - super.writeToNBT(nbttagcompound); - - // Legacy for old fermenter with strange meta data - int kind = worldObj.getBlockMetadata(xCoord, yCoord, zCoord); - nbttagcompound.setInteger("Kind", kind); - - /* - * if (machine != null) { NBTTagCompound NBTmachine = new NBTTagCompound(); machine.writeToNBT(NBTmachine); nbttagcompound.setTag("Machine", - * NBTmachine); } else { Proxies.log.warning("Saved a " + getClass() + " without machine."); } - */ - } - - @Override - public void validate() { - super.validate(); - } - - public boolean isWorking() { - return false; - } - - public static EnumTankLevel rateTankLevel(int scaled) { - - if (scaled < 5) { - return EnumTankLevel.EMPTY; - } else if (scaled < 30) { - return EnumTankLevel.LOW; - } else if (scaled < 60) { - return EnumTankLevel.MEDIUM; - } else if (scaled < 90) { - return EnumTankLevel.HIGH; - } else { - return EnumTankLevel.MAXIMUM; - } - } - - // INETWORKEDTILE IMPLEMENTATION - @Override - public PacketPayload getPacketPayload() { - return null; - } - - @Override - public void fromPacketPayload(PacketPayload payload) { - } -} diff --git a/src/main/java/forestry/core/gadgets/TileMill.java b/src/main/java/forestry/core/gadgets/TileMill.java deleted file mode 100755 index c28af950a..000000000 --- a/src/main/java/forestry/core/gadgets/TileMill.java +++ /dev/null @@ -1,14 +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.gadgets; - -public class TileMill extends TileMachine { -} diff --git a/src/main/java/forestry/core/genetics/BreedingTracker.java b/src/main/java/forestry/core/genetics/BreedingTracker.java index f12f3b01f..0874e37c9 100755 --- a/src/main/java/forestry/core/genetics/BreedingTracker.java +++ b/src/main/java/forestry/core/genetics/BreedingTracker.java @@ -28,7 +28,7 @@ import forestry.api.genetics.IBreedingTracker; import forestry.api.genetics.IIndividual; import forestry.api.genetics.IMutation; import forestry.api.genetics.ISpeciesRoot; -import forestry.core.network.PacketIds; +import forestry.core.network.PacketId; import forestry.core.network.PacketNBT; import forestry.core.proxy.Proxies; @@ -77,7 +77,7 @@ public abstract class BreedingTracker extends WorldSavedData implements IBreedin NBTTagCompound nbttagcompound = new NBTTagCompound(); encodeToNBT(nbttagcompound); - Proxies.net.sendToPlayer(new PacketNBT(PacketIds.GENOME_TRACKER_UPDATE, nbttagcompound), player); + Proxies.net.sendToPlayer(new PacketNBT(PacketId.GENOME_TRACKER_UPDATE, nbttagcompound), player); } /* HELPER FUNCTIONS TO PREVENT OBFUSCATION OF INTERFACE METHODS */ diff --git a/src/main/java/forestry/core/genetics/Chromosome.java b/src/main/java/forestry/core/genetics/Chromosome.java index 77a8db9f3..98bfb46ea 100755 --- a/src/main/java/forestry/core/genetics/Chromosome.java +++ b/src/main/java/forestry/core/genetics/Chromosome.java @@ -19,7 +19,6 @@ import net.minecraft.nbt.NBTTagCompound; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAllele; import forestry.api.genetics.IChromosome; -import forestry.api.genetics.ILegacyHandler; import forestry.core.proxy.Proxies; public class Chromosome implements IChromosome { @@ -69,7 +68,7 @@ public class Chromosome implements IChromosome { @Override public IAllele getActiveAllele() { if (primary == null || secondary == null) { - Proxies.log.severe("Chromosome is missing alleles"); + return null; } if (primary.isDominant()) { return primary; diff --git a/src/main/java/forestry/core/genetics/Genome.java b/src/main/java/forestry/core/genetics/Genome.java index 6886cea56..11c81fc51 100755 --- a/src/main/java/forestry/core/genetics/Genome.java +++ b/src/main/java/forestry/core/genetics/Genome.java @@ -51,6 +51,37 @@ public abstract class Genome implements IGenome { } // NBT RETRIEVAL + /** + * Quickly gets the species without loading the whole genome. + * We need this because the client uses the species for rendering. + */ + protected static IAlleleSpecies getSpeciesDirectly(ItemStack itemStack) { + NBTTagCompound nbtTagCompound = itemStack.getTagCompound(); + if (nbtTagCompound == null) { + return null; + } + + NBTTagCompound genomeNBT = nbtTagCompound.getCompoundTag("Genome"); + if (genomeNBT == null) { + return null; + } + + NBTTagList chromosomesNBT = genomeNBT.getTagList("Chromosomes", 10); + if (chromosomesNBT == null) { + return null; + } + + NBTTagCompound chromosomeNBT = chromosomesNBT.getCompoundTagAt(0); + Chromosome chromosome = Chromosome.loadChromosomeFromNBT(chromosomeNBT); + + IAllele activeAllele = chromosome.getActiveAllele(); + if (!(activeAllele instanceof IAlleleSpecies)) { + return null; + } + + return (IAlleleSpecies) activeAllele; + } + public static IChromosome getChromosome(ItemStack itemStack, IChromosomeType chromosomeType, ISpeciesRoot speciesRoot) { NBTTagCompound nbtTagCompound = itemStack.getTagCompound(); if (nbtTagCompound == null) { diff --git a/src/main/java/forestry/core/genetics/Mutation.java b/src/main/java/forestry/core/genetics/Mutation.java index 7f20e1f9f..f481d3569 100755 --- a/src/main/java/forestry/core/genetics/Mutation.java +++ b/src/main/java/forestry/core/genetics/Mutation.java @@ -46,7 +46,8 @@ public abstract class Mutation implements IMutationCustom { this.template = template; this.chance = chance; } - + + @Override public Collection getSpecialConditions() { return specialConditions; } diff --git a/src/main/java/forestry/core/genetics/MutationConditionTemperature.java b/src/main/java/forestry/core/genetics/MutationConditionTemperature.java index b819800ba..15ed9e6ab 100644 --- a/src/main/java/forestry/core/genetics/MutationConditionTemperature.java +++ b/src/main/java/forestry/core/genetics/MutationConditionTemperature.java @@ -31,7 +31,7 @@ public class MutationConditionTemperature implements IMutationCondition { @Override public float getChance(World world, int x, int y, int z, IAllele allele0, IAllele allele1, IGenome genome0, IGenome genome1) { BiomeGenBase biome = world.getWorldChunkManager().getBiomeGenAt(x, z); - EnumTemperature biomeTemperature = EnumTemperature.getFromBiome(biome); + EnumTemperature biomeTemperature = EnumTemperature.getFromBiome(biome, x, y, z); if (biomeTemperature.ordinal() < minTemperature.ordinal() || biomeTemperature.ordinal() > maxTemperature.ordinal()) { return 0; diff --git a/src/main/java/forestry/core/genetics/alleles/Allele.java b/src/main/java/forestry/core/genetics/alleles/Allele.java index ec81deb83..5ecd6c521 100644 --- a/src/main/java/forestry/core/genetics/alleles/Allele.java +++ b/src/main/java/forestry/core/genetics/alleles/Allele.java @@ -21,7 +21,6 @@ import forestry.api.arboriculture.IAlleleGrowth; import forestry.api.arboriculture.IAlleleTreeSpecies; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAllele; -import forestry.api.genetics.ILegacyHandler; import forestry.api.lepidopterology.IAlleleButterflySpecies; public abstract class Allele implements IAllele { @@ -199,138 +198,6 @@ public abstract class Allele implements IAllele { public static final Allele plantTypeNether = new AllelePlantType(EnumPlantType.Nether); public static final Allele plantTypeCrop = new AllelePlantType(EnumPlantType.Crop); - public static void setupAPI() { - // LEGACY MAPPINGS - ILegacyHandler legacy = (ILegacyHandler) AlleleManager.alleleRegistry; - - legacy.registerLegacyMapping(0, "forestry.speciesForest"); - legacy.registerLegacyMapping(1, "forestry.speciesMeadows"); - legacy.registerLegacyMapping(2, "forestry.speciesCommon"); - legacy.registerLegacyMapping(3, "forestry.speciesCultivated"); - - legacy.registerLegacyMapping(4, "forestry.speciesNoble"); - legacy.registerLegacyMapping(5, "forestry.speciesMajestic"); - legacy.registerLegacyMapping(6, "forestry.speciesImperial"); - - legacy.registerLegacyMapping(7, "forestry.speciesDiligent"); - legacy.registerLegacyMapping(8, "forestry.speciesUnweary"); - legacy.registerLegacyMapping(9, "forestry.speciesIndustrious"); - - legacy.registerLegacyMapping(10, "forestry.speciesSteadfast"); - legacy.registerLegacyMapping(11, "forestry.speciesValiant"); - legacy.registerLegacyMapping(12, "forestry.speciesHeroic"); - - legacy.registerLegacyMapping(13, "forestry.speciesSinister"); - legacy.registerLegacyMapping(14, "forestry.speciesFiendish"); - legacy.registerLegacyMapping(15, "forestry.speciesDemonic"); - - legacy.registerLegacyMapping(16, "forestry.speciesModest"); - legacy.registerLegacyMapping(17, "forestry.speciesFrugal"); - legacy.registerLegacyMapping(18, "forestry.speciesAustere"); - - legacy.registerLegacyMapping(19, "forestry.speciesTropical"); - legacy.registerLegacyMapping(20, "forestry.speciesExotic"); - legacy.registerLegacyMapping(21, "forestry.speciesEdenic"); - - legacy.registerLegacyMapping(22, "forestry.speciesEnded"); - - legacy.registerLegacyMapping(25, "forestry.speciesWintry"); - - legacy.registerLegacyMapping(28, "forestry.speciesVindictive"); - legacy.registerLegacyMapping(29, "forestry.speciesVengeful"); - legacy.registerLegacyMapping(30, "forestry.speciesAvenging"); - - legacy.registerLegacyMapping(34, "forestry.speciesLeporine"); - - legacy.registerLegacyMapping(40, "forestry.speciesRural"); - - legacy.registerLegacyMapping(43, "forestry.speciesMarshy"); - - // Flowers - legacy.registerLegacyMapping(1500, "forestry.flowersVanilla"); - legacy.registerLegacyMapping(1501, "forestry.flowersNether"); - legacy.registerLegacyMapping(1502, "forestry.flowersCacti"); - legacy.registerLegacyMapping(1503, "forestry.flowersMushrooms"); - legacy.registerLegacyMapping(1504, "forestry.flowersEnd"); - legacy.registerLegacyMapping(1505, "forestry.flowersJungle"); - legacy.registerLegacyMapping(1506, "forestry.flowersSnow"); - legacy.registerLegacyMapping(1507, "forestry.flowersWheat"); - - // Effects - legacy.registerLegacyMapping(1800, "forestry.effectNone"); - legacy.registerLegacyMapping(1801, "forestry.effectAggressive"); - legacy.registerLegacyMapping(1802, "forestry.effectHeroic"); - legacy.registerLegacyMapping(1803, "forestry.effectBeatific"); - legacy.registerLegacyMapping(1804, "forestry.effectMiasmic"); - legacy.registerLegacyMapping(1805, "forestry.effectMisanthrope"); - legacy.registerLegacyMapping(1806, "forestry.effectGlacial"); - legacy.registerLegacyMapping(1807, "forestry.effectRadioactive"); - legacy.registerLegacyMapping(1808, "forestry.effectCreeper"); - legacy.registerLegacyMapping(1809, "forestry.effectIgnition"); - legacy.registerLegacyMapping(1810, "forestry.effectExploration"); - legacy.registerLegacyMapping(1811, "forestry.effectFestiveEaster"); - - // Generic - legacy.registerLegacyMapping(1024, "forestry.boolFalse"); - legacy.registerLegacyMapping(1025, "forestry.boolTrue"); - - // Speed - legacy.registerLegacyMapping(1100, "forestry.speedSlowest"); - legacy.registerLegacyMapping(1101, "forestry.speedSlower"); - legacy.registerLegacyMapping(1102, "forestry.speedSlow"); - legacy.registerLegacyMapping(1103, "forestry.speedNorm"); - legacy.registerLegacyMapping(1104, "forestry.speedFast"); - legacy.registerLegacyMapping(1105, "forestry.speedFaster"); - legacy.registerLegacyMapping(1106, "forestry.speedFastest"); - - // Lifespan - legacy.registerLegacyMapping(1200, "forestry.lifespanShortest"); - legacy.registerLegacyMapping(1201, "forestry.lifespanShorter"); - legacy.registerLegacyMapping(1202, "forestry.lifespanShort"); - legacy.registerLegacyMapping(1203, "forestry.lifespanShortened"); - legacy.registerLegacyMapping(1204, "forestry.lifespanNormal"); - legacy.registerLegacyMapping(1205, "forestry.lifespanElongated"); - legacy.registerLegacyMapping(1206, "forestry.lifespanLong"); - legacy.registerLegacyMapping(1207, "forestry.lifespanLonger"); - legacy.registerLegacyMapping(1208, "forestry.lifespanLongest"); - - // Fertility - legacy.registerLegacyMapping(1300, "forestry.fertilityLow"); - legacy.registerLegacyMapping(1301, "forestry.fertilityNormal"); - legacy.registerLegacyMapping(1302, "forestry.fertilityHigh"); - legacy.registerLegacyMapping(1303, "forestry.fertilityMaximum"); - - // Tolerance - legacy.registerLegacyMapping(1450, "forestry.toleranceNone"); - legacy.registerLegacyMapping(1451, "forestry.toleranceBoth1"); - legacy.registerLegacyMapping(1452, "forestry.toleranceBoth2"); - legacy.registerLegacyMapping(1453, "forestry.toleranceBoth3"); - legacy.registerLegacyMapping(1454, "forestry.toleranceBoth4"); - legacy.registerLegacyMapping(1455, "forestry.toleranceBoth5"); - legacy.registerLegacyMapping(1456, "forestry.toleranceUp1"); - legacy.registerLegacyMapping(1457, "forestry.toleranceUp2"); - legacy.registerLegacyMapping(1458, "forestry.toleranceUp3"); - legacy.registerLegacyMapping(1459, "forestry.toleranceUp4"); - legacy.registerLegacyMapping(1460, "forestry.toleranceUp5"); - legacy.registerLegacyMapping(1461, "forestry.toleranceDown1"); - legacy.registerLegacyMapping(1462, "forestry.toleranceDown2"); - legacy.registerLegacyMapping(1463, "forestry.toleranceDown3"); - legacy.registerLegacyMapping(1464, "forestry.toleranceDown4"); - legacy.registerLegacyMapping(1465, "forestry.toleranceDown5"); - - // Flower growth - legacy.registerLegacyMapping(1700, "forestry.floweringSlowest"); - legacy.registerLegacyMapping(1701, "forestry.floweringSlower"); - legacy.registerLegacyMapping(1702, "forestry.floweringSlow"); - legacy.registerLegacyMapping(1710, "forestry.floweringMaximum"); - - // Territory - legacy.registerLegacyMapping(1750, "forestry.territoryDefault"); - legacy.registerLegacyMapping(1751, "forestry.territoryLarge"); - legacy.registerLegacyMapping(1752, "forestry.territoryLarger"); - legacy.registerLegacyMapping(1753, "forestry.territoryLargest"); - } - @Override public String getName() { return StatCollector.translateToLocal(getUnlocalizedName()); diff --git a/src/main/java/forestry/core/genetics/alleles/AlleleRegistry.java b/src/main/java/forestry/core/genetics/alleles/AlleleRegistry.java index c6b478e6b..f64954054 100644 --- a/src/main/java/forestry/core/genetics/alleles/AlleleRegistry.java +++ b/src/main/java/forestry/core/genetics/alleles/AlleleRegistry.java @@ -13,7 +13,6 @@ package forestry.core.genetics.alleles; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; @@ -30,14 +29,13 @@ import forestry.api.genetics.IClassification; import forestry.api.genetics.IClassification.EnumClassLevel; import forestry.api.genetics.IFruitFamily; import forestry.api.genetics.IIndividual; -import forestry.api.genetics.ILegacyHandler; import forestry.api.genetics.IMutation; import forestry.api.genetics.ISpeciesRoot; import forestry.core.config.ForestryItem; import forestry.core.genetics.Classification; import forestry.core.genetics.ItemResearchNote.EnumNoteType; -public class AlleleRegistry implements IAlleleRegistry, ILegacyHandler { +public class AlleleRegistry implements IAlleleRegistry { private static final int ALLELE_ARRAY_SIZE = 2048; @@ -104,11 +102,6 @@ public class AlleleRegistry implements IAlleleRegistry, ILegacyHandler { private final LinkedHashMap classificationMap = new LinkedHashMap(128); private final LinkedHashMap fruitMap = new LinkedHashMap(64); - private final HashMap metaMapToUID = new HashMap(); - private final HashMap uidMapToMeta = new HashMap(); - - private final HashMap legacyMap = new HashMap(); - /* * Internal HashSet of all alleleHandlers, which trigger when an allele or branch is registered */ @@ -225,21 +218,6 @@ public class AlleleRegistry implements IAlleleRegistry, ILegacyHandler { return fruitMap.get(uid); } - /* LEGACY MAPPINGS */ - @Override - public void registerLegacyMapping(int id, String uid) { - this.legacyMap.put(id, uid); - } - - @Override - public IAllele getFromLegacyMap(int id) { - if (!legacyMap.containsKey(id)) { - return null; - } - - return getAllele(legacyMap.get(id)); - } - /* ALLELE HANDLERS */ @Override public void registerAlleleHandler(IAlleleHandler handler) { diff --git a/src/main/java/forestry/core/genetics/alleles/EnumAllele.java b/src/main/java/forestry/core/genetics/alleles/EnumAllele.java index 6297e3aa7..a4992f3c3 100644 --- a/src/main/java/forestry/core/genetics/alleles/EnumAllele.java +++ b/src/main/java/forestry/core/genetics/alleles/EnumAllele.java @@ -72,7 +72,8 @@ public class EnumAllele { AVERAGE(20), FAST(25), FASTER(30), - FASTEST(35); + FASTEST(35), + MAXIMUM(99, true); private final Integer value; private final boolean dominant; diff --git a/src/main/java/forestry/core/gui/ClimateLedger.java b/src/main/java/forestry/core/gui/ClimateLedger.java index 5562c9da7..b52e0b29b 100755 --- a/src/main/java/forestry/core/gui/ClimateLedger.java +++ b/src/main/java/forestry/core/gui/ClimateLedger.java @@ -23,10 +23,9 @@ public class ClimateLedger extends Ledger { private final IClimatised tile; public ClimateLedger(LedgerManager manager, IClimatised tile) { - super(manager); + super(manager, "climate"); this.tile = tile; maxHeight = 72; - overlayColor = manager.gui.fontColor.get("ledger.climate.background"); } @Override @@ -44,16 +43,13 @@ public class ClimateLedger extends Ledger { return; } - manager.minecraft.fontRenderer.drawStringWithShadow(StringUtil.localize("gui.climate"), x + 22, y + 8, - manager.gui.fontColor.get("ledger.climate.header")); - manager.minecraft.fontRenderer.drawStringWithShadow(StringUtil.localize("gui.temperature") + ":", x + 22, y + 20, - manager.gui.fontColor.get("ledger.climate.subheader")); - manager.minecraft.fontRenderer.drawString(AlleleManager.climateHelper.toDisplay(temperature) + " " + StringUtil.floatAsPercent(tile.getExactTemperature()), x + 22, - y + 32, manager.gui.fontColor.get("ledger.climate.text")); - manager.minecraft.fontRenderer.drawStringWithShadow(StringUtil.localize("gui.humidity") + ":", x + 22, y + 44, - manager.gui.fontColor.get("ledger.climate.subheader")); - manager.minecraft.fontRenderer.drawString(AlleleManager.climateHelper.toDisplay(tile.getHumidity()) + " " + StringUtil.floatAsPercent(tile.getExactHumidity()), - x + 22, y + 56, manager.gui.fontColor.get("ledger.climate.text")); + drawHeader(StringUtil.localize("gui.climate"), x + 22, y + 8); + + drawSubheader(StringUtil.localize("gui.temperature") + ':', x + 22, y + 20); + drawText(AlleleManager.climateHelper.toDisplay(temperature) + ' ' + StringUtil.floatAsPercent(tile.getExactTemperature()), x + 22, y + 32); + + drawSubheader(StringUtil.localize("gui.humidity") + ':', x + 22, y + 44); + drawText(AlleleManager.climateHelper.toDisplay(tile.getHumidity()) + ' ' + StringUtil.floatAsPercent(tile.getExactHumidity()), x + 22, y + 56); } @Override diff --git a/src/main/java/forestry/core/gui/ContainerEscritoire.java b/src/main/java/forestry/core/gui/ContainerEscritoire.java index a9a2dd239..136f216d9 100755 --- a/src/main/java/forestry/core/gui/ContainerEscritoire.java +++ b/src/main/java/forestry/core/gui/ContainerEscritoire.java @@ -15,10 +15,7 @@ import net.minecraft.entity.player.EntityPlayer; import forestry.core.gadgets.TileEscritoire; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotOutput; -import forestry.core.network.PacketIds; -import forestry.core.network.PacketPayload; -import forestry.core.network.PacketUpdate; -import forestry.core.proxy.Proxies; +import forestry.core.network.PacketGuiSelect; public class ContainerEscritoire extends ContainerTile implements IGuiSelectable { @@ -32,7 +29,7 @@ public class ContainerEscritoire extends ContainerTile implement this.player = player; // Analyze slot - addSlotToContainer(new SlotFiltered(this.tile, TileEscritoire.SLOT_ANALYZE, 97, 67).setCrafter(this.tile)); + addSlotToContainer(new SlotFiltered(this.tile, TileEscritoire.SLOT_ANALYZE, 97, 67).setCrafter(this.tile).setStackLimit(1)); for (int i = 0; i < TileEscritoire.SLOTS_INPUT_COUNT; i++) { addSlotToContainer(new SlotFiltered(this.tile, TileEscritoire.SLOT_INPUT_1 + i, 17, 49 + i * 18).setBlockedTexture("slots/blocked_2")); @@ -56,35 +53,20 @@ public class ContainerEscritoire extends ContainerTile implement tile.sendBoard(player); } - public void sendTokenClick(int index) { - PacketPayload payload = new PacketPayload(1, 0, 0); - payload.intPayload[0] = index; - PacketUpdate packet = new PacketUpdate(PacketIds.GUI_SELECTION_CHANGE, payload); - Proxies.net.sendToServer(packet); - } - - public void sendProbeClick() { - PacketPayload payload = new PacketPayload(1, 0, 0); - payload.intPayload[0] = -1; - PacketUpdate packet = new PacketUpdate(PacketIds.GUI_SELECTION_CHANGE, payload); - Proxies.net.sendToServer(packet); - } - @Override - public void handleSelectionChange(EntityPlayer player, PacketUpdate packet) { + public void handleSelectionChange(EntityPlayer player, PacketGuiSelect packet) { if (!tile.getGame().isEnded()) { - int index = packet.payload.intPayload[0]; + int index = packet.getPrimaryIndex(); if (index == -1) { tile.probe(); } else { - tile.getGame().choose(packet.payload.intPayload[0]); + tile.getGame().choose(index); tile.processTurnResult(player.getGameProfile()); } } } @Override - public void setSelection(PacketUpdate packet) { + public void setSelection(PacketGuiSelect packet) { } - } diff --git a/src/main/java/forestry/core/gui/ContainerItemInventory.java b/src/main/java/forestry/core/gui/ContainerItemInventory.java index ce63b7c0e..aa5c72db2 100755 --- a/src/main/java/forestry/core/gui/ContainerItemInventory.java +++ b/src/main/java/forestry/core/gui/ContainerItemInventory.java @@ -48,4 +48,12 @@ public abstract class ContainerItemInventory extends Co public final boolean canInteractWith(EntityPlayer entityplayer) { return inventory.isUseableByPlayer(entityplayer); } + + @Override + public final ItemStack slotClick(int slotIndex, int button, int modifier, EntityPlayer player) { + ItemStack result = super.slotClick(slotIndex, button, modifier, player); + inventory.onSlotClick(player); + return result; + } + } diff --git a/src/main/java/forestry/core/gui/ContainerLiquidTanks.java b/src/main/java/forestry/core/gui/ContainerLiquidTanks.java index 384f6d120..d09bf55fb 100755 --- a/src/main/java/forestry/core/gui/ContainerLiquidTanks.java +++ b/src/main/java/forestry/core/gui/ContainerLiquidTanks.java @@ -26,9 +26,8 @@ import forestry.api.core.IToolPipette; import forestry.core.fluids.tanks.StandardTank; import forestry.core.gadgets.TileForestry; import forestry.core.interfaces.ILiquidTankContainer; -import forestry.core.network.PacketIds; -import forestry.core.network.PacketPayload; -import forestry.core.network.PacketUpdate; +import forestry.core.network.PacketId; +import forestry.core.network.PacketSlotClick; import forestry.core.proxy.Proxies; public class ContainerLiquidTanks extends ContainerTile { @@ -44,9 +43,7 @@ public class ContainerLiquidTanks return; } - PacketPayload payload = new PacketPayload(1, 0, 0); - payload.intPayload[0] = slot; - Proxies.net.sendToServer(new PacketUpdate(PacketIds.PIPETTE_CLICK, payload)); + Proxies.net.sendToServer(new PacketSlotClick(PacketId.PIPETTE_CLICK, tile, slot)); } public void handlePipetteClick(int slot, EntityPlayerMP player) { diff --git a/src/main/java/forestry/core/gui/ContainerNaturalistInventory.java b/src/main/java/forestry/core/gui/ContainerNaturalistInventory.java index a0e448ca4..738d09095 100755 --- a/src/main/java/forestry/core/gui/ContainerNaturalistInventory.java +++ b/src/main/java/forestry/core/gui/ContainerNaturalistInventory.java @@ -15,7 +15,7 @@ import net.minecraft.entity.player.InventoryPlayer; import forestry.core.gadgets.TileNaturalistChest; import forestry.core.gui.slots.SlotFiltered; -import forestry.core.network.PacketUpdate; +import forestry.core.network.PacketGuiSelect; public class ContainerNaturalistInventory extends ContainerTile implements IGuiSelectable { @@ -31,11 +31,11 @@ public class ContainerNaturalistInventory extends ContainerTile extends Con public void handleChipsetClick(int slot, EntityPlayer player, ItemStack itemstack) { if (!Proxies.common.isSimulating(player.worldObj)) { - PacketPayload payload = new PacketPayload(1, 0, 0); - payload.intPayload[0] = slot; - Proxies.net.sendToServer(new PacketUpdate(PacketIds.CHIPSET_CLICK, payload)); + PacketSlotClick packet = new PacketSlotClick(PacketId.CHIPSET_CLICK, tile, slot); + Proxies.net.sendToServer(packet); player.inventory.setItemStack(null); return; } @@ -50,18 +47,16 @@ public class ContainerSocketed extends Con player.inventory.setItemStack(null); } Proxies.net.inventoryChangeNotify(player); - - TileEntity te = (TileEntity) tile; - Proxies.net.sendToPlayer(new PacketSocketUpdate(PacketIds.SOCKET_UPDATE, te.xCoord, te.yCoord, te.zCoord, tile), player); - } + PacketSocketUpdate packet = new PacketSocketUpdate(PacketId.SOCKET_UPDATE, tile); + Proxies.net.sendToPlayer(packet, player); + } } public void handleSolderingIronClick(int slot, EntityPlayer player, ItemStack itemstack) { if (!Proxies.common.isSimulating(player.worldObj)) { - PacketPayload payload = new PacketPayload(1, 0, 0); - payload.intPayload[0] = slot; - Proxies.net.sendToServer(new PacketUpdate(PacketIds.SOLDERING_IRON_CLICK, payload)); + PacketSlotClick packet = new PacketSlotClick(PacketId.SOLDERING_IRON_CLICK, tile, slot); + Proxies.net.sendToServer(packet); return; } @@ -82,9 +77,7 @@ public class ContainerSocketed extends Con player.inventory.setItemStack(null); } - TileEntity te = (TileEntity) tile; - Proxies.net.sendToPlayer(new PacketSocketUpdate(PacketIds.SOCKET_UPDATE, te.xCoord, te.yCoord, te.zCoord, tile), player); - + PacketSocketUpdate packet = new PacketSocketUpdate(PacketId.SOCKET_UPDATE, tile); + Proxies.net.sendToPlayer(packet, player); } - } diff --git a/src/main/java/forestry/core/gui/ContainerTile.java b/src/main/java/forestry/core/gui/ContainerTile.java index 6373f499e..5f23173fc 100644 --- a/src/main/java/forestry/core/gui/ContainerTile.java +++ b/src/main/java/forestry/core/gui/ContainerTile.java @@ -10,10 +10,15 @@ ******************************************************************************/ package forestry.core.gui; +import com.google.common.collect.ImmutableSet; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; +import forestry.api.core.IErrorState; import forestry.core.gadgets.TileForestry; +import forestry.core.network.PacketErrorUpdate; +import forestry.core.proxy.Proxies; public class ContainerTile extends ContainerForestry { @@ -34,4 +39,24 @@ public class ContainerTile extends ContainerForestry { public final boolean canInteractWith(EntityPlayer entityplayer) { return tile.isUseableByPlayer(entityplayer); } + + private ImmutableSet previousErrorStates; + + @Override + public void detectAndSendChanges() { + super.detectAndSendChanges(); + + ImmutableSet errorStates = tile.getErrorStates(); + + if ((previousErrorStates != null) && !errorStates.equals(previousErrorStates)) { + PacketErrorUpdate packet = new PacketErrorUpdate(tile); + for (Object crafter : crafters) { + if (crafter instanceof EntityPlayer) { + Proxies.net.sendToPlayer(packet, (EntityPlayer) crafter); + } + } + } + + previousErrorStates = errorStates; + } } diff --git a/src/main/java/forestry/core/gui/ErrorLedger.java b/src/main/java/forestry/core/gui/ErrorLedger.java index f2530eb7e..9aac5bd06 100755 --- a/src/main/java/forestry/core/gui/ErrorLedger.java +++ b/src/main/java/forestry/core/gui/ErrorLedger.java @@ -26,9 +26,8 @@ public class ErrorLedger extends Ledger { private IErrorState state; public ErrorLedger(LedgerManager manager) { - super(manager, false); + super(manager, "error", false); maxHeight = 72; - overlayColor = manager.gui.fontColor.get("ledger.error.background"); } public void setState(@Nullable IErrorState state) { @@ -37,7 +36,7 @@ public class ErrorLedger extends Ledger { String helpString = StringUtil.localize(state.getHelp()); FontRenderer fontRenderer = manager.minecraft.fontRenderer; int lineCount = fontRenderer.listFormattedStringToWidth(helpString, maxWidth - 28).size(); - maxHeight = lineCount * (fontRenderer.FONT_HEIGHT + 2) + 20; + maxHeight = (lineCount + 1) * fontRenderer.FONT_HEIGHT + 20; } } @@ -47,8 +46,6 @@ public class ErrorLedger extends Ledger { return; } - - // Draw background drawBackground(x, y); @@ -57,12 +54,10 @@ public class ErrorLedger extends Ledger { // Write description if fully opened if (isFullyOpened()) { - FontRenderer fontRenderer = manager.minecraft.fontRenderer; - - fontRenderer.drawStringWithShadow(getTooltip(), x + 24, y + 8, manager.gui.fontColor.get("ledger.error.header")); + drawHeader(getTooltip(), x + 24, y + 8); String helpString = StringUtil.localize(state.getHelp()); - fontRenderer.drawSplitString(helpString, x + 24, y + 20, maxWidth - 28, manager.gui.fontColor.get("ledger.error.text")); + drawSplitText(helpString, x + 24, y + 20, maxWidth - 28); } } diff --git a/src/main/java/forestry/core/gui/GuiEscritoire.java b/src/main/java/forestry/core/gui/GuiEscritoire.java index 309c61374..77cee81d9 100755 --- a/src/main/java/forestry/core/gui/GuiEscritoire.java +++ b/src/main/java/forestry/core/gui/GuiEscritoire.java @@ -28,6 +28,8 @@ import forestry.core.gadgets.NaturalistGame; import forestry.core.gadgets.NaturalistGame.GameToken; import forestry.core.gadgets.TileEscritoire; import forestry.core.gui.widgets.Widget; +import forestry.core.network.PacketGuiSelect; +import forestry.core.network.PacketId; import forestry.core.proxy.Proxies; import forestry.core.render.SpriteSheet; import forestry.core.render.TextureManager; @@ -35,7 +37,7 @@ import forestry.core.utils.StringUtil; public class GuiEscritoire extends GuiForestry { - private static enum Notes { + private enum Notes { level1, level2, level3, level4, success, failure } @@ -46,7 +48,7 @@ public class GuiEscritoire extends GuiForestry ext ledgerManager.add(new HintLedger(ledgerManager, (IHintSource) inventory)); } - if (inventory instanceof IOwnable && ((IOwnable) inventory).isOwnable()) { + if (inventory instanceof IOwnable) { ledgerManager.add(new OwnerLedger(ledgerManager, (IOwnable) inventory)); } diff --git a/src/main/java/forestry/core/gui/GuiNaturalistInventory.java b/src/main/java/forestry/core/gui/GuiNaturalistInventory.java index 6e19c0db4..a570b053c 100755 --- a/src/main/java/forestry/core/gui/GuiNaturalistInventory.java +++ b/src/main/java/forestry/core/gui/GuiNaturalistInventory.java @@ -30,9 +30,9 @@ import forestry.core.config.Defaults; import forestry.core.genetics.EnumMutateChance; import forestry.core.gui.buttons.GuiBetterButton; import forestry.core.gui.buttons.StandardButtonTextureSets; -import forestry.core.network.PacketIds; -import forestry.core.network.PacketPayload; -import forestry.core.network.PacketUpdate; +import forestry.core.network.ForestryPacket; +import forestry.core.network.PacketGuiSelect; +import forestry.core.network.PacketId; import forestry.core.proxy.Proxies; import forestry.core.utils.StringUtil; @@ -93,10 +93,8 @@ public class GuiNaturalistInventory extends GuiForestry maxWidth) { currentWidth = maxWidth; } } else if (!open && currentWidth > minWidth) { - currentWidth -= Config.guiTabSpeed; + currentWidth -= moveAmount; if (currentWidth < minWidth) { currentWidth = minWidth; } @@ -78,12 +103,12 @@ public abstract class Ledger { // Height if (open && currentHeight < maxHeight) { - currentHeight += Config.guiTabSpeed; + currentHeight += moveAmount; if (currentHeight > maxHeight) { currentHeight = maxHeight; } } else if (!open && currentHeight > minHeight) { - currentHeight -= Config.guiTabSpeed; + currentHeight -= moveAmount; if (currentHeight < minHeight) { currentHeight = minHeight; } @@ -91,7 +116,11 @@ public abstract class Ledger { } public int getHeight() { - return currentHeight; + return Math.round(currentHeight); + } + + public int getWidth() { + return Math.round(currentWidth); } public abstract void draw(int x, int y); @@ -144,11 +173,14 @@ public abstract class Ledger { Proxies.common.bindTexture(texture); - manager.gui.drawTexturedModalRect(x, y + 4, 0, 256 - currentHeight + 4, 4, currentHeight - 4); // left edge - manager.gui.drawTexturedModalRect(x + 4, y, 256 - currentWidth + 4, 0, currentWidth - 4, 4); // top edge + int height = getHeight(); + int width = getWidth(); + + manager.gui.drawTexturedModalRect(x, y + 4, 0, 256 - height + 4, 4, height - 4); // left edge + manager.gui.drawTexturedModalRect(x + 4, y, 256 - width + 4, 0, width - 4, 4); // top edge manager.gui.drawTexturedModalRect(x, y, 0, 0, 4, 4); // top left corner - manager.gui.drawTexturedModalRect(x + 4, y + 4, 256 - currentWidth + 4, 256 - currentHeight + 4, currentWidth - 4, currentHeight - 4); // body + bottom + right + manager.gui.drawTexturedModalRect(x + 4, y + 4, 256 - width + 4, 256 - height + 4, width - 4, height - 4); // body + bottom + right GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); } @@ -162,6 +194,21 @@ public abstract class Ledger { manager.gui.drawTexturedModelRectFromIcon(x, y, icon, 16, 16); GL11.glEnable(GL11.GL_LIGHTING); } + } + protected void drawHeader(String string, int x, int y) { + manager.minecraft.fontRenderer.drawStringWithShadow(string, x, y, fontColorHeader); + } + + protected void drawSubheader(String string, int x, int y) { + manager.minecraft.fontRenderer.drawStringWithShadow(string, x, y, fontColorSubheader); + } + + protected void drawText(String string, int x, int y) { + manager.minecraft.fontRenderer.drawString(string, x, y, fontColorText); + } + + protected void drawSplitText(String string, int x, int y, int width) { + manager.minecraft.fontRenderer.drawSplitString(string, x, y, width, fontColorText); } } diff --git a/src/main/java/forestry/core/gui/LedgerManager.java b/src/main/java/forestry/core/gui/LedgerManager.java index e96e22718..09e000be6 100755 --- a/src/main/java/forestry/core/gui/LedgerManager.java +++ b/src/main/java/forestry/core/gui/LedgerManager.java @@ -90,7 +90,7 @@ public class LedgerManager { continue; } - errorLedger.currentShiftX = xShiftError - errorLedger.currentWidth; + errorLedger.currentShiftX = xShiftError - errorLedger.getWidth(); errorLedger.currentShiftY = yShiftError; if (errorLedger.intersectsWith(mX, mY)) { return errorLedger; @@ -135,7 +135,7 @@ public class LedgerManager { } GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - errorLedger.draw(-errorLedger.currentWidth, yPos); + errorLedger.draw(-errorLedger.getWidth(), yPos); yPos += errorLedger.getHeight(); } } diff --git a/src/main/java/forestry/core/gui/OwnerLedger.java b/src/main/java/forestry/core/gui/OwnerLedger.java index da87d7d6c..46400a969 100755 --- a/src/main/java/forestry/core/gui/OwnerLedger.java +++ b/src/main/java/forestry/core/gui/OwnerLedger.java @@ -18,7 +18,7 @@ import net.minecraft.util.IIcon; import forestry.core.interfaces.IOwnable; import forestry.core.interfaces.IRestrictedAccess; import forestry.core.network.PacketCoordinates; -import forestry.core.network.PacketIds; +import forestry.core.network.PacketId; import forestry.core.proxy.Proxies; import forestry.core.render.TextureManager; import forestry.core.utils.EnumAccess; @@ -33,8 +33,16 @@ public class OwnerLedger extends Ledger { private final IOwnable tile; public OwnerLedger(LedgerManager manager, IOwnable tile) { - super(manager); + super(manager, "owner"); this.tile = tile; + + boolean playerIsOwner = tile.isOwner(manager.minecraft.thePlayer); + + if (playerIsOwner) { + maxHeight = 60; + } else { + maxHeight = 36; + } } public boolean isAccessButton(int mouseX, int mouseY) { @@ -45,18 +53,13 @@ public class OwnerLedger extends Ledger { return mouseX >= shiftX && mouseX <= currentShiftX + currentWidth && mouseY >= shiftY && mouseY <= shiftY + 12; } + @Override + public boolean isVisible() { + return tile.isOwned(); + } + @Override public void draw(int x, int y) { - - // Update state - boolean playerIsOwner = tile.isOwner(manager.minecraft.thePlayer); - - if (playerIsOwner) { - maxHeight = 60; - } else { - maxHeight = 36; - } - // Draw background drawBackground(x, y); @@ -75,16 +78,16 @@ public class OwnerLedger extends Ledger { return; } - manager.minecraft.fontRenderer.drawStringWithShadow(StringUtil.localize("gui.owner"), x + 22, y + 8, manager.gui.fontColor.get("ledger.owner.header")); + drawHeader(StringUtil.localize("gui.owner"), x + 22, y + 8); - manager.minecraft.fontRenderer.drawString(PlayerUtil.getOwnerName(tile), x + 22, y + 20, manager.gui.fontColor.get("ledger.owner.text")); + drawText(PlayerUtil.getOwnerName(tile), x + 22, y + 20); + boolean playerIsOwner = tile.isOwner(manager.minecraft.thePlayer); if (playerIsOwner && tile instanceof IRestrictedAccess) { - manager.minecraft.fontRenderer.drawStringWithShadow(StringUtil.localize("gui.access") + ":", x + 22, y + 32, - manager.gui.fontColor.get("ledger.owner.subheader")); + drawSubheader(StringUtil.localize("gui.access") + ':', x + 22, y + 32); // Access rules drawIcon(accessIcon, x + 20, y + 40); - manager.minecraft.fontRenderer.drawString(StringUtil.localize(access.getName()), x + 38, y + 44, manager.gui.fontColor.get("ledger.owner.text")); + drawText(StringUtil.localize(access.getName()), x + 38, y + 44); } } @@ -99,7 +102,7 @@ public class OwnerLedger extends Ledger { if (isAccessButton(x, y) && tile instanceof IRestrictedAccess) { if (!Proxies.common.isSimulating(((TileEntity) tile).getWorldObj())) { TileEntity te = (TileEntity) tile; - Proxies.net.sendToServer(new PacketCoordinates(PacketIds.ACCESS_SWITCH, te.xCoord, te.yCoord, te.zCoord)); + Proxies.net.sendToServer(new PacketCoordinates(PacketId.ACCESS_SWITCH, te)); } ((IRestrictedAccess) tile).switchAccessRule(manager.minecraft.thePlayer); @@ -108,5 +111,4 @@ public class OwnerLedger extends Ledger { return false; } - } diff --git a/src/main/java/forestry/core/gui/PowerLedger.java b/src/main/java/forestry/core/gui/PowerLedger.java index d81aad776..c0c9ec575 100755 --- a/src/main/java/forestry/core/gui/PowerLedger.java +++ b/src/main/java/forestry/core/gui/PowerLedger.java @@ -20,10 +20,9 @@ public class PowerLedger extends Ledger { private final IPowerHandler tile; public PowerLedger(LedgerManager manager, IPowerHandler tile) { - super(manager); + super(manager, "power"); this.tile = tile; maxHeight = 94; - overlayColor = manager.gui.fontColor.get("ledger.power.background"); } @Override @@ -39,17 +38,17 @@ public class PowerLedger extends Ledger { } EnergyManager energyManager = tile.getEnergyManager(); - manager.minecraft.fontRenderer.drawStringWithShadow(StringUtil.localize("gui.energy"), x + 22, y + 8, manager.gui.fontColor.get("ledger.power.header")); - manager.minecraft.fontRenderer.drawStringWithShadow(StringUtil.localize("gui.stored") + ":", x + 22, y + 20, - manager.gui.fontColor.get("ledger.power.subheader")); - manager.minecraft.fontRenderer.drawString(energyManager.getTotalEnergyStored() + " RF", x + 22, y + 32, manager.gui.fontColor.get("ledger.power.text")); - manager.minecraft.fontRenderer.drawStringWithShadow(StringUtil.localize("gui.maxenergy") + ":", x + 22, y + 44, - manager.gui.fontColor.get("ledger.power.subheader")); - manager.minecraft.fontRenderer.drawString(energyManager.getMaxEnergyStored() + " RF", x + 22, y + 56, manager.gui.fontColor.get("ledger.power.text")); - manager.minecraft.fontRenderer.drawStringWithShadow(StringUtil.localize("gui.maxenergyreceive") + ":", x + 22, y + 68, - manager.gui.fontColor.get("ledger.power.subheader")); - manager.minecraft.fontRenderer.drawString(energyManager.getMaxEnergyReceived() + " RF", x + 22, y + 80, manager.gui.fontColor.get("ledger.power.text")); + drawHeader(StringUtil.localize("gui.energy"), x + 22, y + 8); + + drawSubheader(StringUtil.localize("gui.stored") + ':', x + 22, y + 20); + drawText(energyManager.getTotalEnergyStored() + " RF", x + 22, y + 32); + + drawSubheader(StringUtil.localize("gui.maxenergy") + ':', x + 22, y + 44); + drawText(energyManager.getMaxEnergyStored() + " RF", x + 22, y + 56); + + drawSubheader(StringUtil.localize("gui.maxenergyreceive") + ':', x + 22, y + 68); + drawText(energyManager.getMaxEnergyReceived() + " RF", x + 22, y + 80); } @Override diff --git a/src/main/java/forestry/core/gui/slots/SlotFiltered.java b/src/main/java/forestry/core/gui/slots/SlotFiltered.java index 36c0a6b12..03a960fb6 100644 --- a/src/main/java/forestry/core/gui/slots/SlotFiltered.java +++ b/src/main/java/forestry/core/gui/slots/SlotFiltered.java @@ -16,7 +16,7 @@ import net.minecraft.item.ItemStack; import forestry.core.interfaces.IFilterSlotDelegate; /** - * Slot which only takes specific items, specified by the ICustomSlotInventory. + * Slot which only takes specific items, specified by the IFilterSlotDelegate. */ public class SlotFiltered extends SlotWatched { diff --git a/src/main/java/forestry/core/gui/slots/SlotForestry.java b/src/main/java/forestry/core/gui/slots/SlotForestry.java index 4fb9ebab3..efd0dd5ec 100755 --- a/src/main/java/forestry/core/gui/slots/SlotForestry.java +++ b/src/main/java/forestry/core/gui/slots/SlotForestry.java @@ -21,7 +21,6 @@ import forestry.core.gui.tooltips.ToolTip; public class SlotForestry extends Slot implements IToolTipProvider { private boolean isPhantom; - private boolean isInfinite; private boolean canAdjustPhantom = true; private boolean canShift = true; private int stackLimit; @@ -35,11 +34,6 @@ public class SlotForestry extends Slot implements IToolTipProvider { this.stackLimit = -1; } - public SlotForestry setInfinite() { - this.isInfinite = true; - return this; - } - public SlotForestry setPhantom() { isPhantom = true; return this; @@ -93,22 +87,6 @@ public class SlotForestry extends Slot implements IToolTipProvider { } } - @Override - public ItemStack decrStackSize(int i) { - if (!isInfinite) { - return super.decrStackSize(i); - } - - ItemStack stack = inventory.getStackInSlot(getSlotIndex()); - if (stack == null) { - return null; - } - - ItemStack result = stack.copy(); - result.stackSize = i; - return result; - } - /** * @param toolTips the tooltips to set */ diff --git a/src/main/java/forestry/core/gui/slots/SlotLocked.java b/src/main/java/forestry/core/gui/slots/SlotLocked.java index 8cb1d7a31..118c8466f 100755 --- a/src/main/java/forestry/core/gui/slots/SlotLocked.java +++ b/src/main/java/forestry/core/gui/slots/SlotLocked.java @@ -16,8 +16,8 @@ import net.minecraft.item.ItemStack; public class SlotLocked extends SlotForestry { - public SlotLocked(IInventory par1iInventory, int par2, int par3, int par4) { - super(par1iInventory, par2, par3, par4); + public SlotLocked(IInventory inventory, int slotIndex, int xPos, int yPos) { + super(inventory, slotIndex, xPos, yPos); setCanAdjustPhantom(false); blockShift(); setPhantom(); diff --git a/src/main/java/forestry/core/gadgets/TileEngine.java b/src/main/java/forestry/core/interfaces/IActivatable.java old mode 100755 new mode 100644 similarity index 73% rename from src/main/java/forestry/core/gadgets/TileEngine.java rename to src/main/java/forestry/core/interfaces/IActivatable.java index 822f2f12e..0d8da1e77 --- a/src/main/java/forestry/core/gadgets/TileEngine.java +++ b/src/main/java/forestry/core/interfaces/IActivatable.java @@ -1,14 +1,18 @@ -/******************************************************************************* - * 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.gadgets; - -public class TileEngine extends TileMachine { -} +/******************************************************************************* + * 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.interfaces; + +/* Networked tile entities that have a client side "active" flag */ +public interface IActivatable { + boolean isActive(); + + void setActive(boolean active); +} diff --git a/src/main/java/forestry/core/interfaces/IOreDictionaryHandler.java b/src/main/java/forestry/core/interfaces/IItemStackDisplay.java old mode 100755 new mode 100644 similarity index 85% rename from src/main/java/forestry/core/interfaces/IOreDictionaryHandler.java rename to src/main/java/forestry/core/interfaces/IItemStackDisplay.java index 2d379a69a..f6d108567 --- a/src/main/java/forestry/core/interfaces/IOreDictionaryHandler.java +++ b/src/main/java/forestry/core/interfaces/IItemStackDisplay.java @@ -1,17 +1,17 @@ -/******************************************************************************* - * 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.interfaces; - -import net.minecraft.item.ItemStack; - -public interface IOreDictionaryHandler { - void onOreRegistration(String name, ItemStack ore); -} +/******************************************************************************* + * 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.interfaces; + +import net.minecraft.item.ItemStack; + +public interface IItemStackDisplay { + void handleItemStackForDisplay(ItemStack itemStack); +} diff --git a/src/main/java/forestry/core/interfaces/IOwnable.java b/src/main/java/forestry/core/interfaces/IOwnable.java index e881a8df3..159cd43d2 100755 --- a/src/main/java/forestry/core/interfaces/IOwnable.java +++ b/src/main/java/forestry/core/interfaces/IOwnable.java @@ -16,11 +16,9 @@ import com.mojang.authlib.GameProfile; public interface IOwnable { - boolean isOwnable(); - boolean isOwned(); - GameProfile getOwnerProfile(); + GameProfile getOwner(); void setOwner(EntityPlayer player); diff --git a/src/main/java/forestry/core/inventory/InventoryAdapter.java b/src/main/java/forestry/core/inventory/InventoryAdapter.java index fe9e60497..233c83de6 100755 --- a/src/main/java/forestry/core/inventory/InventoryAdapter.java +++ b/src/main/java/forestry/core/inventory/InventoryAdapter.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.inventory; +import java.io.IOException; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; @@ -17,12 +19,15 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import forestry.core.config.Defaults; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IStreamable; import forestry.core.utils.PlainInventory; /** * With permission from Krapht. */ -public class InventoryAdapter implements IInventoryAdapter { +public class InventoryAdapter implements IInventoryAdapter, IStreamable { protected final IInventory inventory; private boolean allowAutomation = true; @@ -206,4 +211,14 @@ public class InventoryAdapter implements IInventoryAdapter { } nbttagcompound.setTag(inventory.getInventoryName(), nbttaglist); } + + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + data.writeInventory(inventory); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + data.readInventory(inventory); + } } diff --git a/src/main/java/forestry/core/inventory/ItemInventory.java b/src/main/java/forestry/core/inventory/ItemInventory.java index 2f68ba4ec..1b13c1aa4 100755 --- a/src/main/java/forestry/core/inventory/ItemInventory.java +++ b/src/main/java/forestry/core/inventory/ItemInventory.java @@ -145,12 +145,12 @@ public abstract class ItemInventory implements IInventory, IFilterSlotDelegate { } } - migrateToNewNBT(); + writeToParentNBT(); } } } - private void migrateToNewNBT() { + private void writeToParentNBT() { ItemStack parent = getParent(); if (parent == null) { return; @@ -176,6 +176,9 @@ public abstract class ItemInventory implements IInventory, IFilterSlotDelegate { return Integer.toString(i, Character.MAX_RADIX); } + public void onSlotClick(EntityPlayer player) { + } + @Override public ItemStack decrStackSize(int i, int j) { ItemStack stack = getStackInSlot(i); @@ -250,7 +253,8 @@ public abstract class ItemInventory implements IInventory, IFilterSlotDelegate { } @Override - public void markDirty() { + public final void markDirty() { + writeToParentNBT(); } @Override diff --git a/src/main/java/forestry/core/items/ItemCrated.java b/src/main/java/forestry/core/items/ItemCrated.java index 595b15763..133fde17b 100755 --- a/src/main/java/forestry/core/items/ItemCrated.java +++ b/src/main/java/forestry/core/items/ItemCrated.java @@ -80,7 +80,8 @@ public class ItemCrated extends Item { if (contained == null) { return StatCollector.translateToLocal("item.for.crate.name"); } else { - return StringUtil.localize("item.crated.adj") + " " + Proxies.common.getDisplayName(contained); + String containedName = Proxies.common.getDisplayName(contained); + return StringUtil.localizeAndFormat("item.crated.grammar", containedName); } } diff --git a/src/main/java/forestry/core/network/DataInputStreamForestry.java b/src/main/java/forestry/core/network/DataInputStreamForestry.java new file mode 100644 index 000000000..1eb33e183 --- /dev/null +++ b/src/main/java/forestry/core/network/DataInputStreamForestry.java @@ -0,0 +1,121 @@ +package forestry.core.network; + +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.inventory.IInventory; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; + +import cpw.mods.fml.common.registry.GameData; + +import forestry.core.proxy.Proxies; + +public class DataInputStreamForestry extends DataInputStream { + + public DataInputStreamForestry(InputStream in) { + super(in); + } + + public ItemStack readItemStack() throws IOException { + ItemStack itemstack = null; + String itemName = readUTF(); + + if (!itemName.isEmpty()) { + Item item = GameData.getItemRegistry().getRaw(itemName); + byte stackSize = readByte(); + int meta = readVarInt(); + itemstack = new ItemStack(item, stackSize, meta); + + if (item.isDamageable() || item.getShareTag()) { + itemstack.stackTagCompound = readNBTTagCompound(); + } + } + + return itemstack; + } + + public ItemStack[] readItemStacks() throws IOException { + int stackCount = readVarInt(); + + ItemStack[] itemStacks = new ItemStack[stackCount]; + for (int i = 0; i < stackCount; i++) { + itemStacks[i] = readItemStack(); + } + + return itemStacks; + } + + public void readInventory(IInventory inventory) throws IOException { + int size = readVarInt(); + + for (int i = 0; i < size; i++) { + ItemStack stack = readItemStack(); + inventory.setInventorySlotContents(i, stack); + } + } + + public T readStreamable(Class streamableClass) throws IOException { + if (readBoolean()) { + try { + T streamable = streamableClass.newInstance(); + streamable.readData(this); + return streamable; + } catch (ReflectiveOperationException e) { + Proxies.log.severe("Failed to read Streamable for class " + streamableClass + " with error " + e); + } + } + return null; + } + + public List readStreamables(Class streamableClass) throws IOException { + int length = readVarInt(); + List streamables = new ArrayList(length); + if (length > 0) { + for (int i = 0; i < length; i++) { + T streamable = readStreamable(streamableClass); + streamables.add(streamable); + } + } + return streamables; + } + + /** + * Reads a compressed int from the buffer. To do so it maximally reads 5 byte-sized chunks whose most significant + * bit dictates whether another byte should be read. + */ + public int readVarInt() throws IOException { + int varInt = 0; + int size = 0; + byte b0; + + do { + b0 = readByte(); + varInt |= (b0 & 127) << size++ * 7; + + if (size > 5) { + throw new RuntimeException("VarInt too big"); + } + } while ((b0 & 128) == 128); + + return varInt; + } + + public NBTTagCompound readNBTTagCompound() throws IOException { + int length = readVarInt(); + + if (length < 0) { + return null; + } else { + byte[] compressed = new byte[length]; + readFully(compressed); + return CompressedStreamTools.readCompressed(new ByteArrayInputStream(compressed)); + } + } +} diff --git a/src/main/java/forestry/core/network/DataOutputStreamForestry.java b/src/main/java/forestry/core/network/DataOutputStreamForestry.java new file mode 100644 index 000000000..dd596d810 --- /dev/null +++ b/src/main/java/forestry/core/network/DataOutputStreamForestry.java @@ -0,0 +1,96 @@ +package forestry.core.network; + +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.List; + +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; + +import cpw.mods.fml.common.registry.GameData; + +public class DataOutputStreamForestry extends DataOutputStream { + + public DataOutputStreamForestry(OutputStream out) { + super(out); + } + + public void writeItemStack(ItemStack itemstack) throws IOException { + if (itemstack == null) { + writeUTF(""); + } else { + writeUTF(GameData.getItemRegistry().getNameForObject(itemstack.getItem())); + writeByte(itemstack.stackSize); + writeVarInt(itemstack.getItemDamage()); + + if (itemstack.getItem().isDamageable() || itemstack.getItem().getShareTag()) { + writeNBTTagCompound(itemstack.stackTagCompound); + } + } + } + + public void writeItemStacks(ItemStack[] itemStacks) throws IOException { + writeVarInt(itemStacks.length); + for (ItemStack itemstack : itemStacks) { + writeItemStack(itemstack); + } + } + + public void writeInventory(IInventory inventory) throws IOException { + int size = inventory.getSizeInventory(); + writeVarInt(size); + + for (int i = 0; i < size; i++) { + ItemStack stack = inventory.getStackInSlot(i); + writeItemStack(stack); + } + } + + public void writeStreamable(IStreamable streamable) throws IOException { + if (streamable != null) { + writeBoolean(true); + streamable.writeData(this); + } else { + writeBoolean(false); + } + } + + public void writeStreamables(List streamables) throws IOException { + if (streamables == null) { + writeVarInt(0); + } else { + writeVarInt(streamables.size()); + for (IStreamable streamable : streamables) { + writeStreamable(streamable); + } + } + } + + /** + * Writes a compressed int to the buffer. The smallest number of bytes to fit the passed int will be written. Of + * each such byte only 7 bits will be used to describe the actual value since its most significant bit dictates + * whether the next byte is part of that same int. Micro-optimization for int values that are expected to have + * values below 128. + */ + public void writeVarInt(int varInt) throws IOException { + while ((varInt & -128) != 0) { + writeByte(varInt & 127 | 128); + varInt >>>= 7; + } + + writeByte(varInt); + } + + public void writeNBTTagCompound(NBTTagCompound nbttagcompound) throws IOException { + if (nbttagcompound == null) { + writeVarInt(-1); + } else { + byte[] compressed = CompressedStreamTools.compress(nbttagcompound); + writeVarInt((short) compressed.length); + write(compressed); + } + } +} diff --git a/src/main/java/forestry/core/network/ForestryPacket.java b/src/main/java/forestry/core/network/ForestryPacket.java index 7d07547c9..e96949574 100755 --- a/src/main/java/forestry/core/network/ForestryPacket.java +++ b/src/main/java/forestry/core/network/ForestryPacket.java @@ -10,40 +10,33 @@ ******************************************************************************/ package forestry.core.network; -import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; import java.io.IOException; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTTagCompound; - import cpw.mods.fml.common.network.internal.FMLProxyPacket; -import cpw.mods.fml.common.registry.GameData; import io.netty.buffer.Unpooled; public class ForestryPacket { protected static final String channel = "FOR"; - protected int id; + private final PacketId id; - public ForestryPacket() { + public ForestryPacket(DataInputStreamForestry data) throws IOException { + this.id = PacketId.INVALID; + readData(data); } - public ForestryPacket(int id) { + public ForestryPacket(PacketId id) { this.id = id; } - public FMLProxyPacket getPacket() { + public final FMLProxyPacket getPacket() { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - DataOutputStream data = new DataOutputStream(bytes); + DataOutputStreamForestry data = new DataOutputStreamForestry(bytes); try { - data.writeByte(getID()); + data.writeByte(id.ordinal()); writeData(data); } catch (IOException e) { e.printStackTrace(); @@ -52,73 +45,9 @@ public class ForestryPacket { return new FMLProxyPacket(Unpooled.wrappedBuffer(bytes.toByteArray()), channel); } - public int getID() { - return id; + protected void writeData(DataOutputStreamForestry data) throws IOException { } - protected ItemStack readItemStack(DataInputStream data) throws IOException { - ItemStack itemstack = null; - String itemName = data.readUTF(); - - if (!itemName.isEmpty()) { - Item item = GameData.getItemRegistry().getRaw(itemName); - byte stackSize = data.readByte(); - short meta = data.readShort(); - itemstack = new ItemStack(item, stackSize, meta); - - if (item.isDamageable() || item.getShareTag()) { - itemstack.stackTagCompound = this.readNBTTagCompound(data); - } - } - - return itemstack; + protected void readData(DataInputStreamForestry data) throws IOException { } - - protected void writeItemStack(ItemStack itemstack, DataOutputStream data) throws IOException { - - if (itemstack == null) { - data.writeUTF(""); - } else { - data.writeUTF(GameData.getItemRegistry().getNameForObject(itemstack.getItem())); - data.writeByte(itemstack.stackSize); - data.writeShort(itemstack.getItemDamage()); - - if (itemstack.getItem().isDamageable() || itemstack.getItem().getShareTag()) { - this.writeNBTTagCompound(itemstack.stackTagCompound, data); - } - } - } - - protected NBTTagCompound readNBTTagCompound(DataInputStream data) throws IOException { - - short length = data.readShort(); - - if (length < 0) { - return null; - } else { - byte[] compressed = new byte[length]; - data.readFully(compressed); - return CompressedStreamTools.readCompressed(new ByteArrayInputStream(compressed)); - } - - } - - protected void writeNBTTagCompound(NBTTagCompound nbttagcompound, DataOutputStream data) throws IOException { - - if (nbttagcompound == null) { - data.writeShort(-1); - } else { - byte[] compressed = CompressedStreamTools.compress(nbttagcompound); - data.writeShort((short) compressed.length); - data.write(compressed); - } - - } - - public void writeData(DataOutputStream data) throws IOException { - } - - public void readData(DataInputStream data) throws IOException { - } - } diff --git a/src/main/java/forestry/core/network/ILocatedPacket.java b/src/main/java/forestry/core/network/ILocatedPacket.java index 9b1599e3a..a8bcd8920 100755 --- a/src/main/java/forestry/core/network/ILocatedPacket.java +++ b/src/main/java/forestry/core/network/ILocatedPacket.java @@ -15,4 +15,8 @@ import net.minecraft.world.World; public interface ILocatedPacket { TileEntity getTarget(World world); + + int getPosX(); + int getPosY(); + int getPosZ(); } diff --git a/src/main/java/forestry/core/interfaces/IPacketHandler.java b/src/main/java/forestry/core/network/IPacketHandler.java old mode 100755 new mode 100644 similarity index 81% rename from src/main/java/forestry/core/interfaces/IPacketHandler.java rename to src/main/java/forestry/core/network/IPacketHandler.java index e402a483c..673ba9538 --- a/src/main/java/forestry/core/interfaces/IPacketHandler.java +++ b/src/main/java/forestry/core/network/IPacketHandler.java @@ -8,9 +8,8 @@ * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ -package forestry.core.interfaces; +package forestry.core.network; -import java.io.DataInputStream; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; @@ -18,6 +17,6 @@ import net.minecraft.entity.player.EntityPlayer; public interface IPacketHandler { /** Returns true if the packet has been handled */ - boolean onPacketData(int packetID, DataInputStream data, EntityPlayer player) throws IOException; + boolean onPacketData(PacketId packetID, DataInputStreamForestry data, EntityPlayer player) throws IOException; } diff --git a/src/main/java/forestry/core/network/INetworkedEntity.java b/src/main/java/forestry/core/network/IStreamable.java old mode 100755 new mode 100644 similarity index 74% rename from src/main/java/forestry/core/network/INetworkedEntity.java rename to src/main/java/forestry/core/network/IStreamable.java index 5d9f37b86..7c7127e63 --- a/src/main/java/forestry/core/network/INetworkedEntity.java +++ b/src/main/java/forestry/core/network/IStreamable.java @@ -1,19 +1,19 @@ -/******************************************************************************* - * 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; - -public interface INetworkedEntity { - - void sendNetworkUpdate(); - - void fromPacket(ForestryPacket packet); - -} +/******************************************************************************* + * 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 java.io.IOException; + +public interface IStreamable { + void writeData(DataOutputStreamForestry data) throws IOException; + + void readData(DataInputStreamForestry data) throws IOException; +} diff --git a/src/main/java/forestry/core/network/PacketCoordinates.java b/src/main/java/forestry/core/network/PacketCoordinates.java index 3b79a1876..32f4e29e0 100755 --- a/src/main/java/forestry/core/network/PacketCoordinates.java +++ b/src/main/java/forestry/core/network/PacketCoordinates.java @@ -10,8 +10,6 @@ ******************************************************************************/ package forestry.core.network; -import java.io.DataInputStream; -import java.io.DataOutputStream; import java.io.IOException; import net.minecraft.tileentity.TileEntity; @@ -24,18 +22,19 @@ public class PacketCoordinates extends ForestryPacket implements ILocatedPacket private int posY; private int posZ; - public PacketCoordinates() { + public PacketCoordinates(DataInputStreamForestry data) throws IOException { + super(data); } - public PacketCoordinates(int id, TileEntity tileEntity) { + public PacketCoordinates(PacketId id, TileEntity tileEntity) { this(id, tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord); } - public PacketCoordinates(int id, ChunkCoordinates coordinates) { + public PacketCoordinates(PacketId id, ChunkCoordinates coordinates) { this(id, coordinates.posX, coordinates.posY, coordinates.posZ); } - public PacketCoordinates(int id, int posX, int posY, int posZ) { + public PacketCoordinates(PacketId id, int posX, int posY, int posZ) { super(id); this.posX = posX; this.posY = posY; @@ -43,42 +42,37 @@ public class PacketCoordinates extends ForestryPacket implements ILocatedPacket } @Override - public void writeData(DataOutputStream data) throws IOException { - - data.writeInt(posX); - data.writeInt(posY); - data.writeInt(posZ); - + protected void writeData(DataOutputStreamForestry data) throws IOException { + data.writeVarInt(posX); + data.writeVarInt(posY); + data.writeVarInt(posZ); } @Override - public void readData(DataInputStream data) throws IOException { - - posX = data.readInt(); - posY = data.readInt(); - posZ = data.readInt(); - + protected void readData(DataInputStreamForestry data) throws IOException { + posX = data.readVarInt(); + posY = data.readVarInt(); + posZ = data.readVarInt(); } - public ChunkCoordinates getCoordinates() { + public final ChunkCoordinates getCoordinates() { return new ChunkCoordinates(posX, posY, posZ); } - public int getPosX() { + public final int getPosX() { return posX; } - public int getPosY() { + public final int getPosY() { return posY; } - public int getPosZ() { + public final int getPosZ() { return posZ; } @Override - public TileEntity getTarget(World world) { + public final TileEntity getTarget(World world) { return world.getTileEntity(posX, posY, posZ); } - } diff --git a/src/main/java/forestry/core/network/PacketErrorUpdate.java b/src/main/java/forestry/core/network/PacketErrorUpdate.java new file mode 100644 index 000000000..ac555bb59 --- /dev/null +++ b/src/main/java/forestry/core/network/PacketErrorUpdate.java @@ -0,0 +1,52 @@ +/******************************************************************************* + * 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 java.io.IOException; + +import net.minecraft.tileentity.TileEntity; + +import forestry.core.gadgets.TileForestry; +import forestry.core.proxy.Proxies; + +public class PacketErrorUpdate extends PacketCoordinates { + + private TileForestry tileForestry; + + public static void onPacketData(DataInputStreamForestry data) throws IOException { + new PacketErrorUpdate(data); + } + + public PacketErrorUpdate(DataInputStreamForestry data) throws IOException { + super(data); + } + + public PacketErrorUpdate(TileForestry tileForestry) { + super(PacketId.TILE_FORESTRY_ERROR_UPDATE, tileForestry); + this.tileForestry = tileForestry; + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + tileForestry.writeErrorData(data); + } + + @Override + protected void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + + TileEntity tile = getTarget(Proxies.common.getRenderWorld()); + if (tile instanceof TileForestry) { + ((TileForestry) tile).readErrorData(data); + } + } +} diff --git a/src/main/java/forestry/core/network/PacketFXSignal.java b/src/main/java/forestry/core/network/PacketFXSignal.java index 39c156121..7bfe8669e 100755 --- a/src/main/java/forestry/core/network/PacketFXSignal.java +++ b/src/main/java/forestry/core/network/PacketFXSignal.java @@ -10,8 +10,6 @@ ******************************************************************************/ package forestry.core.network; -import java.io.DataInputStream; -import java.io.DataOutputStream; import java.io.IOException; import net.minecraft.block.Block; @@ -30,11 +28,13 @@ public class PacketFXSignal extends PacketCoordinates { NONE(""), BLOCK_DESTROY(""), BLOCK_PLACE(""), LEAF("step.grass"), LOG("dig.wood"), DIRT("dig.gravel"); public final String soundFile; - public final float volume = 1.0f; - public final float pitch = 1.0f; + public final float volume; + public final float pitch; SoundFXType(String soundFile) { this.soundFile = soundFile; + this.volume = 1.0f; + this.pitch = 1.0f; } } @@ -44,7 +44,8 @@ public class PacketFXSignal extends PacketCoordinates { private Block block; private int meta; - public PacketFXSignal() { + public PacketFXSignal(DataInputStreamForestry data) throws IOException { + super(data); } public PacketFXSignal(VisualFXType type, int xCoord, int yCoord, int zCoord, Block block, int meta) { @@ -56,7 +57,7 @@ public class PacketFXSignal extends PacketCoordinates { } public PacketFXSignal(VisualFXType visualFX, SoundFXType soundFX, int xCoord, int yCoord, int zCoord, Block block, int meta) { - super(PacketIds.FX_SIGNAL, xCoord, yCoord, zCoord); + super(PacketId.FX_SIGNAL, xCoord, yCoord, zCoord); this.visualFX = visualFX; this.soundFX = soundFX; this.block = block; @@ -64,7 +65,7 @@ public class PacketFXSignal extends PacketCoordinates { } @Override - public void writeData(DataOutputStream data) throws IOException { + public void writeData(DataOutputStreamForestry data) throws IOException { super.writeData(data); data.writeShort(visualFX.ordinal()); data.writeShort(soundFX.ordinal()); @@ -73,7 +74,7 @@ public class PacketFXSignal extends PacketCoordinates { } @Override - public void readData(DataInputStream data) throws IOException { + protected void readData(DataInputStreamForestry data) throws IOException { super.readData(data); this.visualFX = VisualFXType.values()[data.readShort()]; this.soundFX = SoundFXType.values()[data.readShort()]; @@ -95,5 +96,4 @@ public class PacketFXSignal extends PacketCoordinates { } } } - } diff --git a/src/main/java/forestry/core/network/PacketGuiInteger.java b/src/main/java/forestry/core/network/PacketGuiInteger.java index 1e013df0e..f2e0bc256 100644 --- a/src/main/java/forestry/core/network/PacketGuiInteger.java +++ b/src/main/java/forestry/core/network/PacketGuiInteger.java @@ -10,8 +10,6 @@ ******************************************************************************/ package forestry.core.network; -import java.io.DataInputStream; -import java.io.DataOutputStream; import java.io.IOException; import net.minecraft.client.entity.EntityClientPlayerMP; @@ -26,25 +24,26 @@ public class PacketGuiInteger extends ForestryPacket { private int windowId, dataId, value; - public PacketGuiInteger() { - super(); + public PacketGuiInteger(DataInputStreamForestry data) throws IOException { + super(data); } public PacketGuiInteger(int windowId, int dataId, int value) { + super(PacketId.GUI_INTEGER); this.windowId = windowId; this.dataId = dataId; this.value = value; } @Override - public void writeData(DataOutputStream data) throws IOException { + public void writeData(DataOutputStreamForestry data) throws IOException { data.writeByte(windowId); data.writeByte(dataId); data.writeInt(value); } @Override - public void readData(DataInputStream data) throws IOException { + protected void readData(DataInputStreamForestry data) throws IOException { windowId = data.readByte(); dataId = data.readByte(); value = data.readInt(); @@ -55,10 +54,4 @@ public class PacketGuiInteger extends ForestryPacket { player.openContainer.updateProgressBar(dataId, value); } } - - @Override - public int getID() { - return PacketIds.GUI_INTEGER; - } - } diff --git a/src/main/java/forestry/core/network/PacketGuiSelect.java b/src/main/java/forestry/core/network/PacketGuiSelect.java new file mode 100644 index 000000000..bc86f9cda --- /dev/null +++ b/src/main/java/forestry/core/network/PacketGuiSelect.java @@ -0,0 +1,50 @@ +/******************************************************************************* + * 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 java.io.IOException; + +public class PacketGuiSelect extends ForestryPacket { + private int primaryIndex; + private int secondaryIndex; + + public PacketGuiSelect(DataInputStreamForestry data) throws IOException { + super(data); + } + + public PacketGuiSelect(PacketId id, int primaryIndex, int secondaryIndex) { + super(id); + this.primaryIndex = primaryIndex; + this.secondaryIndex = secondaryIndex; + } + + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeInt(primaryIndex); + data.writeInt(secondaryIndex); + } + + @Override + protected void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + primaryIndex = data.readInt(); + secondaryIndex = data.readInt(); + } + + public int getPrimaryIndex() { + return primaryIndex; + } + + public int getSecondaryIndex() { + return secondaryIndex; + } +} diff --git a/src/main/java/forestry/core/network/PacketHandler.java b/src/main/java/forestry/core/network/PacketHandler.java index 8ae619a49..9367ab031 100755 --- a/src/main/java/forestry/core/network/PacketHandler.java +++ b/src/main/java/forestry/core/network/PacketHandler.java @@ -10,13 +10,11 @@ ******************************************************************************/ package forestry.core.network; -import java.io.DataInputStream; import java.io.InputStream; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.Container; -import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.network.NetHandlerPlayServer; import net.minecraft.tileentity.TileEntity; @@ -35,6 +33,8 @@ import forestry.api.core.ForestryEvent; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IBreedingTracker; import forestry.api.genetics.ISpeciesRoot; +import forestry.apiculture.network.PacketActiveUpdate; +import forestry.core.circuits.ContainerSolderingIron; import forestry.core.circuits.ItemCircuitBoard; import forestry.core.gadgets.TileForestry; import forestry.core.gui.ContainerLiquidTanks; @@ -47,6 +47,8 @@ import forestry.plugins.PluginManager; import io.netty.buffer.ByteBufInputStream; public class PacketHandler { + private final FMLEventChannel channel; + public PacketHandler() { channel = NetworkRegistry.INSTANCE.newEventDrivenChannel(ForestryPacket.channel); channel.register(this); @@ -54,101 +56,110 @@ public class PacketHandler { @SubscribeEvent public void onPacket(ServerCustomPacketEvent event) { - onPacketData(new ByteBufInputStream(event.packet.payload()), - ((NetHandlerPlayServer) event.handler).playerEntity); + onPacketData(event.packet, ((NetHandlerPlayServer) event.handler).playerEntity); } @SubscribeEvent public void onPacket(ClientCustomPacketEvent event) { - onPacketData(new ByteBufInputStream(event.packet.payload()), null); + onPacketData(event.packet, null); } /** Returns true if the packet has been handled */ - public boolean onPacketData(InputStream is, EntityPlayerMP player) { - DataInputStream data = new DataInputStream(is); - PacketUpdate packetU; + private static boolean onPacketData(FMLProxyPacket fmlPacket, EntityPlayerMP player) { + InputStream is = new ByteBufInputStream(fmlPacket.payload()); + DataInputStreamForestry data = new DataInputStreamForestry(is); try { - int packetId = data.readByte(); + int packetIdOrdinal = data.readByte(); + if (packetIdOrdinal >= PacketId.VALUES.length) { + return false; + } + PacketId packetId = PacketId.VALUES[packetIdOrdinal]; switch (packetId) { - case PacketIds.TILE_FORESTRY_UPDATE: - PacketTileUpdate packetT = new PacketTileUpdate(); - packetT.readData(data); - onTileUpdate(packetT); + case TILE_FORESTRY_UPDATE: { + PacketTileStream.onPacketData(data); return true; - case PacketIds.TILE_UPDATE: - PacketUpdate packetUpdate = new PacketUpdate(); - packetUpdate.readData(data); - onTileUpdate(packetUpdate); + } + case TILE_FORESTRY_ERROR_UPDATE: { + PacketErrorUpdate.onPacketData(data); return true; - case PacketIds.TILE_NBT: - PacketTileNBT packetN = new PacketTileNBT(); - packetN.readData(data); - onTileUpdate(packetN); + } + case TILE_FORESTRY_GUI_OPENED: { + PacketTileGuiOpened.onPacketData(data); return true; - case PacketIds.SOCKET_UPDATE: - PacketSocketUpdate packetS = new PacketSocketUpdate(); - packetS.readData(data); + } + case TILE_FORESTRY_ACTIVE: { + PacketActiveUpdate.onPacketData(data); + return true; + } + case SOCKET_UPDATE: { + PacketSocketUpdate packetS = new PacketSocketUpdate(data); onSocketUpdate(packetS); return true; - case PacketIds.IINVENTORY_STACK: - PacketInventoryStack packetQ = new PacketInventoryStack(); - packetQ.readData(data); - onInventoryStack(packetQ); - return true; - case PacketIds.FX_SIGNAL: - PacketFXSignal packetF = new PacketFXSignal(); - packetF.readData(data); - packetF.executeFX(); + } + case FX_SIGNAL: { + PacketFXSignal packet = new PacketFXSignal(data); + packet.executeFX(); return true; + } - case PacketIds.PIPETTE_CLICK: - packetU = new PacketUpdate(); - packetU.readData(data); - onPipetteClick(packetU, player); + case PIPETTE_CLICK: { + PacketSlotClick packet = new PacketSlotClick(data); + onPipetteClick(packet, player); return true; - case PacketIds.SOLDERING_IRON_CLICK: - packetU = new PacketUpdate(); - packetU.readData(data); - onSolderingIronClick(packetU, player); + } + case SOLDERING_IRON_CLICK: { + PacketSlotClick packet = new PacketSlotClick(data); + onSolderingIronClick(packet, player); return true; - case PacketIds.CHIPSET_CLICK: - packetU = new PacketUpdate(); - packetU.readData(data); - onChipsetClick(packetU, player); + } + case CHIPSET_CLICK: { + PacketSlotClick packet = new PacketSlotClick(data); + onChipsetClick(packet, player); return true; - case PacketIds.ACCESS_SWITCH: - PacketCoordinates packetC = new PacketCoordinates(); - packetC.readData(data); - onAccessSwitch(packetC, player); + } + case ACCESS_SWITCH: { + PacketCoordinates packet = new PacketCoordinates(data); + onAccessSwitch(packet, player); return true; - case PacketIds.GUI_SELECTION: - PacketUpdate packetI = new PacketUpdate(); - packetI.readData(data); - onGuiSelection(packetI); + } + case GUI_SELECTION_SET: { + PacketGuiSelect packet = new PacketGuiSelect(data); + onGuiSelection(packet); return true; - case PacketIds.GUI_SELECTION_CHANGE: - PacketUpdate packetZ = new PacketUpdate(); - packetZ.readData(data); - onGuiChange(player, packetZ); + } + case GUI_SELECTION_CHANGE: { + PacketGuiSelect packet = new PacketGuiSelect(data); + onGuiChange(player, packet); return true; - case PacketIds.GENOME_TRACKER_UPDATE: - PacketNBT packetTR = new PacketNBT(); - packetTR.readData(data); - onGenomeTrackerUpdate(packetTR); + } + case GUI_LAYOUT_SELECT: { + PacketString packet = new PacketString(data); + onGuiLayoutSelect(packet); return true; - case PacketIds.GUI_INTEGER: - PacketGuiInteger packet = new PacketGuiInteger(); - packet.readData(data); + } + case GENOME_TRACKER_UPDATE: { + PacketNBT packet = new PacketNBT(data); + onGenomeTrackerUpdate(packet); return true; - default: - for (forestry.core.interfaces.IPacketHandler handler : PluginManager.packetHandlers) { + } + case GUI_INTEGER: { + PacketGuiInteger packet = new PacketGuiInteger(data); + return true; + } + case GUI_ITEMSTACK: { + PacketItemStackDisplay.onPacketData(data); + return true; + } + default: { + for (IPacketHandler handler : PluginManager.packetHandlers) { if (handler.onPacketData(packetId, data, player)) { return true; } } + } } } catch (Exception ex) { ex.printStackTrace(); @@ -157,19 +168,11 @@ public class PacketHandler { return false; } - public void sendPacket(FMLProxyPacket packet) { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { - channel.sendToServer(packet); - } else { - channel.sendToAll(packet); - } - } - public void sendPacket(FMLProxyPacket packet, EntityPlayerMP player) { channel.sendTo(packet, player); } - private void onGenomeTrackerUpdate(PacketNBT packet) { + private static void onGenomeTrackerUpdate(PacketNBT packet) { assert FMLCommonHandler.instance().getEffectiveSide().isClient(); EntityPlayer player = Proxies.common.getPlayer(); @@ -186,7 +189,7 @@ public class PacketHandler { } } - private void onGuiChange(EntityPlayer player, PacketUpdate packet) { + private static void onGuiChange(EntityPlayer player, PacketGuiSelect packet) { assert FMLCommonHandler.instance().getEffectiveSide().isServer(); if (!(player.openContainer instanceof IGuiSelectable)) { @@ -196,7 +199,7 @@ public class PacketHandler { ((IGuiSelectable) player.openContainer).handleSelectionChange(player, packet); } - private void onGuiSelection(PacketUpdate packet) { + private static void onGuiSelection(PacketGuiSelect packet) { assert FMLCommonHandler.instance().getEffectiveSide().isClient(); EntityPlayer player = Proxies.common.getPlayer(); @@ -207,10 +210,22 @@ public class PacketHandler { } ((IGuiSelectable) container).setSelection(packet); - } - private void onSocketUpdate(PacketSocketUpdate packet) { + private static void onGuiLayoutSelect(PacketString packet) { + assert FMLCommonHandler.instance().getEffectiveSide().isClient(); + + EntityPlayer player = Proxies.common.getPlayer(); + + Container container = player.openContainer; + if (!(container instanceof ContainerSolderingIron)) { + return; + } + + ((ContainerSolderingIron) container).setLayout(packet.getString()); + } + + private static void onSocketUpdate(PacketSocketUpdate packet) { assert FMLCommonHandler.instance().getEffectiveSide().isClient(); TileEntity tile = packet.getTarget(Proxies.common.getRenderWorld()); @@ -219,33 +234,12 @@ public class PacketHandler { } ISocketable socketable = (ISocketable) tile; - for (int i = 0; i < packet.itemstacks.length; i++) { - socketable.setSocket(i, packet.itemstacks[i]); + for (int i = 0; i < packet.itemStacks.length; i++) { + socketable.setSocket(i, packet.itemStacks[i]); } } - private void onTileUpdate(ForestryPacket packet) { - - TileEntity tile = ((ILocatedPacket) packet).getTarget(Proxies.common.getRenderWorld()); - if (tile instanceof INetworkedEntity) { - ((INetworkedEntity) tile).fromPacket(packet); - } - - } - - private void onInventoryStack(PacketInventoryStack packet) { - - TileEntity tile = packet.getTarget(Proxies.common.getRenderWorld()); - if (tile == null) { - return; - } - - if (tile instanceof IInventory) { - ((IInventory) tile).setInventorySlotContents(packet.slotIndex, packet.itemstack); - } - } - - private void onChipsetClick(PacketUpdate packet, EntityPlayer player) { + private static void onChipsetClick(PacketSlotClick packet, EntityPlayer player) { assert FMLCommonHandler.instance().getEffectiveSide().isServer(); if (!(player.openContainer instanceof ContainerSocketed)) { @@ -256,11 +250,10 @@ public class PacketHandler { return; } - ((ContainerSocketed) player.openContainer).handleChipsetClick(packet.payload.intPayload[0], player, itemstack); - + ((ContainerSocketed) player.openContainer).handleChipsetClick(packet.getSlot(), player, itemstack); } - private void onSolderingIronClick(PacketUpdate packet, EntityPlayer player) { + private static void onSolderingIronClick(PacketSlotClick packet, EntityPlayer player) { assert FMLCommonHandler.instance().getEffectiveSide().isServer(); if (!(player.openContainer instanceof ContainerSocketed)) { @@ -268,10 +261,10 @@ public class PacketHandler { } ItemStack itemstack = player.inventory.getItemStack(); - ((ContainerSocketed) player.openContainer).handleSolderingIronClick(packet.payload.intPayload[0], player, itemstack); + ((ContainerSocketed) player.openContainer).handleSolderingIronClick(packet.getSlot(), player, itemstack); } - private void onAccessSwitch(PacketCoordinates packet, EntityPlayer playerEntity) { + private static void onAccessSwitch(PacketCoordinates packet, EntityPlayer playerEntity) { assert FMLCommonHandler.instance().getEffectiveSide().isServer(); TileForestry tile = (TileForestry) packet.getTarget(playerEntity.worldObj); @@ -282,15 +275,13 @@ public class PacketHandler { tile.switchAccessRule(playerEntity); } - private void onPipetteClick(PacketUpdate packet, EntityPlayerMP player) { + private static void onPipetteClick(PacketSlotClick packet, EntityPlayerMP player) { assert FMLCommonHandler.instance().getEffectiveSide().isServer(); if (!(player.openContainer instanceof ContainerLiquidTanks)) { return; } - ((ContainerLiquidTanks) player.openContainer).handlePipetteClick(packet.payload.intPayload[0], player); + ((ContainerLiquidTanks) player.openContainer).handlePipetteClick(packet.getSlot(), player); } - - private final FMLEventChannel channel; } diff --git a/src/main/java/forestry/core/network/PacketId.java b/src/main/java/forestry/core/network/PacketId.java new file mode 100644 index 000000000..cb9cbc376 --- /dev/null +++ b/src/main/java/forestry/core/network/PacketId.java @@ -0,0 +1,62 @@ +/******************************************************************************* + * 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; + +public enum PacketId { + INVALID, + + TILE_FORESTRY_UPDATE, + TILE_FORESTRY_ERROR_UPDATE, + TILE_FORESTRY_GUI_OPENED, + TILE_FORESTRY_ACTIVE, + FX_SIGNAL, + + WORKTABLE_MEMORY_UPDATE, + + HABITAT_BIOME_POINTER, + CANDLE, + + GUI_SELECTION_CHANGE, + IMPRINT_SELECTION_GET, + GUI_SELECTION_SET, + GUI_LAYOUT_SELECT, + GUI_INTEGER, + GUI_ITEMSTACK, + + PIPETTE_CLICK, + + ACCESS_SWITCH, + + GENOME_TRACKER_UPDATE, + GAME_TOKEN_SET, + + CHIPSET_CLICK, + SOLDERING_IRON_CLICK, + SOCKET_UPDATE, + + LETTER_REQUEST_INFO, + LETTER_TEXT, + TRADING_ADDRESS_SET, + LETTER_INFO, + POBOX_INFO, + POBOX_INFO_REQUEST, + + RIPENING_UPDATE, + + // Propolis pipe + PROP_SEND_FILTER_SET, + PROP_REQUEST_FILTER_SET, + PROP_SEND_FILTER_CHANGE_GENOME, + PROP_SEND_FILTER_CHANGE_TYPE + ; + + public static final PacketId[] VALUES = values(); +} diff --git a/src/main/java/forestry/core/network/PacketIds.java b/src/main/java/forestry/core/network/PacketIds.java deleted file mode 100755 index 7550c9214..000000000 --- a/src/main/java/forestry/core/network/PacketIds.java +++ /dev/null @@ -1,63 +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; - -/** - * Valid ids: 0 - 127 - */ -public class PacketIds { - - public static final int TILE_FORESTRY_UPDATE = 0; - public static final int TILE_UPDATE = 1; - public static final int TILE_DESCRIPTION = 2; - public static final int IINVENTORY_STACK = 3; - public static final int FX_SIGNAL = 4; - public static final int TILE_NBT = 5; - - public static final int HABITAT_BIOME_POINTER = 20; - public static final int CANDLE = 21; - - public static final int GUI_SELECTION_CHANGE = 30; - public static final int IMPRINT_SELECTION_GET = 31; - public static final int GUI_SELECTION = 32; - - public static final int PIPETTE_CLICK = 40; - - public static final int ACCESS_SWITCH = 50; - - public static final int GENOME_TRACKER_UPDATE = 60; - public static final int GAME_TOKEN_SET = 61; - - public static final int CHIPSET_CLICK = 70; - public static final int SOLDERING_IRON_CLICK = 71; - public static final int SOCKET_UPDATE = 72; - - 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 LETTER_INFO = 83; - public static final int POBOX_INFO = 85; - public static final int POBOX_INFO_REQUEST = 86; - - public static final int SAPLING = 89; - public static final int LEAF = 90; - public static final int RIPENING_UPDATE = 91; - - public static final int GUI_INTEGER = 92; - - // Propolis pipe - public static final int PROP_SEND_FILTER_SET = 100; - public static final int PROP_REQUEST_FILTER_SET = 101; - public static final int PROP_SEND_FILTER_CHANGE_GENOME = 102; - public static final int PROP_SEND_FILTER_CHANGE_TYPE = 103; - - -} diff --git a/src/main/java/forestry/core/network/PacketItemStackDisplay.java b/src/main/java/forestry/core/network/PacketItemStackDisplay.java new file mode 100644 index 000000000..046ef8a83 --- /dev/null +++ b/src/main/java/forestry/core/network/PacketItemStackDisplay.java @@ -0,0 +1,55 @@ +/******************************************************************************* + * 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 java.io.IOException; + +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; + +import forestry.core.gadgets.TileForestry; +import forestry.core.interfaces.IItemStackDisplay; +import forestry.core.proxy.Proxies; + +public class PacketItemStackDisplay extends PacketCoordinates { + + private ItemStack itemStack; + + public static void onPacketData(DataInputStreamForestry data) throws IOException { + new PacketItemStackDisplay(data); + } + + public PacketItemStackDisplay(DataInputStreamForestry data) throws IOException { + super(data); + } + + public PacketItemStackDisplay(T tile, ItemStack itemStack) { + super(PacketId.GUI_ITEMSTACK, tile); + this.itemStack = itemStack; + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeItemStack(itemStack); + } + + @Override + protected void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + itemStack = data.readItemStack(); + + TileEntity tile = getTarget(Proxies.common.getRenderWorld()); + if (tile instanceof IItemStackDisplay) { + ((IItemStackDisplay) tile).handleItemStackForDisplay(itemStack); + } + } +} diff --git a/src/main/java/forestry/core/network/PacketNBT.java b/src/main/java/forestry/core/network/PacketNBT.java index c221b484b..d6dfd5ae1 100755 --- a/src/main/java/forestry/core/network/PacketNBT.java +++ b/src/main/java/forestry/core/network/PacketNBT.java @@ -10,43 +10,31 @@ ******************************************************************************/ package forestry.core.network; -import java.io.ByteArrayInputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; import java.io.IOException; -import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; public class PacketNBT extends ForestryPacket { protected NBTTagCompound nbttagcompound; - public PacketNBT() { + public PacketNBT(DataInputStreamForestry data) throws IOException { + super(data); } - public PacketNBT(int id) { - super(id); - } - - public PacketNBT(int id, NBTTagCompound nbttagcompound) { + public PacketNBT(PacketId id, NBTTagCompound nbttagcompound) { super(id); this.nbttagcompound = nbttagcompound; } @Override - public void writeData(DataOutputStream data) throws IOException { - byte[] compressed = CompressedStreamTools.compress(nbttagcompound); - data.writeShort(compressed.length); - data.write(compressed); + public void writeData(DataOutputStreamForestry data) throws IOException { + data.writeNBTTagCompound(nbttagcompound); } @Override - public void readData(DataInputStream data) throws IOException { - short length = data.readShort(); - byte[] compressed = new byte[length]; - data.readFully(compressed); - this.nbttagcompound = CompressedStreamTools.readCompressed(new ByteArrayInputStream(compressed)); + protected void readData(DataInputStreamForestry data) throws IOException { + this.nbttagcompound = data.readNBTTagCompound(); } public NBTTagCompound getTagCompound() { diff --git a/src/main/java/forestry/core/network/PacketPayload.java b/src/main/java/forestry/core/network/PacketPayload.java deleted file mode 100755 index 4b1deb2d8..000000000 --- a/src/main/java/forestry/core/network/PacketPayload.java +++ /dev/null @@ -1,66 +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 forestry.core.utils.Utils; - -public class PacketPayload { - public int[] intPayload = new int[0]; - public short[] shortPayload = new short[0]; - public float[] floatPayload = new float[0]; - public String[] stringPayload = new String[0]; - - public PacketPayload() { - } - - public PacketPayload(int intSize, int floatSize, int stringSize) { - intPayload = new int[intSize]; - floatPayload = new float[floatSize]; - stringPayload = new String[stringSize]; - } - - public PacketPayload(int intSize, int shortSize) { - intPayload = new int[intSize]; - shortPayload = new short[shortSize]; - } - - public void append(PacketPayload other) { - if (other == null) { - return; - } - - if (other.intPayload.length > 0) { - this.intPayload = Utils.concat(this.intPayload, other.intPayload); - } - if (other.shortPayload.length > 0) { - this.shortPayload = Utils.concat(this.shortPayload, other.shortPayload); - } - if (other.floatPayload.length > 0) { - this.floatPayload = Utils.concat(this.floatPayload, other.floatPayload); - } - if (other.stringPayload.length > 0) { - this.stringPayload = Utils.concat(this.stringPayload, other.stringPayload); - } - - } - - public void append(int[] other) { - if (other == null || other.length < 0) { - return; - } - - this.intPayload = Utils.concat(this.intPayload, other); - } - - public boolean isEmpty() { - return intPayload.length == 0 && shortPayload.length == 0 && floatPayload.length == 0 && stringPayload.length == 0; - } -} diff --git a/src/main/java/forestry/core/network/PacketInventoryStack.java b/src/main/java/forestry/core/network/PacketSlotClick.java old mode 100755 new mode 100644 similarity index 50% rename from src/main/java/forestry/core/network/PacketInventoryStack.java rename to src/main/java/forestry/core/network/PacketSlotClick.java index fbc8cdbf2..cd962ea30 --- a/src/main/java/forestry/core/network/PacketInventoryStack.java +++ b/src/main/java/forestry/core/network/PacketSlotClick.java @@ -1,47 +1,44 @@ -/******************************************************************************* - * 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 java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import net.minecraft.item.ItemStack; - -public class PacketInventoryStack extends PacketCoordinates { - - public int slotIndex; - public ItemStack itemstack; - - public PacketInventoryStack() { - } - - public PacketInventoryStack(int id, int posX, int posY, int posZ, int slotIndex, ItemStack itemstack) { - super(id, posX, posY, posZ); - this.slotIndex = slotIndex; - this.itemstack = itemstack; - } - - @Override - public void writeData(DataOutputStream data) throws IOException { - super.writeData(data); - data.writeInt(slotIndex); - writeItemStack(itemstack, data); - } - - @Override - public void readData(DataInputStream data) throws IOException { - super.readData(data); - slotIndex = data.readInt(); - itemstack = readItemStack(data); - } - -} +/******************************************************************************* + * 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 java.io.IOException; + +import net.minecraft.tileentity.TileEntity; + +public class PacketSlotClick extends PacketCoordinates { + private int slot; + + public PacketSlotClick(DataInputStreamForestry data) throws IOException { + super(data); + } + + public PacketSlotClick(PacketId id, TileEntity tile, int slot) { + super(id, tile); + this.slot = slot; + } + + @Override + protected void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + this.slot = data.readVarInt(); + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeVarInt(slot); + } + + public int getSlot() { + return slot; + } +} diff --git a/src/main/java/forestry/core/network/PacketSocketUpdate.java b/src/main/java/forestry/core/network/PacketSocketUpdate.java index 0a7e8167b..6e1f7570b 100755 --- a/src/main/java/forestry/core/network/PacketSocketUpdate.java +++ b/src/main/java/forestry/core/network/PacketSocketUpdate.java @@ -10,48 +10,41 @@ ******************************************************************************/ package forestry.core.network; -import java.io.DataInputStream; -import java.io.DataOutputStream; import java.io.IOException; import net.minecraft.item.ItemStack; +import forestry.core.gadgets.TileForestry; import forestry.core.interfaces.ISocketable; public class PacketSocketUpdate extends PacketCoordinates { - public ItemStack[] itemstacks; + public ItemStack[] itemStacks; - public PacketSocketUpdate() { + public PacketSocketUpdate(DataInputStreamForestry data) throws IOException { + super(data); } - public PacketSocketUpdate(int id, int posX, int posY, int posZ, ISocketable tile) { - super(id, posX, posY, posZ); + public PacketSocketUpdate(PacketId id, T tile) { + super(id, tile); - itemstacks = new ItemStack[tile.getSocketCount()]; + itemStacks = new ItemStack[tile.getSocketCount()]; for (int i = 0; i < tile.getSocketCount(); i++) { - itemstacks[i] = tile.getSocket(i); + itemStacks[i] = tile.getSocket(i); } } @Override - public void writeData(DataOutputStream data) throws IOException { + protected void writeData(DataOutputStreamForestry data) throws IOException { super.writeData(data); - data.writeShort(itemstacks.length); - for (ItemStack itemstack : itemstacks) { - writeItemStack(itemstack, data); - } + data.writeItemStacks(itemStacks); } @Override - public void readData(DataInputStream data) throws IOException { + protected void readData(DataInputStreamForestry data) throws IOException { super.readData(data); - int sockets = data.readShort(); - itemstacks = new ItemStack[sockets]; - for (int i = 0; i < sockets; i++) { - itemstacks[i] = readItemStack(data); - } + itemStacks = data.readItemStacks(); } } diff --git a/src/main/java/forestry/core/network/PacketString.java b/src/main/java/forestry/core/network/PacketString.java new file mode 100644 index 000000000..dd602658a --- /dev/null +++ b/src/main/java/forestry/core/network/PacketString.java @@ -0,0 +1,43 @@ +/******************************************************************************* + * 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 java.io.IOException; + +public class PacketString extends ForestryPacket { + + private String string; + + public PacketString(DataInputStreamForestry data) throws IOException { + super(data); + } + + public PacketString(PacketId id, String string) { + super(id); + this.string = string; + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeUTF(string); + } + + @Override + protected void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + string = data.readUTF(); + } + + public String getString() { + return string; + } +} diff --git a/src/main/java/forestry/core/network/PacketTileGuiOpened.java b/src/main/java/forestry/core/network/PacketTileGuiOpened.java new file mode 100644 index 000000000..ab5ee0c96 --- /dev/null +++ b/src/main/java/forestry/core/network/PacketTileGuiOpened.java @@ -0,0 +1,52 @@ +/******************************************************************************* + * 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 java.io.IOException; + +import net.minecraft.tileentity.TileEntity; + +import forestry.core.gadgets.TileForestry; +import forestry.core.proxy.Proxies; + +public class PacketTileGuiOpened extends PacketCoordinates { + + private TileForestry tileForestry; + + public static void onPacketData(DataInputStreamForestry data) throws IOException { + new PacketTileGuiOpened(data); + } + + private PacketTileGuiOpened(DataInputStreamForestry data) throws IOException { + super(data); + } + + public PacketTileGuiOpened(TileForestry tileForestry) { + super(PacketId.TILE_FORESTRY_GUI_OPENED, tileForestry); + this.tileForestry = tileForestry; + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + tileForestry.writeGuiData(data); + } + + @Override + protected void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + + TileEntity tile = getTarget(Proxies.common.getRenderWorld()); + if (tile instanceof TileForestry) { + ((TileForestry) tile).readGuiData(data); + } + } +} diff --git a/src/main/java/forestry/core/network/PacketTileNBT.java b/src/main/java/forestry/core/network/PacketTileNBT.java deleted file mode 100755 index 2e5b7c4ed..000000000 --- a/src/main/java/forestry/core/network/PacketTileNBT.java +++ /dev/null @@ -1,66 +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 java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; - -public class PacketTileNBT extends PacketNBT implements ILocatedPacket { - - private int posX; - private int posY; - private int posZ; - - public PacketTileNBT() { - } - - public PacketTileNBT(int id, TileEntity tile) { - super(id); - - posX = tile.xCoord; - posY = tile.yCoord; - posZ = tile.zCoord; - - this.nbttagcompound = new NBTTagCompound(); - tile.writeToNBT(nbttagcompound); - } - - @Override - public void writeData(DataOutputStream data) throws IOException { - - data.writeInt(posX); - data.writeInt(posY); - data.writeInt(posZ); - - super.writeData(data); - } - - @Override - public void readData(DataInputStream data) throws IOException { - - posX = data.readInt(); - posY = data.readInt(); - posZ = data.readInt(); - - super.readData(data); - } - - @Override - public TileEntity getTarget(World world) { - return world.getTileEntity(posX, posY, posZ); - } - -} diff --git a/src/main/java/forestry/core/network/PacketTileStream.java b/src/main/java/forestry/core/network/PacketTileStream.java new file mode 100644 index 000000000..856d1ab78 --- /dev/null +++ b/src/main/java/forestry/core/network/PacketTileStream.java @@ -0,0 +1,51 @@ +/******************************************************************************* + * 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 java.io.IOException; + +import net.minecraft.tileentity.TileEntity; + +import forestry.core.proxy.Proxies; + +public class PacketTileStream extends PacketCoordinates { + + private IStreamable streamable; + + public static void onPacketData(DataInputStreamForestry data) throws IOException { + new PacketTileStream(data); + } + + public PacketTileStream(DataInputStreamForestry data) throws IOException { + super(data); + } + + public PacketTileStream(T streamable) { + super(PacketId.TILE_FORESTRY_UPDATE, streamable); + this.streamable = streamable; + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + streamable.writeData(data); + } + + @Override + protected void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + + TileEntity tile = getTarget(Proxies.common.getRenderWorld()); + if (tile instanceof IStreamable) { + ((IStreamable) tile).readData(data); + } + } +} diff --git a/src/main/java/forestry/core/network/PacketTileUpdate.java b/src/main/java/forestry/core/network/PacketTileUpdate.java deleted file mode 100755 index ce60dfa76..000000000 --- a/src/main/java/forestry/core/network/PacketTileUpdate.java +++ /dev/null @@ -1,123 +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 java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.HashSet; -import java.util.Set; -import java.util.UUID; - -import com.mojang.authlib.GameProfile; - -import net.minecraftforge.common.util.ForgeDirection; - -import forestry.api.core.ErrorStateRegistry; -import forestry.api.core.IErrorState; -import forestry.core.gadgets.TileForestry; -import forestry.core.utils.EnumAccess; - -public class PacketTileUpdate extends PacketUpdate { - - private ForgeDirection orientation = ForgeDirection.WEST; - private final Set errorStates; - - private boolean isOwnable = false; - private EnumAccess access = EnumAccess.SHARED; - private GameProfile owner = null; - - public PacketTileUpdate() { - errorStates = new HashSet(); - } - - public PacketTileUpdate(TileForestry tile) { - super(PacketIds.TILE_FORESTRY_UPDATE, tile); - - orientation = tile.getOrientation(); - errorStates = tile.getErrorStates(); - - isOwnable = tile.isOwnable(); - access = tile.getAccess(); - owner = tile.getOwnerProfile(); - } - - @Override - public void writeData(DataOutputStream data) throws IOException { - super.writeData(data); - - data.writeByte(orientation.ordinal()); - - data.writeShort(errorStates.size()); - for (IErrorState errorState : errorStates) { - data.writeShort(errorState.getID()); - } - - // TODO: Should this really be sent to the client? Huge network cost. - // As far as I know, only GUIs need it, and there are better ways to get the information to a GUI. - // -CovertJaguar - if (isOwnable) { - data.writeByte(access.ordinal()); - if (owner == null) { - data.writeBoolean(false); - } else { - data.writeBoolean(true); - data.writeLong(owner.getId().getMostSignificantBits()); - data.writeLong(owner.getId().getLeastSignificantBits()); - data.writeUTF(owner.getName()); - } - } else { - data.writeInt(-1); - } - } - - @Override - public void readData(DataInputStream data) throws IOException { - super.readData(data); - - orientation = ForgeDirection.getOrientation(data.readByte()); - - short errorStateCount = data.readShort(); - for (int i = 0; i < errorStateCount; i++) { - short errorStateId = data.readShort(); - IErrorState errorState = ErrorStateRegistry.getErrorState(errorStateId); - errorStates.add(errorState); - } - - int ordinal = data.readByte(); - isOwnable = ordinal >= 0; - if (isOwnable) { - access = EnumAccess.values()[ordinal]; - - if (data.readBoolean()) { - owner = new GameProfile(new UUID(data.readLong(), data.readLong()), data.readUTF()); - } else { - owner = null; - } - } - } - - public ForgeDirection getOrientation() { - return orientation; - } - - public Set getErrorStates() { - return errorStates; - } - - public EnumAccess getAccess() { - return access; - } - - public GameProfile getOwner() { - return owner; - } -} diff --git a/src/main/java/forestry/core/network/PacketUpdate.java b/src/main/java/forestry/core/network/PacketUpdate.java deleted file mode 100755 index cbb8079dd..000000000 --- a/src/main/java/forestry/core/network/PacketUpdate.java +++ /dev/null @@ -1,120 +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 java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import forestry.core.gadgets.TileForestry; - -public class PacketUpdate extends PacketCoordinates { - - public PacketPayload payload; - - public PacketUpdate() { - } - - public PacketUpdate(int id) { - this(id, 0, 0, 0, null); - } - - public PacketUpdate(int id, TileForestry tile) { - super(id, tile); - this.payload = tile.getPacketPayload(); - } - - public PacketUpdate(int id, PacketPayload payload) { - this(id, 0, 0, 0, payload); - } - - public PacketUpdate(int id, int posX, int posY, int posZ, PacketPayload payload) { - super(id, posX, posY, posZ); - - this.payload = payload; - } - - public PacketUpdate(int id, int posX, int posY, int posZ, short val) { - super(id, posX, posY, posZ); - - this.payload = new PacketPayload(0, 1); - this.payload.shortPayload[0] = val; - } - - public PacketUpdate(int id, int posX, int posY, int posZ, int val) { - super(id, posX, posY, posZ); - - this.payload = new PacketPayload(1, 0); - this.payload.intPayload[0] = val; - } - - @Override - public void writeData(DataOutputStream data) throws IOException { - - super.writeData(data); - - // No payload means no data - if (payload == null) { - data.writeInt(0); - data.writeInt(0); - data.writeInt(0); - data.writeInt(0); - return; - } - - data.writeInt(payload.intPayload.length); - data.writeInt(payload.shortPayload.length); - data.writeInt(payload.floatPayload.length); - data.writeInt(payload.stringPayload.length); - - for (int intData : payload.intPayload) { - data.writeInt(intData); - } - for (int shortData : payload.shortPayload) { - data.writeShort(shortData); - } - for (float floatData : payload.floatPayload) { - data.writeFloat(floatData); - } - for (String stringData : payload.stringPayload) { - data.writeUTF(stringData); - } - - } - - @Override - public void readData(DataInputStream data) throws IOException { - - super.readData(data); - - payload = new PacketPayload(); - - payload.intPayload = new int[data.readInt()]; - payload.shortPayload = new short[data.readInt()]; - payload.floatPayload = new float[data.readInt()]; - payload.stringPayload = new String[data.readInt()]; - - for (int i = 0; i < payload.intPayload.length; i++) { - payload.intPayload[i] = data.readInt(); - } - for (int i = 0; i < payload.shortPayload.length; i++) { - payload.shortPayload[i] = data.readShort(); - } - for (int i = 0; i < payload.floatPayload.length; i++) { - payload.floatPayload[i] = data.readFloat(); - } - for (int i = 0; i < payload.stringPayload.length; i++) { - payload.stringPayload[i] = data.readUTF(); - } - - } - -} diff --git a/src/main/java/forestry/core/proxy/ClientProxyCommon.java b/src/main/java/forestry/core/proxy/ClientProxyCommon.java index a85f241f2..4fa83e7a5 100755 --- a/src/main/java/forestry/core/proxy/ClientProxyCommon.java +++ b/src/main/java/forestry/core/proxy/ClientProxyCommon.java @@ -33,7 +33,7 @@ import forestry.apiculture.render.TextureHabitatLocator; import forestry.core.ForestryClient; import forestry.core.TickHandlerCoreClient; import forestry.core.WorldGenerator; -import forestry.core.config.Config; +import forestry.core.render.EntityHoneydustFX; import forestry.core.render.SpriteSheet; public class ClientProxyCommon extends ProxyCommon { @@ -162,26 +162,25 @@ public class ClientProxyCommon extends ProxyCommon { // FIXME: This is causing crashes. @Override public void addEntityBiodustFX(World world, double d1, double d2, double d3, float f1, float f2, float f3) { - if (!Config.enableParticleFX) { + if (!ClientProxyRender.shouldSpawnParticle(world)) { return; } // ModLoader.getMinecraftInstance().effectRenderer.addEffect(new EntityBiodustFX(world, d1, d2, d3, f1, f2, f3)); } - // FIXME: This is causing crashes. @Override public void addEntitySwarmFX(World world, double d1, double d2, double d3, float f1, float f2, float f3) { - if (!Config.enableParticleFX) { + if (!ClientProxyRender.shouldSpawnParticle(world)) { return; } - // ModLoader.getMinecraftInstance().effectRenderer.addEffect(new EntityHoneydustFX(world, d1, d2, d3, f1, f2, f3)); + getClientInstance().effectRenderer.addEffect(new EntityHoneydustFX(world, d1, d2, d3, f1, f2, f3)); } @Override public void addEntityExplodeFX(World world, double d1, double d2, double d3, float f1, float f2, float f3) { - if (!Config.enableParticleFX) { + if (!ClientProxyRender.shouldSpawnParticle(world)) { return; } diff --git a/src/main/java/forestry/core/proxy/ClientProxyRender.java b/src/main/java/forestry/core/proxy/ClientProxyRender.java index d13a46372..0f6001b20 100755 --- a/src/main/java/forestry/core/proxy/ClientProxyRender.java +++ b/src/main/java/forestry/core/proxy/ClientProxyRender.java @@ -75,27 +75,31 @@ public class ClientProxyRender extends ProxyRender { return new RenderEscritoire(); } - private boolean shouldSpawnParticle(World world, boolean canDisable) { - if (canDisable && !Config.enableParticleFX) { + public static boolean shouldSpawnParticle(World world) { + if (!Config.enableParticleFX) { return false; } + Minecraft mc = FMLClientHandler.instance().getClient(); int particleSetting = mc.gameSettings.particleSetting; - if (!canDisable && particleSetting > 1) { - particleSetting = 1; + + // minimal + if (particleSetting == 2) { + return world.rand.nextInt(10) == 0; } - if (particleSetting == 1 && world.rand.nextInt(3) == 0) { - particleSetting = 2; - } - if (particleSetting > 1) { - return false; + + // decreased + if (particleSetting == 1) { + return world.rand.nextInt(3) != 0; } + + // all return true; } @Override public void addSnowFX(World world, double xCoord, double yCoord, double zCoord, int color, int areaX, int areaY, int areaZ) { - if (!shouldSpawnParticle(world, true)) { + if (!shouldSpawnParticle(world)) { return; } diff --git a/src/main/java/forestry/core/proxy/ProxyCommon.java b/src/main/java/forestry/core/proxy/ProxyCommon.java index 021da79eb..88970dd9a 100755 --- a/src/main/java/forestry/core/proxy/ProxyCommon.java +++ b/src/main/java/forestry/core/proxy/ProxyCommon.java @@ -55,7 +55,7 @@ import forestry.core.config.ForestryBlock; import forestry.core.config.ForestryItem; import forestry.core.network.PacketCoordinates; import forestry.core.network.PacketFXSignal; -import forestry.core.network.PacketIds; +import forestry.core.network.PacketId; import forestry.core.render.SpriteSheet; import forestry.core.utils.StringUtil; import forestry.plugins.PluginManager; @@ -145,7 +145,7 @@ public class ProxyCommon { public void setHabitatLocatorCoordinates(Entity player, ChunkCoordinates coordinates) { if (coordinates != null) { - Forestry.packetHandler.sendPacket(new PacketCoordinates(PacketIds.HABITAT_BIOME_POINTER, coordinates).getPacket(), (EntityPlayerMP) player); + Forestry.packetHandler.sendPacket(new PacketCoordinates(PacketId.HABITAT_BIOME_POINTER, coordinates).getPacket(), (EntityPlayerMP) player); } } @@ -203,7 +203,7 @@ public class ProxyCommon { } public void playSoundFX(World world, int x, int y, int z, Block block) { - Proxies.net.sendNetworkPacket(new PacketFXSignal(PacketFXSignal.SoundFXType.LEAF, x, y, z, block, 0), x, y, z); + Proxies.net.sendNetworkPacket(new PacketFXSignal(PacketFXSignal.SoundFXType.LEAF, x, y, z, block, 0)); } public void playSoundFX(World world, int x, int y, int z, String sound, float volume, float pitch) { @@ -235,7 +235,7 @@ public class ProxyCommon { public void sendFXSignal(PacketFXSignal.VisualFXType visualFX, PacketFXSignal.SoundFXType soundFX, World world, int xCoord, int yCoord, int zCoord, Block block, int i) { if (Proxies.common.isSimulating(world)) { - Proxies.net.sendNetworkPacket(new PacketFXSignal(visualFX, soundFX, xCoord, yCoord, zCoord, block, i), xCoord, yCoord, zCoord); + Proxies.net.sendNetworkPacket(new PacketFXSignal(visualFX, soundFX, xCoord, yCoord, zCoord, block, i)); } } diff --git a/src/main/java/forestry/core/proxy/ProxyNetwork.java b/src/main/java/forestry/core/proxy/ProxyNetwork.java index f60c4da2a..a9a6a23f7 100755 --- a/src/main/java/forestry/core/proxy/ProxyNetwork.java +++ b/src/main/java/forestry/core/proxy/ProxyNetwork.java @@ -20,27 +20,35 @@ import net.minecraftforge.common.util.FakePlayer; import forestry.Forestry; import forestry.core.config.Defaults; import forestry.core.network.ForestryPacket; +import forestry.core.network.ILocatedPacket; public class ProxyNetwork { - public void sendNetworkPacket(ForestryPacket packet, int x, int y, int z) { + public

void sendNetworkPacket(P packet) { if (packet == null) { return; } + int x = packet.getPosX(); + int y = packet.getPosY(); + int z = packet.getPosZ(); World[] worlds = DimensionManager.getWorlds(); for (World world : worlds) { for (int j = 0; j < world.playerEntities.size(); j++) { EntityPlayerMP player = (EntityPlayerMP) world.playerEntities.get(j); - - if (Math.abs(player.posX - x) <= Defaults.NET_MAX_UPDATE_DISTANCE && Math.abs(player.posY - y) <= Defaults.NET_MAX_UPDATE_DISTANCE - && Math.abs(player.posZ - z) <= Defaults.NET_MAX_UPDATE_DISTANCE) { + if (isPlayerInRange(player, x, y, z)) { Forestry.packetHandler.sendPacket(packet.getPacket(), player); } } } } + private static boolean isPlayerInRange(EntityPlayerMP player, int x, int y, int z) { + return Math.abs(player.posX - x) <= Defaults.NET_MAX_UPDATE_DISTANCE && + Math.abs(player.posY - y) <= Defaults.NET_MAX_UPDATE_DISTANCE && + Math.abs(player.posZ - z) <= Defaults.NET_MAX_UPDATE_DISTANCE; + } + public void sendToPlayer(ForestryPacket packet, EntityPlayer entityplayer) { if (!(entityplayer instanceof EntityPlayerMP) || (entityplayer instanceof FakePlayer)) { return; diff --git a/src/main/java/forestry/core/render/EntityHoneydustFX.java b/src/main/java/forestry/core/render/EntityHoneydustFX.java index 1ae5520f8..18500ead9 100755 --- a/src/main/java/forestry/core/render/EntityHoneydustFX.java +++ b/src/main/java/forestry/core/render/EntityHoneydustFX.java @@ -21,16 +21,8 @@ public class EntityHoneydustFX extends EntityReddustFX { public EntityHoneydustFX(World world, double d, double d1, double d2, float f, float f1, float f2, float f3) { super(world, d, d1, d2, f, f1, f2, f3); - // float f4 = (float)Math.random() * 0.4F + 0.6F; - // particleRed = ((float)(Math.random() * 0.20000000298023224D) + 0.95F) - // * f1 * f4; - // particleGreen = ((float)(Math.random() * 0.20000000298023224D) + - // 0.75F) * f2 * f4; - // particleBlue = ((float)(Math.random() * 0.20000000298023224D) + 0.1F) - // * f3 * f4; - particleRed = 0.9F; - particleGreen = 0.75F; - particleBlue = 0F; + particleRed = 0.9F + (world.rand.nextFloat() * 0.2F); + particleGreen = 0.75F + (world.rand.nextFloat() * 0.2F); + particleBlue = 0F + (world.rand.nextFloat() * 0.2F); } - } diff --git a/src/main/java/forestry/core/utils/PlayerUtil.java b/src/main/java/forestry/core/utils/PlayerUtil.java index a2acc6aa5..6d91b70ef 100644 --- a/src/main/java/forestry/core/utils/PlayerUtil.java +++ b/src/main/java/forestry/core/utils/PlayerUtil.java @@ -26,7 +26,7 @@ public class PlayerUtil { } public static String getOwnerName(IOwnable ownable) { - GameProfile profile = ownable.getOwnerProfile(); + GameProfile profile = ownable.getOwner(); if (profile == null) { return StringUtil.localize("gui.derelict"); } else { diff --git a/src/main/java/forestry/core/utils/Schemata.java b/src/main/java/forestry/core/utils/Schemata.java index c2593d544..40ea5f47b 100755 --- a/src/main/java/forestry/core/utils/Schemata.java +++ b/src/main/java/forestry/core/utils/Schemata.java @@ -19,7 +19,7 @@ public class Schemata { private final char key; - private EnumStructureBlock(char key) { + EnumStructureBlock(char key) { this.key = key; } diff --git a/src/main/java/forestry/core/utils/ShapedRecipeCustom.java b/src/main/java/forestry/core/utils/ShapedRecipeCustom.java index 38596e907..a597df0de 100755 --- a/src/main/java/forestry/core/utils/ShapedRecipeCustom.java +++ b/src/main/java/forestry/core/utils/ShapedRecipeCustom.java @@ -80,22 +80,14 @@ public class ShapedRecipeCustom implements IDescriptiveRecipe { ItemStack[][] resources = new ItemStack[3][3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { - resources[i][j] = getStackInRowAndColumn(inventoryCrafting, i, j); + int k = i + j * 3; + resources[i][j] = inventoryCrafting.getStackInSlot(k); } } return matches(resources); } - public ItemStack getStackInRowAndColumn(IInventory inventory, int i, int j) { - if (i >= 0 && i < width) { - int k = i + j * width; - return inventory.getStackInSlot(k); - } else { - return null; - } - } - public boolean matches(ItemStack[][] resources) { for (int i = 0; i <= 3 - width; i++) { diff --git a/src/main/java/forestry/core/utils/StackUtils.java b/src/main/java/forestry/core/utils/StackUtils.java index c4f8ef25c..6892a2fc3 100755 --- a/src/main/java/forestry/core/utils/StackUtils.java +++ b/src/main/java/forestry/core/utils/StackUtils.java @@ -234,8 +234,7 @@ public class StackUtils { boolean matched = false; for (ItemStack cached : condensed) { - if (cached.isItemEqual(stack) - || (craftingEquivalency && isCraftingEquivalent(cached, stack, true, false))) { + if ((cached.isItemEqual(stack) && ItemStack.areItemStackTagsEqual(cached, stack)) || (craftingEquivalency && isCraftingEquivalent(cached, stack, true, false))) { cached.stackSize += maxCountedPerStack > 0 && stack.stackSize > maxCountedPerStack ? maxCountedPerStack : stack.stackSize; matched = true; } @@ -285,12 +284,11 @@ public class StackUtils { for (ItemStack offer : condensedOffered) { if (isCraftingEquivalent(req, offer, oreDictionary, craftingTools)) { - matched = true; int stackCount = (int) Math.floor(offer.stackSize / req.stackSize); - if (stackCount <= 0) { - return 0; - } else if (count == 0) { + matched |= (stackCount > 0); + + if (count == 0) { count = stackCount; } else if (count > stackCount) { count = stackCount; @@ -343,6 +341,12 @@ public class StackUtils { return false; } + if (base.hasTagCompound() && !base.stackTagCompound.hasNoTags()) { + if (!ItemStack.areItemStacksEqual(base, comparison)) { + return false; + } + } + if (oreDictionary) { int[] idsBase = OreDictionary.getOreIDs(base); Arrays.sort(idsBase); @@ -467,13 +471,17 @@ public class StackUtils { return block == getBlock(stack) && meta == stack.getItemDamage(); } - public static List parseItemStackStrings(String itemStackStrings) { + public static List parseItemStackStrings(String itemStackStrings, int missingMetaValue) { String[] parts = itemStackStrings.split("(\\s*;\\s*)+"); + return parseItemStackStrings(parts, missingMetaValue); + } + + public static List parseItemStackStrings(String[] parts, int missingMetaValue) { List itemStacks = new ArrayList(); for (String itemStackString : parts) { - ItemStack itemStack = StackUtils.parseItemStackString(itemStackString); + ItemStack itemStack = StackUtils.parseItemStackString(itemStackString, missingMetaValue); if (itemStack != null) { itemStacks.add(itemStack); } @@ -482,7 +490,7 @@ public class StackUtils { return itemStacks; } - public static ItemStack parseItemStackString(String itemStackString) { + public static ItemStack parseItemStackString(String itemStackString, int missingMetaValue) { itemStackString = itemStackString.trim(); if (itemStackString.isEmpty()) { return null; @@ -495,16 +503,16 @@ public class StackUtils { return null; } - String name = parts[0] + ":" + parts[1]; + String name = parts[0] + ':' + parts[1]; int meta; if (parts.length == 2) { - meta = 0; + meta = missingMetaValue; } else { try { meta = parts[2].equals("*") ? OreDictionary.WILDCARD_VALUE : NumberFormat.getIntegerInstance().parse(parts[2]).intValue(); } catch (ParseException e) { - Proxies.log.warning("ItemStack string (" + itemStackString + ") has improperly formatter metadata. Suitable metadata are integer values or *."); + Proxies.log.warning("ItemStack string (" + itemStackString + ") has improperly formatted metadata. Suitable metadata are integer values or *."); return null; } } diff --git a/src/main/java/forestry/core/utils/StringUtil.java b/src/main/java/forestry/core/utils/StringUtil.java index 0c6df8902..337923ce1 100755 --- a/src/main/java/forestry/core/utils/StringUtil.java +++ b/src/main/java/forestry/core/utils/StringUtil.java @@ -102,7 +102,7 @@ public class StringUtil { public static String line(int length) { StringBuilder line = new StringBuilder(); for (int i = 0; i < length; i++) { - line.append("-"); + line.append('-'); } return line.toString(); diff --git a/src/main/java/forestry/core/utils/Utils.java b/src/main/java/forestry/core/utils/Utils.java index 56176481e..f6145d565 100755 --- a/src/main/java/forestry/core/utils/Utils.java +++ b/src/main/java/forestry/core/utils/Utils.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.core.utils; -import java.util.Arrays; import java.util.Random; import net.minecraft.block.Block; @@ -25,7 +24,6 @@ import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -import net.minecraft.world.biome.BiomeGenBase; import cpw.mods.fml.common.registry.EntityRegistry; @@ -104,30 +102,6 @@ public class Utils { } - public static T[] concat(T[] first, T[] second) { - T[] result = Arrays.copyOf(first, first.length + second.length); - System.arraycopy(second, 0, result, first.length, second.length); - return result; - } - - public static int[] concat(int[] first, int[] second) { - int[] result = Arrays.copyOf(first, first.length + second.length); - System.arraycopy(second, 0, result, first.length, second.length); - return result; - } - - public static short[] concat(short[] first, short[] second) { - short[] result = Arrays.copyOf(first, first.length + second.length); - System.arraycopy(second, 0, result, first.length, second.length); - return result; - } - - public static float[] concat(float[] first, float[] second) { - float[] result = Arrays.copyOf(first, first.length + second.length); - System.arraycopy(second, 0, result, first.length, second.length); - return result; - } - public static boolean canWrench(EntityPlayer player, int x, int y, int z) { ItemStack itemstack = player.getCurrentEquippedItem(); @@ -201,10 +175,6 @@ public class Utils { } - public static BiomeGenBase getBiomeAt(World world, int x, int z) { - return world.getBiomeGenForCoordsBody(x, z); - } - private static E createEntity(World world, Class entityClass) { if (!EntityList.classToStringMapping.containsKey(entityClass)) { return null; diff --git a/src/main/java/forestry/core/vect/Vect.java b/src/main/java/forestry/core/vect/Vect.java index 878c22cb7..1c6339416 100644 --- a/src/main/java/forestry/core/vect/Vect.java +++ b/src/main/java/forestry/core/vect/Vect.java @@ -12,6 +12,8 @@ package forestry.core.vect; import java.util.Random; +import net.minecraft.entity.Entity; + import net.minecraftforge.common.util.ForgeDirection; /** @@ -42,6 +44,12 @@ public class Vect implements IVect { this.z = z; } + public Vect(Entity entity) { + this.x = (int) Math.round(entity.posX); + this.y = (int) Math.round(entity.posY); + this.z = (int) Math.round(entity.posZ); + } + public static Vect getRandomPositionInArea(Random random, IVect area) { int x = random.nextInt(area.getX()); int y = random.nextInt(area.getY()); diff --git a/src/main/java/forestry/energy/EnergyManager.java b/src/main/java/forestry/energy/EnergyManager.java index c60e5631c..b5b8468a1 100644 --- a/src/main/java/forestry/energy/EnergyManager.java +++ b/src/main/java/forestry/energy/EnergyManager.java @@ -1,18 +1,23 @@ package forestry.energy; +import java.io.IOException; + import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; import forestry.core.GameMode; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IStreamable; import forestry.core.utils.BlockUtil; import cofh.api.energy.EnergyStorage; import cofh.api.energy.IEnergyHandler; import cofh.api.energy.IEnergyReceiver; -public class EnergyManager implements IEnergyHandler { +public class EnergyManager implements IEnergyHandler, IStreamable { private enum EnergyTransferMode { EXTRACT, RECEIVE, BOTH } @@ -79,11 +84,23 @@ public class EnergyManager implements IEnergyHandler { } /* Packets */ - public int toPacketInt() { + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + int energyStored = energyStorage.getEnergyStored(); + data.writeInt(energyStored); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + int energyStored = data.readInt(); + energyStorage.setEnergyStored(energyStored); + } + + public int toGuiInt() { return energyStorage.getEnergyStored(); } - public void fromPacketInt(int packetInt) { + public void fromGuiInt(int packetInt) { energyStorage.setEnergyStored(packetInt); } diff --git a/src/main/java/forestry/energy/GuiHandlerEnergy.java b/src/main/java/forestry/energy/GuiHandlerEnergy.java index b32319167..f73ddbc6e 100755 --- a/src/main/java/forestry/energy/GuiHandlerEnergy.java +++ b/src/main/java/forestry/energy/GuiHandlerEnergy.java @@ -15,7 +15,7 @@ import net.minecraft.world.World; import forestry.core.GuiHandlerBase; import forestry.core.network.GuiId; -import forestry.core.network.PacketIds; +import forestry.core.network.PacketId; import forestry.core.network.PacketSocketUpdate; import forestry.core.proxy.Proxies; import forestry.energy.gadgets.EngineBronze; @@ -43,16 +43,16 @@ public class GuiHandlerEnergy extends GuiHandlerBase { switch (GuiId.values()[id]) { case EngineBronzeGUI: - return new GuiEngineBronze(player.inventory, (EngineBronze) getTileForestry(world, x, y, z)); + return new GuiEngineBronze(player.inventory, getTileForestry(world, x, y, z, player, EngineBronze.class)); case EngineCopperGUI: - return new GuiEngineCopper(player.inventory, (EngineCopper) getTileForestry(world, x, y, z)); + return new GuiEngineCopper(player.inventory, getTileForestry(world, x, y, z, player, EngineCopper.class)); case EngineTinGUI: - return new GuiEngineTin(player.inventory, (EngineTin) getTileForestry(world, x, y, z)); + return new GuiEngineTin(player.inventory, getTileForestry(world, x, y, z, player, EngineTin.class)); case GeneratorGUI: - return new GuiGenerator(player.inventory, (MachineGenerator) getTileForestry(world, x, y, z)); + return new GuiGenerator(player.inventory, getTileForestry(world, x, y, z, player, MachineGenerator.class)); default: return null; @@ -69,18 +69,18 @@ public class GuiHandlerEnergy extends GuiHandlerBase { switch (GuiId.values()[id]) { case EngineBronzeGUI: - return new ContainerEngineBronze(player.inventory, (EngineBronze) getTileForestry(world, x, y, z)); + return new ContainerEngineBronze(player.inventory, getTileForestry(world, x, y, z, player, EngineBronze.class)); case EngineCopperGUI: - return new ContainerEngineCopper(player.inventory, (EngineCopper) getTileForestry(world, x, y, z)); + return new ContainerEngineCopper(player.inventory, getTileForestry(world, x, y, z, player, EngineCopper.class)); case EngineTinGUI: - EngineTin tile = (EngineTin) getTileForestry(world, x, y, z); - Proxies.net.sendToPlayer(new PacketSocketUpdate(PacketIds.SOCKET_UPDATE, x, y, z, tile), player); + EngineTin tile = getTileForestry(world, x, y, z, player, EngineTin.class); + Proxies.net.sendToPlayer(new PacketSocketUpdate(PacketId.SOCKET_UPDATE, tile), player); return new ContainerEngineTin(player.inventory, tile); case GeneratorGUI: - return new ContainerGenerator(player.inventory, (MachineGenerator) getTileForestry(world, x, y, z)); + return new ContainerGenerator(player.inventory, getTileForestry(world, x, y, z, player, MachineGenerator.class)); default: return null; diff --git a/src/main/java/forestry/energy/gadgets/EngineBronze.java b/src/main/java/forestry/energy/gadgets/EngineBronze.java index 16044ce28..260316b85 100755 --- a/src/main/java/forestry/energy/gadgets/EngineBronze.java +++ b/src/main/java/forestry/energy/gadgets/EngineBronze.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.energy.gadgets; +import java.io.IOException; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.ICrafting; @@ -39,35 +41,15 @@ import forestry.core.gadgets.TileBase; import forestry.core.interfaces.ILiquidTankContainer; import forestry.core.inventory.IInventoryAdapter; import forestry.core.inventory.TileInventoryAdapter; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.GuiId; -import forestry.core.network.PacketPayload; public class EngineBronze extends Engine implements ISidedInventory, ILiquidTankContainer { /* CONSTANTS */ public static final short SLOT_CAN = 0; - /* NETWORK */ - @Override - public PacketPayload getPacketPayload() { - PacketPayload payload = super.getPacketPayload(); - - if (shutdown) { - payload.append(new int[]{1}); - } else { - payload.append(new int[]{0}); - } - - return payload; - } - - @Override - public void fromPacketPayload(PacketPayload payload) { - super.fromPacketPayload(payload); - - shutdown = payload.intPayload[3] > 0; - } - private final FilteredTank fuelTank; private final FilteredTank heatingTank; private final TankManager tankManager; @@ -156,7 +138,7 @@ public class EngineBronze extends Engine implements ISidedInventory, ILiquidTank currentOutput = determineFuelValue(FluidRegistry.getFluid(currentFluidId)); energyManager.generateEnergy(currentOutput); } else { - burnTime = totalTime = this.determineBurnTime(fuelTank.getFluid().getFluid()); + burnTime = totalTime = determineBurnTime(fuelTank.getFluid().getFluid()); currentFluidId = fuelTank.getFluid().getFluid().getID(); fuelTank.drain(Defaults.BUCKET_VOLUME, true); } @@ -228,7 +210,7 @@ public class EngineBronze extends Engine implements ISidedInventory, ILiquidTank /** * Returns the fuel value (power per cycle) an item of the passed fluid */ - private int determineFuelValue(Fluid fluid) { + private static int determineFuelValue(Fluid fluid) { if (FuelManager.bronzeEngineFuel.containsKey(fluid)) { return FuelManager.bronzeEngineFuel.get(fluid).powerPerCycle; } else { @@ -239,7 +221,7 @@ public class EngineBronze extends Engine implements ISidedInventory, ILiquidTank /** * @return Duration of burn cycle of one bucket */ - private int determineBurnTime(Fluid fluid) { + private static int determineBurnTime(Fluid fluid) { if (FuelManager.bronzeEngineFuel.containsKey(fluid)) { return FuelManager.bronzeEngineFuel.get(fluid).burnDuration; } else { @@ -299,6 +281,19 @@ public class EngineBronze extends Engine implements ISidedInventory, ILiquidTank tankManager.writeTanksToNBT(nbt); } + /* NETWORK */ + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeBoolean(shutdown); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + shutdown = data.readBoolean(); + } + /* GUI */ @Override public void getGUINetworkData(int id, int data) { @@ -315,7 +310,7 @@ public class EngineBronze extends Engine implements ISidedInventory, ILiquidTank currentOutput = data; break; case 3: - energyManager.fromPacketInt(data); + energyManager.fromGuiInt(data); break; case 4: heat = data; @@ -332,7 +327,7 @@ public class EngineBronze extends Engine implements ISidedInventory, ILiquidTank iCrafting.sendProgressBarUpdate(containerEngine, i, burnTime); iCrafting.sendProgressBarUpdate(containerEngine, i + 1, totalTime); iCrafting.sendProgressBarUpdate(containerEngine, i + 2, currentOutput); - iCrafting.sendProgressBarUpdate(containerEngine, i + 3, energyManager.toPacketInt()); + iCrafting.sendProgressBarUpdate(containerEngine, i + 3, energyManager.toGuiInt()); iCrafting.sendProgressBarUpdate(containerEngine, i + 4, heat); iCrafting.sendProgressBarUpdate(containerEngine, i + 5, currentFluidId); } diff --git a/src/main/java/forestry/energy/gadgets/EngineClockwork.java b/src/main/java/forestry/energy/gadgets/EngineClockwork.java index 626c69512..f371e6d81 100755 --- a/src/main/java/forestry/energy/gadgets/EngineClockwork.java +++ b/src/main/java/forestry/energy/gadgets/EngineClockwork.java @@ -68,7 +68,7 @@ public class EngineClockwork extends Engine { } tension = tension > ENGINE_CLOCKWORK_WIND_MAX + WIND_TENSION_BASE ? ENGINE_CLOCKWORK_WIND_MAX + WIND_TENSION_BASE : tension; delay = WIND_DELAY; - sendNetworkUpdate(); + setNeedsNetworkUpdate(); } /* LOADING & SAVING */ @@ -155,7 +155,10 @@ public class EngineClockwork extends Engine { } float fromClockwork = (tension / ENGINE_CLOCKWORK_WIND_MAX) * Defaults.ENGINE_PISTON_SPEED_MAX; - return fromClockwork >= 0.01f ? fromClockwork : 0; + + fromClockwork = Math.round(fromClockwork * 100f) / 100f; + + return fromClockwork; } @Override diff --git a/src/main/java/forestry/energy/gadgets/EngineCopper.java b/src/main/java/forestry/energy/gadgets/EngineCopper.java index 3ef734989..98fb11851 100755 --- a/src/main/java/forestry/energy/gadgets/EngineCopper.java +++ b/src/main/java/forestry/energy/gadgets/EngineCopper.java @@ -328,7 +328,7 @@ public class EngineCopper extends Engine implements ISidedInventory { currentOutput = j; break; case 3: - energyManager.fromPacketInt(j); + energyManager.fromGuiInt(j); break; case 4: heat = j; @@ -341,7 +341,7 @@ public class EngineCopper extends Engine implements ISidedInventory { iCrafting.sendProgressBarUpdate(containerEngine, 0, burnTime); iCrafting.sendProgressBarUpdate(containerEngine, 1, totalBurnTime); iCrafting.sendProgressBarUpdate(containerEngine, 2, currentOutput); - iCrafting.sendProgressBarUpdate(containerEngine, 3, energyManager.toPacketInt()); + iCrafting.sendProgressBarUpdate(containerEngine, 3, energyManager.toGuiInt()); iCrafting.sendProgressBarUpdate(containerEngine, 4, heat); } diff --git a/src/main/java/forestry/energy/gadgets/EngineTin.java b/src/main/java/forestry/energy/gadgets/EngineTin.java index f509594bb..872dc177f 100755 --- a/src/main/java/forestry/energy/gadgets/EngineTin.java +++ b/src/main/java/forestry/energy/gadgets/EngineTin.java @@ -31,7 +31,6 @@ import forestry.core.inventory.InventoryAdapter; import forestry.core.inventory.TileInventoryAdapter; import forestry.core.network.GuiId; import forestry.core.utils.DelayTimer; -import forestry.core.utils.EnumTankLevel; import forestry.plugins.PluginIC2; import ic2.api.energy.prefab.BasicSink; @@ -227,21 +226,6 @@ public class EngineTin extends Engine implements ISocketable, IInventory { return Math.min(i, (int) (ic2EnergySink.getEnergyStored() * i) / ic2EnergySink.getCapacity()); } - public static EnumTankLevel rateLevel(int scaled) { - - if (scaled < 5) { - return EnumTankLevel.EMPTY; - } else if (scaled < 30) { - return EnumTankLevel.LOW; - } else if (scaled < 60) { - return EnumTankLevel.MEDIUM; - } else if (scaled < 90) { - return EnumTankLevel.HIGH; - } else { - return EnumTankLevel.MAXIMUM; - } - } - // / SMP GUI @Override public void getGUINetworkData(int i, int j) { @@ -252,7 +236,7 @@ public class EngineTin extends Engine implements ISocketable, IInventory { currentOutput = j; break; case 1: - energyManager.fromPacketInt(j); + energyManager.fromGuiInt(j); break; case 2: heat = j; @@ -269,7 +253,7 @@ public class EngineTin extends Engine implements ISocketable, IInventory { @Override public void sendGUINetworkData(Container containerEngine, ICrafting iCrafting) { iCrafting.sendProgressBarUpdate(containerEngine, 0, currentOutput); - iCrafting.sendProgressBarUpdate(containerEngine, 1, energyManager.toPacketInt()); + iCrafting.sendProgressBarUpdate(containerEngine, 1, energyManager.toGuiInt()); iCrafting.sendProgressBarUpdate(containerEngine, 2, heat); if (ic2EnergySink != null) { iCrafting.sendProgressBarUpdate(containerEngine, 3, (short) ic2EnergySink.getEnergyStored()); diff --git a/src/main/java/forestry/energy/gui/GuiEngine.java b/src/main/java/forestry/energy/gui/GuiEngine.java index 007afe2a4..77243a01d 100755 --- a/src/main/java/forestry/energy/gui/GuiEngine.java +++ b/src/main/java/forestry/energy/gui/GuiEngine.java @@ -8,9 +8,6 @@ * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ -/** - * - */ package forestry.energy.gui; import net.minecraft.inventory.Container; @@ -26,9 +23,8 @@ public abstract class GuiEngine extends G protected class EngineLedger extends Ledger { public EngineLedger() { - super(ledgerManager); + super(ledgerManager, "power"); maxHeight = 94; - overlayColor = fontColor.get("ledger.power.background"); } @Override @@ -44,13 +40,16 @@ public abstract class GuiEngine extends G return; } - fontRendererObj.drawStringWithShadow(StringUtil.localize("gui.energy"), x + 22, y + 8, fontColor.get("ledger.power.header")); - fontRendererObj.drawStringWithShadow(StringUtil.localize("gui.currentOutput") + ":", x + 22, y + 20, fontColor.get("ledger.power.subheader")); - fontRendererObj.drawString(inventory.getCurrentOutput() + " RF/t", x + 22, y + 32, fontColor.get("ledger.power.text")); - fontRendererObj.drawStringWithShadow(StringUtil.localize("gui.stored") + ":", x + 22, y + 44, fontColor.get("ledger.power.subheader")); - fontRendererObj.drawString(inventory.getEnergyManager().getEnergyStored(inventory.getOrientation()) + " RF", x + 22, y + 56, fontColor.get("ledger.power.text")); - fontRendererObj.drawStringWithShadow(StringUtil.localize("gui.heat") + ":", x + 22, y + 68, fontColor.get("ledger.power.subheader")); - fontRendererObj.drawString((((double) inventory.getHeat() / (double) 10) + 20.0) + " C", x + 22, y + 80, fontColor.get("ledger.power.text")); + drawHeader(StringUtil.localize("gui.energy"), x + 22, y + 8); + + drawSubheader(StringUtil.localize("gui.currentOutput") + ':', x + 22, y + 20); + drawText(inventory.getCurrentOutput() + " RF/t", x + 22, y + 32); + + drawSubheader(StringUtil.localize("gui.stored") + ':', x + 22, y + 44); + drawText(inventory.getEnergyManager().getEnergyStored(inventory.getOrientation()) + " RF", x + 22, y + 56); + + drawSubheader(StringUtil.localize("gui.heat") + ':', x + 22, y + 68); + drawText((((double) inventory.getHeat() / (double) 10) + 20.0) + " C", x + 22, y + 80); } @Override diff --git a/src/main/java/forestry/energy/gui/GuiEngineTin.java b/src/main/java/forestry/energy/gui/GuiEngineTin.java index b24ddb3c6..42b5594b0 100755 --- a/src/main/java/forestry/energy/gui/GuiEngineTin.java +++ b/src/main/java/forestry/energy/gui/GuiEngineTin.java @@ -31,11 +31,26 @@ public class GuiEngineTin extends GuiEngine { EngineTin engine = inventory; int storageHeight = engine.getStorageScaled(46); int storageMaxHeight = engine.getStorageScaled(100); - EnumTankLevel rated = engine.rateLevel(storageMaxHeight); + EnumTankLevel rated = rateLevel(storageMaxHeight); drawHealthMeter(guiLeft + 74, guiTop + 25, storageHeight, rated); } + public static EnumTankLevel rateLevel(int scaled) { + + if (scaled < 5) { + return EnumTankLevel.EMPTY; + } else if (scaled < 30) { + return EnumTankLevel.LOW; + } else if (scaled < 60) { + return EnumTankLevel.MEDIUM; + } else if (scaled < 90) { + return EnumTankLevel.HIGH; + } else { + return EnumTankLevel.MAXIMUM; + } + } + private void drawHealthMeter(int x, int y, int height, EnumTankLevel rated) { int i = 176; int k = 0; diff --git a/src/main/java/forestry/factory/DummyManagers.java b/src/main/java/forestry/factory/DummyManagers.java index 68de0b912..d8cf70414 100644 --- a/src/main/java/forestry/factory/DummyManagers.java +++ b/src/main/java/forestry/factory/DummyManagers.java @@ -9,6 +9,7 @@ import net.minecraftforge.fluids.FluidStack; import forestry.api.recipes.ICarpenterManager; import forestry.api.recipes.ICentrifugeManager; +import forestry.api.recipes.ICentrifugeRecipe; import forestry.api.recipes.IFabricatorManager; import forestry.api.recipes.IFermenterManager; import forestry.api.recipes.IMoistenerManager; @@ -42,6 +43,16 @@ public class DummyManagers { public static class CentrifugeManager implements ICentrifugeManager { + @Override + public void addRecipe(ICentrifugeRecipe recipe) { + + } + + @Override + public void addRecipe(int timePerItem, ItemStack resource, Map products) { + + } + @Override public void addRecipe(int timePerItem, ItemStack resource, HashMap products) { diff --git a/src/main/java/forestry/factory/GuiHandlerFactory.java b/src/main/java/forestry/factory/GuiHandlerFactory.java index 7cec7fcd8..cc1c4e851 100755 --- a/src/main/java/forestry/factory/GuiHandlerFactory.java +++ b/src/main/java/forestry/factory/GuiHandlerFactory.java @@ -58,34 +58,34 @@ public class GuiHandlerFactory extends GuiHandlerBase { switch (GuiId.values()[id]) { case BottlerGUI: - return new GuiBottler(player.inventory, (MachineBottler) getTileForestry(world, x, y, z)); + return new GuiBottler(player.inventory, getTileForestry(world, x, y, z, player, MachineBottler.class)); case CarpenterGUI: - return new GuiCarpenter(player.inventory, (MachineCarpenter) getTileForestry(world, x, y, z)); + return new GuiCarpenter(player.inventory, getTileForestry(world, x, y, z, player, MachineCarpenter.class)); case CentrifugeGUI: - return new GuiCentrifuge(player.inventory, (MachineCentrifuge) getTileForestry(world, x, y, z)); + return new GuiCentrifuge(player.inventory, getTileForestry(world, x, y, z, player, MachineCentrifuge.class)); case FabricatorGUI: - return new GuiFabricator(player.inventory, (MachineFabricator) getTileForestry(world, x, y, z)); + return new GuiFabricator(player.inventory, getTileForestry(world, x, y, z, player, MachineFabricator.class)); case FermenterGUI: - return new GuiFermenter(player.inventory, (MachineFermenter) getTileForestry(world, x, y, z)); + return new GuiFermenter(player.inventory, getTileForestry(world, x, y, z, player, MachineFermenter.class)); case MoistenerGUI: - return new GuiMoistener(player.inventory, (MachineMoistener) getTileForestry(world, x, y, z)); + return new GuiMoistener(player.inventory, getTileForestry(world, x, y, z, player, MachineMoistener.class)); case RaintankGUI: - return new GuiRaintank(player.inventory, (MachineRaintank) getTileForestry(world, x, y, z)); + return new GuiRaintank(player.inventory, getTileForestry(world, x, y, z, player, MachineRaintank.class)); case SqueezerGUI: - return new GuiSqueezer(player.inventory, (MachineSqueezer) getTileForestry(world, x, y, z)); + return new GuiSqueezer(player.inventory, getTileForestry(world, x, y, z, player, MachineSqueezer.class)); case StillGUI: - return new GuiStill(player.inventory, (MachineStill) getTileForestry(world, x, y, z)); + return new GuiStill(player.inventory, getTileForestry(world, x, y, z, player, MachineStill.class)); case WorktableGUI: - return new GuiWorktable(player, (TileWorktable) getTileForestry(world, x, y, z)); + return new GuiWorktable(player, getTileForestry(world, x, y, z, player, TileWorktable.class)); default: return null; @@ -103,34 +103,34 @@ public class GuiHandlerFactory extends GuiHandlerBase { switch (GuiId.values()[id]) { case BottlerGUI: - return new ContainerBottler(player.inventory, (MachineBottler) getTileForestry(world, x, y, z)); + return new ContainerBottler(player.inventory, getTileForestry(world, x, y, z, player, MachineBottler.class)); case CarpenterGUI: - return new ContainerCarpenter(player.inventory, (MachineCarpenter) getTileForestry(world, x, y, z)); + return new ContainerCarpenter(player.inventory, getTileForestry(world, x, y, z, player, MachineCarpenter.class)); case CentrifugeGUI: - return new ContainerCentrifuge(player.inventory, (MachineCentrifuge) getTileForestry(world, x, y, z)); + return new ContainerCentrifuge(player.inventory, getTileForestry(world, x, y, z, player, MachineCentrifuge.class)); case FabricatorGUI: - return new ContainerFabricator(player.inventory, (MachineFabricator) getTileForestry(world, x, y, z)); + return new ContainerFabricator(player.inventory, getTileForestry(world, x, y, z, player, MachineFabricator.class)); case FermenterGUI: - return new ContainerFermenter(player.inventory, (MachineFermenter) getTileForestry(world, x, y, z)); + return new ContainerFermenter(player.inventory, getTileForestry(world, x, y, z, player, MachineFermenter.class)); case MoistenerGUI: - return new ContainerMoistener(player.inventory, (MachineMoistener) getTileForestry(world, x, y, z)); + return new ContainerMoistener(player.inventory, getTileForestry(world, x, y, z, player, MachineMoistener.class)); case RaintankGUI: - return new ContainerRaintank(player.inventory, (MachineRaintank) getTileForestry(world, x, y, z)); + return new ContainerRaintank(player.inventory, getTileForestry(world, x, y, z, player, MachineRaintank.class)); case SqueezerGUI: - return new ContainerSqueezer(player.inventory, (MachineSqueezer) getTileForestry(world, x, y, z)); + return new ContainerSqueezer(player.inventory, getTileForestry(world, x, y, z, player, MachineSqueezer.class)); case StillGUI: - return new ContainerStill(player.inventory, (MachineStill) getTileForestry(world, x, y, z)); + return new ContainerStill(player.inventory, getTileForestry(world, x, y, z, player, MachineStill.class)); case WorktableGUI: - return new ContainerWorktable(player, (TileWorktable) getTileForestry(world, x, y, z)); + return new ContainerWorktable(player, getTileForestry(world, x, y, z, player, TileWorktable.class)); default: return null; diff --git a/src/main/java/forestry/factory/gadgets/MachineCarpenter.java b/src/main/java/forestry/factory/gadgets/MachineCarpenter.java index c45ce470d..47db1bcaa 100644 --- a/src/main/java/forestry/factory/gadgets/MachineCarpenter.java +++ b/src/main/java/forestry/factory/gadgets/MachineCarpenter.java @@ -23,7 +23,7 @@ import net.minecraft.inventory.Container; import net.minecraft.inventory.ICrafting; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; -import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.inventory.InventoryCraftResult; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.nbt.NBTTagCompound; @@ -47,10 +47,10 @@ import forestry.core.fluids.TankManager; import forestry.core.fluids.tanks.FilteredTank; import forestry.core.gadgets.TileBase; import forestry.core.gadgets.TilePowered; +import forestry.core.interfaces.IItemStackDisplay; import forestry.core.interfaces.ILiquidTankContainer; import forestry.core.inventory.IInventoryAdapter; import forestry.core.inventory.InvTools; -import forestry.core.inventory.InventoryAdapter; import forestry.core.inventory.TileInventoryAdapter; import forestry.core.network.GuiId; import forestry.core.proxy.Proxies; @@ -59,9 +59,8 @@ import forestry.core.utils.GuiUtil; import forestry.core.utils.ShapedRecipeCustom; import forestry.core.utils.StackUtils; import forestry.core.utils.Utils; -import forestry.factory.gui.ContainerCarpenter; -public class MachineCarpenter extends TilePowered implements ISidedInventory, ILiquidTankContainer { +public class MachineCarpenter extends TilePowered implements ISidedInventory, ILiquidTankContainer, IItemStackDisplay { /* CONSTANTS */ public final static int SLOT_CRAFTING_1 = 0; @@ -73,6 +72,397 @@ public class MachineCarpenter extends TilePowered implements ISidedInventory, IL public final static short SLOT_INVENTORY_1 = 12; public final static short SLOT_INVENTORY_COUNT = 18; + /* MEMBER */ + public final FilteredTank resourceTank; + private final TankManager tankManager; + private final TileInventoryAdapter craftingInventory; + private final InventoryCraftResult craftPreviewInventory; + + @Nullable + public MachineCarpenter.Recipe currentRecipe; + public MachineCarpenter.Recipe lastRecipe; + private int packageTime; + private int totalTime; + private ItemStack pendingProduct; + + public ItemStack getBoxStack() { + return getInternalInventory().getStackInSlot(SLOT_BOX); + } + + public MachineCarpenter() { + super(1100, 50, 4000); + setHints(Config.hints.get("carpenter")); + resourceTank = new FilteredTank(Defaults.PROCESSOR_TANK_CAPACITY, RecipeManager.recipeFluids); + + craftingInventory = new TileInventoryAdapter(this, 10, "CraftItems"); + craftPreviewInventory = new InventoryCraftResult(); + setInternalInventory(new CarpenterInventoryAdapter(this)); + + InvTools.configureSided(getInternalInventory(), Defaults.FACINGS, SLOT_BOX, 20); + + tankManager = new TankManager(resourceTank); + } + + @Override + public void openGui(EntityPlayer player, TileBase tile) { + player.openGui(ForestryAPI.instance, GuiId.CarpenterGUI.ordinal(), player.worldObj, xCoord, yCoord, zCoord); + } + + /* LOADING & SAVING */ + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + + nbttagcompound.setInteger("PackageTime", packageTime); + nbttagcompound.setInteger("PackageTotalTime", totalTime); + + tankManager.writeTanksToNBT(nbttagcompound); + + craftingInventory.writeToNBT(nbttagcompound); + + // Write pending product + if (pendingProduct != null) { + NBTTagCompound nbttagcompoundP = new NBTTagCompound(); + pendingProduct.writeToNBT(nbttagcompoundP); + nbttagcompound.setTag("PendingProduct", nbttagcompoundP); + } + } + + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); + + packageTime = nbttagcompound.getInteger("PackageTime"); + totalTime = nbttagcompound.getInteger("PackageTotalTime"); + + tankManager.readTanksFromNBT(nbttagcompound); + + craftingInventory.readFromNBT(nbttagcompound); + + // Load pending product + if (nbttagcompound.hasKey("PendingProduct")) { + NBTTagCompound nbttagcompoundP = nbttagcompound.getCompoundTag("PendingProduct"); + pendingProduct = ItemStack.loadItemStackFromNBT(nbttagcompoundP); + } + + // Reset recipe according to contents + setCurrentRecipe(RecipeManager.findMatchingRecipe(resourceTank.getFluid(), getBoxStack(), craftingInventory, worldObj)); + } + + public void resetRecipe() { + if (worldObj.isRemote) { + return; + } + setCurrentRecipe(RecipeManager.findMatchingRecipe(resourceTank.getFluid(), getBoxStack(), craftingInventory, getWorldObj())); + } + + private void setCurrentRecipe(@Nullable MachineCarpenter.Recipe currentRecipe) { + this.currentRecipe = currentRecipe; + + final ItemStack craftingResult; + + if (currentRecipe != null) { + lastRecipe = currentRecipe; + craftingResult = currentRecipe.getCraftingResult(); + } else { + craftingResult = null; + } + + craftPreviewInventory.setInventorySlotContents(0, craftingResult); + } + + @Override + public void updateServerSide() { + super.updateServerSide(); + + if (!updateOnInterval(20)) { + return; + } + IInventoryAdapter accessibleInventory = getInternalInventory(); + // Check if we have suitable items waiting in the item slot + if (accessibleInventory.getStackInSlot(SLOT_CAN_INPUT) != null) { + FluidHelper.drainContainers(tankManager, accessibleInventory, SLOT_CAN_INPUT); + } + + if (!updateOnInterval(40)) { + return; + } + + if (currentRecipe == null) { + Recipe recipe = MachineCarpenter.RecipeManager.findMatchingRecipe(resourceTank.getFluid(), getBoxStack(), craftingInventory, worldObj); + if (recipe != null) { + setCurrentRecipe(recipe); + } + } + + setErrorCondition(currentRecipe == null, EnumErrorCode.NORECIPE); + setErrorCondition(!validateResources(), EnumErrorCode.NORESOURCE); + } + + @Override + public boolean workCycle() { + + if (packageTime > 0) { + packageTime--; + + // Check whether we have become invalid and need to abort production + if (currentRecipe == null || !validateResources()) { + packageTime = totalTime = 0; + return false; + } + + if (packageTime <= 0) { + + pendingProduct = currentRecipe.getCraftingResult(); + totalTime = 0; + + // Remove resources + if (!removeResources(currentRecipe)) { + return false; + } + + // Update product display + resetRecipe(); + + return tryAddPending(); + } + return true; + } else if (pendingProduct != null) { + return tryAddPending(); + } else if (currentRecipe != null) { + + if (!validateResources()) { + return false; + } + + // Enough items available, start the process + packageTime = totalTime = currentRecipe.packagingTime; + + // Update product display + resetRecipe(); + + return true; + } else { + + return false; + } + } + + private boolean validateResources() { + if (currentRecipe == null) { + return true; + } + // Check whether liquid is needed and if there is enough available + if (currentRecipe.liquid != null) { + if (resourceTank.getFluidAmount() < currentRecipe.liquid.amount) { + return false; + } + } + + IInventoryAdapter accessibleInventory = getInternalInventory(); + // Check whether boxes are available + if (currentRecipe.box != null) { + if (accessibleInventory.getStackInSlot(SLOT_BOX) == null) { + return false; + } + } + + // Need at least one matched set + ItemStack[] set = InvTools.getStacks(craftingInventory, SLOT_CRAFTING_1, SLOT_CRAFTING_COUNT); + ItemStack[] stock = InvTools.getStacks(accessibleInventory, SLOT_INVENTORY_1, SLOT_INVENTORY_COUNT); + + return StackUtils.containsSets(set, stock, true, false) > 0; + } + + private boolean removeResources(Recipe recipe) { + + // Remove resources + 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) { + ItemStack removed = getInternalInventory().decrStackSize(SLOT_BOX, 1); + if (removed == null || removed.stackSize == 0) { + return false; + } + } + return removeSets(1, InvTools.getStacks(craftingInventory, SLOT_CRAFTING_1, SLOT_CRAFTING_COUNT)); + } + + private boolean removeSets(int count, ItemStack[] set) { + EntityPlayer player = Proxies.common.getPlayer(worldObj, getOwner()); + return InvTools.removeSets(getInternalInventory(), count, set, SLOT_INVENTORY_1, SLOT_INVENTORY_COUNT, player, true, true, true); + } + + private boolean tryAddPending() { + if (pendingProduct == null) { + return false; + } + + boolean added = InvTools.tryAddStack(this, pendingProduct, SLOT_PRODUCT, SLOT_PRODUCT_COUNT, true); + + if (added) { + pendingProduct = null; + } + + setErrorCondition(!added, EnumErrorCode.NOSPACE); + return added; + } + + /* STATE INFORMATION */ + @Override + public boolean isWorking() { + return packageTime > 0 || pendingProduct != null || currentRecipe != null && validateResources(); + } + + @Override + public boolean hasWork() { + if (currentRecipe == null) { + return false; + } + + IInventoryAdapter accessibleInventory = getInternalInventory(); + // Stop working if the output slot cannot take more + if (accessibleInventory.getStackInSlot(SLOT_PRODUCT) != null + && accessibleInventory.getStackInSlot(SLOT_PRODUCT).getMaxStackSize() - accessibleInventory.getStackInSlot(SLOT_PRODUCT).stackSize < currentRecipe + .getCraftingResult().stackSize) { + return false; + } + + return validateResources(); + } + + public int getCraftingProgressScaled(int i) { + if (totalTime == 0) { + return 0; + } + + return ((totalTime - packageTime) * i) / totalTime; + } + + public int getResourceScaled(int i) { + return (resourceTank.getFluidAmount() * i) / Defaults.PROCESSOR_TANK_CAPACITY; + } + + @Override + public EnumTankLevel getPrimaryLevel() { + return Utils.rateTankLevel(getResourceScaled(100)); + } + + /* SMP GUI */ + @Override + public void getGUINetworkData(int i, int j) { + i -= tankManager.maxMessageId() + 1; + switch (i) { + case 0: + packageTime = j; + break; + case 1: + totalTime = j; + break; + } + } + + @Override + public void sendGUINetworkData(Container container, ICrafting iCrafting) { + int i = tankManager.maxMessageId() + 1; + iCrafting.sendProgressBarUpdate(container, i, packageTime); + iCrafting.sendProgressBarUpdate(container, i + 1, totalTime); + } + + /** + * @return Inaccessible crafting inventory for the craft grid. + */ + public IInventory getCraftingInventory() { + return craftingInventory; + } + + public IInventory getCraftPreviewInventory() { + return craftPreviewInventory; + } + + @Override + public void handleItemStackForDisplay(ItemStack itemStack) { + craftPreviewInventory.setInventorySlotContents(0, itemStack); + } + + // IFLUIDCONTAINER IMPLEMENTATION + @Override + public int fill(ForgeDirection direction, FluidStack resource, boolean doFill) { + return tankManager.fill(direction, resource, doFill); + } + + @Override + public TankManager getTankManager() { + return tankManager; + } + + @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); + } + + private static class CarpenterInventoryAdapter extends TileInventoryAdapter { + public CarpenterInventoryAdapter(MachineCarpenter carpenter) { + super(carpenter, 30, "Items"); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + if (slotIndex == SLOT_CAN_INPUT) { + Fluid fluid = FluidHelper.getFluidInContainer(itemStack); + return tile.tankManager.accepts(fluid); + } else if (slotIndex == SLOT_BOX) { + return RecipeManager.isBox(itemStack); + } else if (canSlotAccept(SLOT_CAN_INPUT, itemStack) || canSlotAccept(SLOT_BOX, itemStack)) { + return false; + } + + return GuiUtil.isIndexInRange(slotIndex, SLOT_INVENTORY_1, SLOT_INVENTORY_COUNT); + } + + @Override + public boolean isItemValidForSlot(int slotIndex, ItemStack itemStack) { + if (GuiUtil.isIndexInRange(slotIndex, SLOT_INVENTORY_1, SLOT_INVENTORY_COUNT)) { + if (tile.lastRecipe != null) { + return tile.lastRecipe.isIngredient(itemStack); + } + } + return true; + } + + @Override + public boolean canExtractItem(int slotIndex, ItemStack itemstack, int side) { + return slotIndex == SLOT_PRODUCT; + } + } + /* RECIPE MANAGMENT */ public static class Recipe { @@ -210,391 +600,4 @@ public class MachineCarpenter extends TilePowered implements ISidedInventory, IL } } - /* MEMBER */ - public final FilteredTank resourceTank; - private final TankManager tankManager; - private final TileInventoryAdapter craftingInventory; - - @Nullable - public MachineCarpenter.Recipe currentRecipe; - public MachineCarpenter.Recipe lastRecipe; - public ContainerCarpenter activeContainer; - private int packageTime; - private int totalTime; - private ItemStack currentProduct; - private ItemStack pendingProduct; - - public ItemStack getBoxStack() { - return getInternalInventory().getStackInSlot(SLOT_BOX); - } - - public MachineCarpenter() { - super(1100, 50, 4000); - setHints(Config.hints.get("carpenter")); - resourceTank = new FilteredTank(Defaults.PROCESSOR_TANK_CAPACITY, RecipeManager.recipeFluids); - craftingInventory = new TileInventoryAdapter(this, 10, "CraftItems"); - setInternalInventory(new CarpenterInventoryAdapter(this)); - InvTools.configureSided(getInternalInventory(), Defaults.FACINGS, SLOT_BOX, 20); - - tankManager = new TankManager(resourceTank); - } - - @Override - public void openGui(EntityPlayer player, TileBase tile) { - player.openGui(ForestryAPI.instance, GuiId.CarpenterGUI.ordinal(), player.worldObj, xCoord, yCoord, zCoord); - } - - /* LOADING & SAVING */ - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - - nbttagcompound.setInteger("PackageTime", packageTime); - nbttagcompound.setInteger("PackageTotalTime", totalTime); - - tankManager.writeTanksToNBT(nbttagcompound); - - craftingInventory.writeToNBT(nbttagcompound); - - // Write pending product - if (pendingProduct != null) { - NBTTagCompound nbttagcompoundP = new NBTTagCompound(); - pendingProduct.writeToNBT(nbttagcompoundP); - nbttagcompound.setTag("PendingProduct", nbttagcompoundP); - } - // Write current product - if (currentProduct != null) { - NBTTagCompound nbttagcompoundC = new NBTTagCompound(); - currentProduct.writeToNBT(nbttagcompoundC); - nbttagcompound.setTag("CurrentProduct", nbttagcompoundC); - } - } - - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); - - packageTime = nbttagcompound.getInteger("PackageTime"); - totalTime = nbttagcompound.getInteger("PackageTotalTime"); - - tankManager.readTanksFromNBT(nbttagcompound); - - craftingInventory.readFromNBT(nbttagcompound); - - // Load pending product - if (nbttagcompound.hasKey("PendingProduct")) { - NBTTagCompound nbttagcompoundP = nbttagcompound.getCompoundTag("PendingProduct"); - pendingProduct = ItemStack.loadItemStackFromNBT(nbttagcompoundP); - } - // Load current product - if (nbttagcompound.hasKey("CurrentProduct")) { - NBTTagCompound nbttagcompoundP = nbttagcompound.getCompoundTag("CurrentProduct"); - currentProduct = ItemStack.loadItemStackFromNBT(nbttagcompoundP); - } - - // Reset recipe according to contents - setCurrentRecipe(RecipeManager.findMatchingRecipe(resourceTank.getFluid(), getBoxStack(), craftingInventory, worldObj)); - } - - public void setCurrentRecipe(@Nullable MachineCarpenter.Recipe currentRecipe) { - this.currentRecipe = currentRecipe; - if (currentRecipe != null) { - lastRecipe = currentRecipe; - } - } - - @Override - public void updateServerSide() { - super.updateServerSide(); - - if (!updateOnInterval(20)) { - return; - } - IInventoryAdapter accessibleInventory = getInternalInventory(); - // Check if we have suitable items waiting in the item slot - if (accessibleInventory.getStackInSlot(SLOT_CAN_INPUT) != null) { - FluidHelper.drainContainers(tankManager, accessibleInventory, SLOT_CAN_INPUT); - } - - if (!updateOnInterval(40)) { - return; - } - - if (currentRecipe == null) { - Recipe recipe = MachineCarpenter.RecipeManager.findMatchingRecipe(resourceTank.getFluid(), getBoxStack(), craftingInventory, worldObj); - setCurrentRecipe(recipe); - } - - setErrorCondition(currentRecipe == null, EnumErrorCode.NORECIPE); - setErrorCondition(!validateResources(), EnumErrorCode.NORESOURCE); - } - - @Override - public boolean workCycle() { - - if (packageTime > 0) { - packageTime--; - - // Check whether we have become invalid and need to abort production - if (currentRecipe == null || currentProduct == null || !currentProduct.isItemEqual(currentRecipe.getCraftingResult()) || !validateResources()) { - currentProduct = null; - packageTime = totalTime = 0; - return false; - } - - if (packageTime <= 0) { - - pendingProduct = currentProduct; - currentProduct = null; - totalTime = 0; - - // Remove resources - if (!removeResources(currentRecipe)) { - return false; - } - - // Update product display - if (activeContainer != null) { - activeContainer.updateProductDisplay(); - } - - return tryAddPending(); - } - return true; - } else if (pendingProduct != null) { - return tryAddPending(); - } else { - - if (currentRecipe != null) { - - if (!validateResources()) { - return false; - } - - // Enough items available, start the process - packageTime = totalTime = currentRecipe.packagingTime; - currentProduct = currentRecipe.getCraftingResult(); - - // Update product display - if (activeContainer != null) { - activeContainer.updateProductDisplay(); - } - - return true; - } - - return false; - } - } - - private boolean validateResources() { - if (currentRecipe == null) { - return true; - } - // Check whether liquid is needed and if there is enough available - if (currentRecipe.liquid != null) { - if (resourceTank.getFluidAmount() < currentRecipe.liquid.amount) { - return false; - } - } - - IInventoryAdapter accessibleInventory = getInternalInventory(); - // Check whether boxes are available - if (currentRecipe.box != null) { - if (accessibleInventory.getStackInSlot(SLOT_BOX) == null) { - return false; - } - } - - // Need at least one matched set - ItemStack[] set = InvTools.getStacks(craftingInventory, SLOT_CRAFTING_1, SLOT_CRAFTING_COUNT); - ItemStack[] stock = InvTools.getStacks(accessibleInventory, SLOT_INVENTORY_1, SLOT_INVENTORY_COUNT); - - return StackUtils.containsSets(set, stock, true, false) > 0; - } - - private boolean removeResources(Recipe recipe) { - - // Remove resources - 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) { - ItemStack removed = getInternalInventory().decrStackSize(SLOT_BOX, 1); - if (removed == null || removed.stackSize == 0) { - return false; - } - } - return removeSets(1, InvTools.getStacks(craftingInventory, SLOT_CRAFTING_1, SLOT_CRAFTING_COUNT)); - } - - private boolean removeSets(int count, ItemStack[] set) { - EntityPlayer player = Proxies.common.getPlayer(worldObj, getOwnerProfile()); - return InvTools.removeSets(getInternalInventory(), count, set, SLOT_INVENTORY_1, SLOT_INVENTORY_COUNT, player, true, true, true); - } - - private boolean tryAddPending() { - if (pendingProduct == null) { - return false; - } - - boolean added = InvTools.tryAddStack(this, pendingProduct, SLOT_PRODUCT, SLOT_PRODUCT_COUNT, true); - - if (added) { - pendingProduct = null; - } - - setErrorCondition(!added, EnumErrorCode.NOSPACE); - return added; - } - - /* STATE INFORMATION */ - @Override - public boolean isWorking() { - return packageTime > 0 || pendingProduct != null || currentRecipe != null && validateResources(); - } - - @Override - public boolean hasWork() { - if (currentRecipe == null) { - return false; - } - - IInventoryAdapter accessibleInventory = getInternalInventory(); - // Stop working if the output slot cannot take more - if (accessibleInventory.getStackInSlot(SLOT_PRODUCT) != null - && accessibleInventory.getStackInSlot(SLOT_PRODUCT).getMaxStackSize() - accessibleInventory.getStackInSlot(SLOT_PRODUCT).stackSize < currentRecipe - .getCraftingResult().stackSize) { - return false; - } - - return validateResources(); - } - - public int getCraftingProgressScaled(int i) { - if (totalTime == 0) { - return 0; - } - - return (packageTime * i) / totalTime; - - } - - public int getResourceScaled(int i) { - return (resourceTank.getFluidAmount() * i) / Defaults.PROCESSOR_TANK_CAPACITY; - } - - @Override - public EnumTankLevel getPrimaryLevel() { - return Utils.rateTankLevel(getResourceScaled(100)); - } - - /* SMP GUI */ - @Override - public void getGUINetworkData(int i, int j) { - i -= tankManager.maxMessageId() + 1; - switch (i) { - case 0: - packageTime = j; - break; - case 1: - totalTime = j; - break; - } - } - - @Override - public void sendGUINetworkData(Container container, ICrafting iCrafting) { - int i = tankManager.maxMessageId() + 1; - iCrafting.sendProgressBarUpdate(container, i, packageTime); - iCrafting.sendProgressBarUpdate(container, i + 1, totalTime); - } - - /** - * @return Inaccessible crafting inventory for the craft grid. - */ - public InventoryAdapter getCraftingInventory() { - return craftingInventory; - } - - // IFLUIDCONTAINER IMPLEMENTATION - @Override - public int fill(ForgeDirection direction, FluidStack resource, boolean doFill) { - return tankManager.fill(direction, resource, doFill); - } - - @Override - public TankManager getTankManager() { - return tankManager; - } - - @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); - } - - public void resetProductDisplay(InventoryCrafting craftMatrix) { - setCurrentRecipe(RecipeManager.findMatchingRecipe(resourceTank.getFluid(), getBoxStack(), craftMatrix, getWorldObj())); - } - - private static class CarpenterInventoryAdapter extends TileInventoryAdapter { - public CarpenterInventoryAdapter(MachineCarpenter carpenter) { - super(carpenter, 30, "Items"); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (slotIndex == SLOT_CAN_INPUT) { - Fluid fluid = FluidHelper.getFluidInContainer(itemStack); - return tile.tankManager.accepts(fluid); - } else if (slotIndex == SLOT_BOX) { - return RecipeManager.isBox(itemStack); - } else if (canSlotAccept(SLOT_CAN_INPUT, itemStack) || canSlotAccept(SLOT_BOX, itemStack)) { - return false; - } - - return GuiUtil.isIndexInRange(slotIndex, SLOT_INVENTORY_1, SLOT_INVENTORY_COUNT); - } - - @Override - public boolean isItemValidForSlot(int slotIndex, ItemStack itemStack) { - if (GuiUtil.isIndexInRange(slotIndex, SLOT_INVENTORY_1, SLOT_INVENTORY_COUNT)) { - if (tile.lastRecipe != null) { - return tile.lastRecipe.isIngredient(itemStack); - } - } - return true; - } - - @Override - public boolean canExtractItem(int slotIndex, ItemStack itemstack, int side) { - return slotIndex == SLOT_PRODUCT; - } - } } diff --git a/src/main/java/forestry/factory/gadgets/MachineCentrifuge.java b/src/main/java/forestry/factory/gadgets/MachineCentrifuge.java index fabb8bcc4..83bc4752b 100755 --- a/src/main/java/forestry/factory/gadgets/MachineCentrifuge.java +++ b/src/main/java/forestry/factory/gadgets/MachineCentrifuge.java @@ -10,11 +10,15 @@ ******************************************************************************/ package forestry.factory.gadgets; +import com.google.common.collect.ImmutableMap; + import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; +import java.util.List; import java.util.Map; +import java.util.Random; import java.util.Set; import java.util.Stack; @@ -33,6 +37,7 @@ import cpw.mods.fml.common.Optional; import forestry.api.core.ForestryAPI; import forestry.api.recipes.ICentrifugeManager; +import forestry.api.recipes.ICentrifugeRecipe; import forestry.core.EnumErrorCode; import forestry.core.config.Config; import forestry.core.config.Defaults; @@ -55,93 +60,8 @@ public class MachineCentrifuge extends TilePowered implements ISidedInventory { public static final int SLOT_PRODUCT_1 = 1; public static final int SLOT_PRODUCT_COUNT = 9; - /* RECIPE MANAGMENT */ - public static class Recipe { - - public final int timePerItem; - public final ItemStack resource; - public final HashMap products; - - public Recipe(int timePerItem, ItemStack resource, HashMap products) { - this.timePerItem = timePerItem; - this.resource = resource; - this.products = products; - - for (ItemStack item : products.keySet()) { - if (item == null) { - throw new IllegalArgumentException("Tried to register a null product of " + resource); - } - } - } - - public boolean matches(ItemStack res) { - return StackUtils.isCraftingEquivalent(resource, res); - } - } - - public static class RecipeManager implements ICentrifugeManager { - - public static final ArrayList recipes = new ArrayList(); - - @Override - public void addRecipe(int timePerItem, ItemStack resource, HashMap products) { - recipes.add(new Recipe(timePerItem, resource, products)); - } - - @Override - public void addRecipe(int timePerItem, ItemStack resource, ItemStack[] produce, int[] chances) { - HashMap products = new HashMap(); - - int i = 0; - for (ItemStack prod : produce) { - products.put(prod, chances[i]); - i++; - } - - addRecipe(timePerItem, resource, products); - } - - @Override - public void addRecipe(int timePerItem, ItemStack resource, ItemStack primary, ItemStack secondary, int chance) { - HashMap products = new HashMap(); - products.put(primary, 100); - if (secondary != null) { - products.put(secondary, chance); - } - addRecipe(timePerItem, resource, products); - } - - @Override - public void addRecipe(int timePerItem, ItemStack resource, ItemStack primary) { - HashMap products = new HashMap(); - products.put(primary, 100); - addRecipe(timePerItem, resource, products); - } - - public static Recipe findMatchingRecipe(ItemStack item) { - for (Recipe recipe : recipes) { - if (recipe.matches(item)) { - return recipe; - } - } - return null; - } - - @Override - public Map getRecipes() { - HashMap recipeList = new HashMap(); - - for (Recipe recipe : recipes) { - Set productsKeys = recipe.products.keySet(); - recipeList.put(new Object[]{recipe.resource}, productsKeys.toArray(new ItemStack[productsKeys.size()])); - } - - return recipeList; - } - } - /* MEMBER */ - public MachineCentrifuge.Recipe currentRecipe; + public ICentrifugeRecipe currentRecipe; private final Stack pendingProducts = new Stack(); private int productionTime; @@ -237,13 +157,8 @@ public class MachineCentrifuge extends TilePowered implements ISidedInventory { } // We are done, add products to queue - for (Map.Entry entry : currentRecipe.products.entrySet()) { - if (entry.getValue() >= 100) { - pendingProducts.push(entry.getKey().copy()); - } else if (worldObj.rand.nextInt(100) < entry.getValue()) { - pendingProducts.push(entry.getKey().copy()); - } - } + Collection products = currentRecipe.getProducts(worldObj.rand); + pendingProducts.addAll(products); getInternalInventory().decrStackSize(SLOT_RESOURCE, 1); checkRecipe(); @@ -254,7 +169,7 @@ public class MachineCentrifuge extends TilePowered implements ISidedInventory { } public void checkRecipe() { - Recipe machingRecipe = RecipeManager.findMatchingRecipe(getInternalInventory().getStackInSlot(SLOT_RESOURCE)); + ICentrifugeRecipe machingRecipe = RecipeManager.findMatchingRecipe(getInternalInventory().getStackInSlot(SLOT_RESOURCE)); if (currentRecipe != machingRecipe) { currentRecipe = machingRecipe; @@ -271,8 +186,8 @@ public class MachineCentrifuge extends TilePowered implements ISidedInventory { return; } - productionTime = currentRecipe.timePerItem; - timePerItem = currentRecipe.timePerItem; + productionTime = currentRecipe.getProcessingTime(); + timePerItem = currentRecipe.getProcessingTime(); } private boolean tryAddPending() { @@ -317,7 +232,7 @@ public class MachineCentrifuge extends TilePowered implements ISidedInventory { return i; } - return (productionTime * i) / timePerItem; + return ((timePerItem - productionTime) * i) / timePerItem; } /* GUI */ @@ -362,4 +277,135 @@ public class MachineCentrifuge extends TilePowered implements ISidedInventory { return GuiUtil.isIndexInRange(slotIndex, SLOT_PRODUCT_1, SLOT_PRODUCT_COUNT); } } + + /* RECIPE MANAGEMENT */ + public static class CentrifugeRecipe implements ICentrifugeRecipe { + + private final int processingTime; + private final ItemStack input; + private final Map outputs; + + public CentrifugeRecipe(int processingTime, ItemStack input, Map outputs) { + this.processingTime = processingTime; + this.input = input; + this.outputs = outputs; + + for (ItemStack item : outputs.keySet()) { + if (item == null) { + throw new IllegalArgumentException("Tried to register a null product of " + input); + } + } + } + + @Override + public ItemStack getInput() { + return input; + } + + @Override + public int getProcessingTime() { + return processingTime; + } + + @Override + public Collection getProducts(Random random) { + List products = new ArrayList(); + + for (Map.Entry entry : this.outputs.entrySet()) { + float probability = entry.getValue(); + + if (probability >= 1.0) { + products.add(entry.getKey().copy()); + } else if (random.nextFloat() < probability) { + products.add(entry.getKey().copy()); + } + } + + return products; + } + + @Override + public Map getAllProducts() { + return ImmutableMap.copyOf(outputs); + } + } + + public static class RecipeManager implements ICentrifugeManager { + + public static final List recipes = new ArrayList(); + + @Override + public void addRecipe(ICentrifugeRecipe recipe) { + recipes.add(recipe); + } + + @Override + public void addRecipe(int timePerItem, ItemStack resource, Map products) { + ICentrifugeRecipe recipe = new CentrifugeRecipe(timePerItem, resource, products); + addRecipe(recipe); + } + + @Override + public void addRecipe(int timePerItem, ItemStack resource, HashMap products) { + Map floatProducts = new HashMap(); + for (Map.Entry entry : products.entrySet()) { + floatProducts.put(entry.getKey(), entry.getValue() / 100.0f); + } + + addRecipe(timePerItem, resource, floatProducts); + } + + @Override + public void addRecipe(int timePerItem, ItemStack resource, ItemStack[] produce, int[] chances) { + Map products = new HashMap(); + + int i = 0; + for (ItemStack prod : produce) { + products.put(prod, chances[i] / 100f); + i++; + } + + addRecipe(timePerItem, resource, products); + } + + @Override + public void addRecipe(int timePerItem, ItemStack resource, ItemStack primary, ItemStack secondary, int chance) { + Map products = new HashMap(); + products.put(primary, 1.0f); + if (secondary != null) { + products.put(secondary, chance / 100f); + } + addRecipe(timePerItem, resource, products); + } + + @Override + public void addRecipe(int timePerItem, ItemStack resource, ItemStack primary) { + Map products = new HashMap(); + products.put(primary, 1.0f); + addRecipe(timePerItem, resource, products); + } + + public static ICentrifugeRecipe findMatchingRecipe(ItemStack item) { + for (ICentrifugeRecipe recipe : recipes) { + ItemStack recipeInput = recipe.getInput(); + if (StackUtils.isCraftingEquivalent(recipeInput, item)) { + return recipe; + } + } + return null; + } + + @Override + public Map getRecipes() { + HashMap recipeList = new HashMap(); + + for (ICentrifugeRecipe recipe : recipes) { + Set productsKeys = recipe.getAllProducts().keySet(); + recipeList.put(new Object[]{recipe.getInput()}, productsKeys.toArray(new ItemStack[productsKeys.size()])); + } + + return recipeList; + } + } + } diff --git a/src/main/java/forestry/factory/gadgets/MachineRaintank.java b/src/main/java/forestry/factory/gadgets/MachineRaintank.java index 9bb02b0f8..19a473214 100755 --- a/src/main/java/forestry/factory/gadgets/MachineRaintank.java +++ b/src/main/java/forestry/factory/gadgets/MachineRaintank.java @@ -67,7 +67,7 @@ public class MachineRaintank extends TileBase implements ISidedInventory, ILiqui public void validate() { // Raintanks in desert biomes are useless if (worldObj != null) { - BiomeGenBase biome = Utils.getBiomeAt(worldObj, xCoord, zCoord); + BiomeGenBase biome = worldObj.getBiomeGenForCoordsBody(xCoord, zCoord); isValidBiome = BiomeHelper.canRainOrSnow(biome); setErrorCondition(!isValidBiome, EnumErrorCode.INVALIDBIOME); } diff --git a/src/main/java/forestry/factory/gadgets/MachineSqueezer.java b/src/main/java/forestry/factory/gadgets/MachineSqueezer.java index 6153497ce..b53d5ca0b 100755 --- a/src/main/java/forestry/factory/gadgets/MachineSqueezer.java +++ b/src/main/java/forestry/factory/gadgets/MachineSqueezer.java @@ -282,7 +282,7 @@ public class MachineSqueezer extends TilePowered implements ISidedInventory, ILi } private boolean removeResources(ItemStack[] stacks) { - EntityPlayer player = Proxies.common.getPlayer(worldObj, getOwnerProfile()); + EntityPlayer player = Proxies.common.getPlayer(worldObj, getOwner()); return InvTools.removeSets(getInternalInventory(), 1, stacks, SLOT_RESOURCE_1, SLOTS_RESOURCE_COUNT, player, false, true, true); } diff --git a/src/main/java/forestry/factory/gadgets/TileWorktable.java b/src/main/java/forestry/factory/gadgets/TileWorktable.java index 327a3e591..242097fd8 100755 --- a/src/main/java/forestry/factory/gadgets/TileWorktable.java +++ b/src/main/java/forestry/factory/gadgets/TileWorktable.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.factory.gadgets; +import java.io.IOException; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryCrafting; @@ -23,11 +25,9 @@ import forestry.core.interfaces.ICrafter; import forestry.core.inventory.InvTools; import forestry.core.inventory.InventoryAdapter; import forestry.core.inventory.TileInventoryAdapter; -import forestry.core.network.ForestryPacket; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.GuiId; -import forestry.core.network.PacketIds; -import forestry.core.network.PacketTileNBT; -import forestry.core.network.PacketTileUpdate; import forestry.core.proxy.Proxies; import forestry.core.utils.GuiUtil; import forestry.core.utils.RecipeUtil; @@ -66,7 +66,6 @@ public class TileWorktable extends TileBase implements ICrafter { super.writeToNBT(nbttagcompound); craftingInventory.writeToNBT(nbttagcompound); - memorized.writeToNBT(nbttagcompound); } @@ -75,24 +74,24 @@ public class TileWorktable extends TileBase implements ICrafter { super.readFromNBT(nbttagcompound); craftingInventory.readFromNBT(nbttagcompound); - memorized.readFromNBT(nbttagcompound); } /* NETWORK */ @Override - public void fromPacket(ForestryPacket packetRaw) { - if (packetRaw instanceof PacketTileUpdate) { - super.fromPacket(packetRaw); - return; - } + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); - PacketTileNBT packet = (PacketTileNBT) packetRaw; - readFromNBT(packet.getTagCompound()); + craftingInventory.writeData(data); + memorized.writeData(data); } - public void sendAll(EntityPlayer player) { - Proxies.net.sendToPlayer(new PacketTileNBT(PacketIds.TILE_NBT, this), player); + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + + craftingInventory.readData(data); + memorized.readData(data); } @Override diff --git a/src/main/java/forestry/factory/gui/ContainerCarpenter.java b/src/main/java/forestry/factory/gui/ContainerCarpenter.java index 226c624e8..26730b855 100755 --- a/src/main/java/forestry/factory/gui/ContainerCarpenter.java +++ b/src/main/java/forestry/factory/gui/ContainerCarpenter.java @@ -13,8 +13,8 @@ package forestry.factory.gui; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.InventoryCraftResult; import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; import forestry.core.gui.ContainerLiquidTanks; import forestry.core.gui.slots.SlotCraftMatrix; @@ -22,105 +22,64 @@ import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotLocked; import forestry.core.gui.slots.SlotOutput; import forestry.core.interfaces.IContainerCrafting; +import forestry.core.network.PacketItemStackDisplay; import forestry.core.proxy.Proxies; import forestry.factory.gadgets.MachineCarpenter; public class ContainerCarpenter extends ContainerLiquidTanks implements IContainerCrafting { - private final IInventory craftingInventory; - public final InventoryCraftingAuto craftMatrix; - public final InventoryCraftResult craftResult; - public ContainerCarpenter(InventoryPlayer inventoryplayer, MachineCarpenter tile) { super(tile, inventoryplayer, 8, 136); - this.tile.activeContainer = this; - craftingInventory = this.tile.getCraftingInventory(); - - craftMatrix = new InventoryCraftingAuto(this, 3, 3); - craftResult = new InventoryCraftResult(); - // Internal inventory for (int i = 0; i < 2; i++) { for (int k = 0; k < 9; k++) { - addSlotToContainer(new Slot(this.tile, MachineCarpenter.SLOT_INVENTORY_1 + k + i * 9, 8 + k * 18, 90 + i * 18)); + addSlotToContainer(new Slot(tile, MachineCarpenter.SLOT_INVENTORY_1 + k + i * 9, 8 + k * 18, 90 + i * 18)); } } // Liquid Input - this.addSlotToContainer(new SlotFiltered(this.tile, MachineCarpenter.SLOT_CAN_INPUT, 120, 20)); + this.addSlotToContainer(new SlotFiltered(tile, MachineCarpenter.SLOT_CAN_INPUT, 120, 20)); // Boxes - this.addSlotToContainer(new SlotFiltered(this.tile, MachineCarpenter.SLOT_BOX, 83, 20)); + this.addSlotToContainer(new SlotFiltered(tile, MachineCarpenter.SLOT_BOX, 83, 20)); // Product - this.addSlotToContainer(new SlotOutput(this.tile, MachineCarpenter.SLOT_PRODUCT, 120, 56)); + this.addSlotToContainer(new SlotOutput(tile, MachineCarpenter.SLOT_PRODUCT, 120, 56)); - // CraftResult display - addSlotToContainer(new SlotLocked(craftResult, 0, 80, 51)); + // Craft Preview display + addSlotToContainer(new SlotLocked(tile.getCraftPreviewInventory(), 0, 80, 51)); // Crafting matrix for (int l = 0; l < 3; l++) { for (int k1 = 0; k1 < 3; k1++) { - addSlotToContainer(new SlotCraftMatrix(this, craftingInventory, k1 + l * 3, 10 + k1 * 18, 20 + l * 18)); + addSlotToContainer(new SlotCraftMatrix(this, tile.getCraftingInventory(), k1 + l * 3, 10 + k1 * 18, 20 + l * 18)); } } - - // Update crafting matrix with current contents of tileentity. - for (int i = 0; i < craftMatrix.getSizeInventory(); i++) { - craftMatrix.setInventorySlotContents(i, craftingInventory.getStackInSlot(i)); - } - } - - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); - updateProductSlot(); } @Override public void onCraftMatrixChanged(IInventory iinventory, int slot) { - craftingInventory.setInventorySlotContents(slot, iinventory.getStackInSlot(slot)); - if (slot < craftMatrix.stackList.length) { - craftMatrix.stackList[slot] = iinventory.getStackInSlot(slot); - } - resetProductDisplay(); + tile.resetRecipe(); } - public void updateProductDisplay() { - // Update crafting matrix with current contents of tileentity. - for (int i = 0; i < craftMatrix.getSizeInventory(); i++) { - craftMatrix.setInventorySlotContents(i, craftingInventory.getStackInSlot(i)); - } - resetProductDisplay(); - } - - private void resetProductDisplay() { - if (tile != null) { - tile.resetProductDisplay(craftMatrix); - updateProductSlot(); - } - } - - private void updateProductSlot() { - // Update crafting display - if (tile.currentRecipe != null) { - craftResult.setInventorySlotContents(0, tile.currentRecipe.getCraftingResult()); - } else { - craftResult.setInventorySlotContents(0, null); - } - } + private ItemStack oldCraftPreview; @Override - public void onContainerClosed(EntityPlayer entityplayer) { - tile.activeContainer = null; - if (entityplayer == null) { - return; - } + public void detectAndSendChanges() { + super.detectAndSendChanges(); - InventoryPlayer inventoryplayer = entityplayer.inventory; - if (inventoryplayer.getItemStack() != null) { - Proxies.common.dropItemPlayer(entityplayer, inventoryplayer.getItemStack()); - inventoryplayer.setItemStack(null); - } + IInventory craftPreviewInventory = tile.getCraftPreviewInventory(); + ItemStack newCraftPreview = craftPreviewInventory.getStackInSlot(0); + if (!ItemStack.areItemStacksEqual(oldCraftPreview, newCraftPreview)) { + oldCraftPreview = newCraftPreview; + + PacketItemStackDisplay packet = new PacketItemStackDisplay(tile, newCraftPreview); + for (Object crafter : crafters) { + if (crafter instanceof EntityPlayer) { + Proxies.net.sendToPlayer(packet, (EntityPlayer) crafter); + } + } + } } + } diff --git a/src/main/java/forestry/factory/gui/ContainerMoistener.java b/src/main/java/forestry/factory/gui/ContainerMoistener.java index 997dcbf78..eeabd732a 100755 --- a/src/main/java/forestry/factory/gui/ContainerMoistener.java +++ b/src/main/java/forestry/factory/gui/ContainerMoistener.java @@ -23,7 +23,7 @@ import forestry.factory.gadgets.MachineMoistener; public class ContainerMoistener extends ContainerLiquidTanks implements IContainerCrafting { public ContainerMoistener(InventoryPlayer player, MachineMoistener tile) { - super(tile, player, 8, 8); + super(tile, player, 8, 84); // Stash for (int l = 0; l < 2; l++) { diff --git a/src/main/java/forestry/factory/gui/ContainerWorktable.java b/src/main/java/forestry/factory/gui/ContainerWorktable.java index c0bd94948..deba2a264 100755 --- a/src/main/java/forestry/factory/gui/ContainerWorktable.java +++ b/src/main/java/forestry/factory/gui/ContainerWorktable.java @@ -21,16 +21,16 @@ import forestry.core.gui.IGuiSelectable; import forestry.core.gui.slots.SlotCraftMatrix; import forestry.core.gui.slots.SlotCrafter; import forestry.core.interfaces.IContainerCrafting; -import forestry.core.network.PacketIds; -import forestry.core.network.PacketPayload; -import forestry.core.network.PacketUpdate; +import forestry.core.network.PacketGuiSelect; +import forestry.core.network.PacketId; +import forestry.core.network.PacketTileStream; import forestry.core.proxy.Proxies; import forestry.core.utils.StackUtils; import forestry.factory.gadgets.TileWorktable; +import forestry.factory.network.PacketWorktableMemoryUpdate; public class ContainerWorktable extends ContainerTile implements IContainerCrafting, IGuiSelectable { - private final EntityPlayer player; private final InventoryCrafting craftMatrix = new InventoryCrafting(this, 3, 3); private long lastUpdate; @@ -60,9 +60,6 @@ public class ContainerWorktable extends ContainerTile implements // Update crafting matrix with current contents of tileentity. updateMatrix(); updateRecipe(); - - this.player = player; - tile.sendAll(player); } @Override @@ -73,7 +70,13 @@ public class ContainerWorktable extends ContainerTile implements } lastUpdate = tile.getMemory().getLastUpdate(); - tile.sendAll(player); + + PacketWorktableMemoryUpdate packet = new PacketWorktableMemoryUpdate(tile); + for (Object crafter : crafters) { + if (crafter instanceof EntityPlayer) { + Proxies.net.sendToPlayer(packet, (EntityPlayer) crafter); + } + } } @Override @@ -105,26 +108,23 @@ public class ContainerWorktable extends ContainerTile implements sendRecipeClick(0, tile.getMemory().capacity); } - public void sendRecipeClick(int mouseButton, int recipeIndex) { - PacketPayload payload = new PacketPayload(2, 0, 0); - payload.intPayload[0] = mouseButton; - payload.intPayload[1] = recipeIndex; - PacketUpdate packet = new PacketUpdate(PacketIds.GUI_SELECTION_CHANGE, payload); + public static void sendRecipeClick(int mouseButton, int recipeIndex) { + PacketGuiSelect packet = new PacketGuiSelect(PacketId.GUI_SELECTION_CHANGE, mouseButton, recipeIndex); Proxies.net.sendToServer(packet); } @Override - public void handleSelectionChange(EntityPlayer player, PacketUpdate packet) { - if (packet.payload.intPayload[0] > 0) { - tile.getMemory().toggleLock(player.worldObj, packet.payload.intPayload[1]); + public void handleSelectionChange(EntityPlayer player, PacketGuiSelect packet) { + if (packet.getPrimaryIndex() > 0) { + tile.getMemory().toggleLock(player.worldObj, packet.getSecondaryIndex()); } else { - tile.chooseRecipe(packet.payload.intPayload[1]); + tile.chooseRecipe(packet.getSecondaryIndex()); updateMatrix(); updateRecipe(); } } @Override - public void setSelection(PacketUpdate packet) { + public void setSelection(PacketGuiSelect packet) { } } diff --git a/src/main/java/forestry/factory/gui/GuiCarpenter.java b/src/main/java/forestry/factory/gui/GuiCarpenter.java index 1ccf23cb9..f957491cc 100755 --- a/src/main/java/forestry/factory/gui/GuiCarpenter.java +++ b/src/main/java/forestry/factory/gui/GuiCarpenter.java @@ -32,7 +32,7 @@ public class GuiCarpenter extends GuiForestryTitled> entries = new ArrayList>(recipe.products.entrySet()); + List> entries = new ArrayList>(recipe.getAllProducts().entrySet()); for (int i = 0; i < Math.min(entries.size(), 9); i++) { - Entry entry = entries.get(i); + Entry entry = entries.get(i); array[i] = entry.getValue() > 0 ? new Object[]{entry.getKey(), entry.getValue()} : null; } - array[9] = recipe.resource; + array[9] = recipe.getInput(); array[10] = machine; generator.addRecipe(template, array); diff --git a/src/main/java/forestry/factory/recipes/RecipeMemory.java b/src/main/java/forestry/factory/recipes/RecipeMemory.java index 3d1d0a79c..83d7be43f 100644 --- a/src/main/java/forestry/factory/recipes/RecipeMemory.java +++ b/src/main/java/forestry/factory/recipes/RecipeMemory.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.factory.recipes; +import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; @@ -28,17 +29,23 @@ import net.minecraft.world.World; import forestry.api.core.INBTTagable; import forestry.core.gui.ContainerDummy; import forestry.core.inventory.InventoryAdapter; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IStreamable; import forestry.core.utils.PlainInventory; -public class RecipeMemory implements INBTTagable { +public class RecipeMemory implements INBTTagable, IStreamable { - public static final class Recipe implements INBTTagable { + public static final class Recipe implements INBTTagable, IStreamable { private InventoryAdapter matrix; private long lastUsed; private boolean locked; private ItemStack cachedRecipeOutput; + public Recipe() { + } + public Recipe(InventoryCrafting crafting) { this.matrix = new InventoryAdapter(new PlainInventory(crafting)); } @@ -106,6 +113,23 @@ public class RecipeMemory implements INBTTagable { nbttagcompound.setBoolean("Locked", locked); } + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + sanitizeMatrix(); + matrix.writeData(data); + data.writeLong(lastUsed); + data.writeBoolean(locked); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + matrix = new InventoryAdapter(new InventoryCrafting(DUMMY_CONTAINER, 3, 3)); + matrix.readData(data); + sanitizeMatrix(); + lastUsed = data.readLong(); + locked = data.readBoolean(); + } + /** * This is a nasty hack to hide a bug where the recipe stacks somehow * get the stackSize set to -1. Which makes the recipe no longer work, @@ -275,4 +299,15 @@ public class RecipeMemory implements INBTTagable { nbttagcompound.setTag("RecipeMemory", nbttaglist); } + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + data.writeStreamables(recipes); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + recipes.clear(); + List newRecipes = data.readStreamables(Recipe.class); + recipes.addAll(newRecipes); + } } diff --git a/src/main/java/forestry/farming/FarmTarget.java b/src/main/java/forestry/farming/FarmTarget.java index 2d3053395..3961d7b8c 100755 --- a/src/main/java/forestry/farming/FarmTarget.java +++ b/src/main/java/forestry/farming/FarmTarget.java @@ -62,7 +62,7 @@ public class FarmTarget { for (extent = 0; extent < limit; extent++) { Block platform = VectUtil.getBlock(world, position); Vect soilPosition = new Vect(position.x, position.y + 1, position.z); - if (!StructureLogicFarm.bricks.contains(platform) || !FarmLogic.canBreakSoil(world, soilPosition)) { + if (!StructureLogicFarm.bricks.contains(platform)) { break; } position.add(getDirection()); diff --git a/src/main/java/forestry/farming/GuiHandlerFarming.java b/src/main/java/forestry/farming/GuiHandlerFarming.java index 79665dff2..206e12e36 100755 --- a/src/main/java/forestry/farming/GuiHandlerFarming.java +++ b/src/main/java/forestry/farming/GuiHandlerFarming.java @@ -15,7 +15,7 @@ import net.minecraft.world.World; import forestry.core.GuiHandlerBase; import forestry.core.network.GuiId; -import forestry.core.network.PacketIds; +import forestry.core.network.PacketId; import forestry.core.network.PacketSocketUpdate; import forestry.core.proxy.Proxies; import forestry.farming.gadgets.TileFarmPlain; @@ -33,8 +33,8 @@ public class GuiHandlerFarming extends GuiHandlerBase { switch (GuiId.values()[id]) { case MultiFarmGUI: - TileFarmPlain tile = (TileFarmPlain) getTileForestry(world, x, y, z); - Proxies.net.sendToPlayer(new PacketSocketUpdate(PacketIds.SOCKET_UPDATE, x, y, z, tile), player); + TileFarmPlain tile = getTileForestry(world, x, y, z, player, TileFarmPlain.class); + Proxies.net.sendToPlayer(new PacketSocketUpdate(PacketId.SOCKET_UPDATE, tile), player); return new ContainerFarm(player.inventory, tile); default: return null; @@ -50,7 +50,7 @@ public class GuiHandlerFarming extends GuiHandlerBase { switch (GuiId.values()[id]) { case MultiFarmGUI: - return new GuiFarm(player, (TileFarmPlain) getTileForestry(world, x, y, z)); + return new GuiFarm(player, getTileForestry(world, x, y, z, player, TileFarmPlain.class)); default: return null; diff --git a/src/main/java/forestry/farming/gadgets/TileFarm.java b/src/main/java/forestry/farming/gadgets/TileFarm.java index f35b4c0f3..06cc97f0e 100755 --- a/src/main/java/forestry/farming/gadgets/TileFarm.java +++ b/src/main/java/forestry/farming/gadgets/TileFarm.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.farming.gadgets; +import java.io.IOException; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; @@ -26,9 +28,9 @@ import forestry.api.farming.IFarmComponent; import forestry.api.farming.IFarmListener; import forestry.core.gadgets.TileForestry; import forestry.core.inventory.IInventoryAdapter; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.GuiId; -import forestry.core.network.PacketPayload; -import forestry.core.proxy.Proxies; public abstract class TileFarm extends TileForestry implements IFarmComponent { @@ -129,28 +131,28 @@ public abstract class TileFarm extends TileForestry implements IFarmComponent { } /* TILEFORESTRY */ - @Override - public PacketPayload getPacketPayload() { - PacketPayload payload = new PacketPayload(0, 3); - payload.shortPayload[0] = (short) farmBlock.ordinal(); - payload.shortPayload[1] = (short) (isMaster() ? 1 : 0); + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeShort(farmBlock.ordinal()); + data.writeBoolean(isMaster()); // so the client can know if it is part of an integrated structure - payload.shortPayload[2] = (short) masterY; - - return payload; + data.writeShort(masterY); } @Override - public void fromPacketPayload(PacketPayload payload) { - EnumFarmBlock farmType = EnumFarmBlock.values()[payload.shortPayload[0]]; - if (payload.shortPayload[1] > 0 && !isMaster()) { + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + short farmBlockOrdinal = data.readShort(); + EnumFarmBlock farmType = EnumFarmBlock.values()[farmBlockOrdinal]; + if (data.readBoolean() && !isMaster()) { makeMaster(); } // so the client can know if it is part of an integrated structure - this.masterY = payload.shortPayload[2]; + this.masterY = data.readShort(); if (this.farmBlock != farmType) { this.farmBlock = farmType; @@ -180,7 +182,7 @@ public abstract class TileFarm extends TileForestry implements IFarmComponent { this.isMaster = true; if (worldObj != null && !worldObj.isRemote) { - sendNetworkUpdate(); + setNeedsNetworkUpdate(); } } diff --git a/src/main/java/forestry/farming/gadgets/TileFarmPlain.java b/src/main/java/forestry/farming/gadgets/TileFarmPlain.java index 6afebb71f..6000a6f16 100755 --- a/src/main/java/forestry/farming/gadgets/TileFarmPlain.java +++ b/src/main/java/forestry/farming/gadgets/TileFarmPlain.java @@ -62,7 +62,6 @@ import forestry.core.proxy.Proxies; import forestry.core.utils.DelayTimer; import forestry.core.utils.GuiUtil; import forestry.core.utils.StackUtils; -import forestry.core.utils.Utils; import forestry.core.vect.Vect; import forestry.core.vect.VectUtil; import forestry.farming.FarmHelper; @@ -216,7 +215,7 @@ public class TileFarmPlain extends TileFarm implements IFarmHousing, ISocketable } private void setBiomeInformation() { - this.biome = Utils.getBiomeAt(worldObj, xCoord, zCoord); + this.biome = worldObj.getBiomeGenForCoordsBody(xCoord, zCoord); } private static TreeMap> createTargets(World world, Vect targetStart, final int allowedExtent, final int farmSizeNorthSouth, final int farmSizeEastWest) { @@ -257,7 +256,7 @@ public class TileFarmPlain extends TileFarm implements IFarmHousing, ISocketable Block platform = VectUtil.getBlock(world, groundLocation); Vect soilPosition = new Vect(groundLocation.x, groundLocation.y + 1, groundLocation.z); - if (!StructureLogicFarm.bricks.contains(platform) || !FarmLogic.canBreakSoil(world, soilPosition)) { + if (!StructureLogicFarm.bricks.contains(platform)) { break; } @@ -776,7 +775,7 @@ public class TileFarmPlain extends TileFarm implements IFarmHousing, ISocketable @Override public void removeResources(ItemStack[] resources) { - EntityPlayer player = Proxies.common.getPlayer(worldObj, getOwnerProfile()); + EntityPlayer player = Proxies.common.getPlayer(worldObj, getOwner()); InvTools.removeSets(getInternalInventory(), 1, resources, SLOT_RESOURCES_1, SLOT_RESOURCES_COUNT, player, false, true, true); } @@ -805,7 +804,7 @@ public class TileFarmPlain extends TileFarm implements IFarmHousing, ISocketable continue; } - EntityPlayer player = Proxies.common.getPlayer(world, getOwnerProfile()); + EntityPlayer player = Proxies.common.getPlayer(world, getOwner()); if (!germling.plantSaplingAt(player, inventory.getStackInSlot(i), world, x, y, z)) { continue; } @@ -973,7 +972,7 @@ public class TileFarmPlain extends TileFarm implements IFarmHousing, ISocketable @Override public float getExactTemperature() { - return biome.temperature; + return biome.getFloatTemperature(xCoord, yCoord, zCoord); } @Override @@ -992,12 +991,6 @@ public class TileFarmPlain extends TileFarm implements IFarmHousing, ISocketable return Config.hints.get("farm"); } - /* IOWNABLE */ - @Override - public boolean isOwnable() { - return true; - } - private static class FarmPlainInventoryAdapter extends TileInventoryAdapter { public FarmPlainInventoryAdapter(TileFarmPlain tile) { super(tile, TileFarmPlain.SLOT_COUNT, "Items"); diff --git a/src/main/java/forestry/farming/gui/GuiFarm.java b/src/main/java/forestry/farming/gui/GuiFarm.java index e98a486cf..c7fd937b5 100755 --- a/src/main/java/forestry/farming/gui/GuiFarm.java +++ b/src/main/java/forestry/farming/gui/GuiFarm.java @@ -34,9 +34,8 @@ public class GuiFarm extends GuiForestry { protected class FarmLedger extends Ledger { public FarmLedger() { - super(ledgerManager); + super(ledgerManager, "farm"); maxHeight = 118; - overlayColor = fontColor.get("ledger.farm.background"); } @Override @@ -52,22 +51,24 @@ public class GuiFarm extends GuiForestry { return; } - fontRendererObj.drawStringWithShadow(StringUtil.localize("gui.hydration"), x + 22, y + 8, fontColor.get("ledger.power.header")); - fontRendererObj.drawStringWithShadow(StringUtil.localize("gui.hydr.heat") + ":", x + 22, y + 20, fontColor.get("ledger.power.subheader")); - fontRendererObj.drawString(StringUtil.floatAsPercent(inventory.getHydrationTempModifier()), x + 22, y + 32, fontColor.get("ledger.power.text")); - fontRendererObj.drawStringWithShadow(StringUtil.localize("gui.hydr.humid") + ":", x + 22, y + 44, fontColor.get("ledger.power.subheader")); - fontRendererObj.drawString(StringUtil.floatAsPercent(inventory.getHydrationHumidModifier()), x + 22, y + 56, fontColor.get("ledger.power.text")); - fontRendererObj.drawStringWithShadow(StringUtil.localize("gui.hydr.rainfall") + ":", x + 22, y + 68, fontColor.get("ledger.power.subheader")); - fontRendererObj.drawString(StringUtil.floatAsPercent(inventory.getHydrationRainfallModifier()) + " (" + inventory.getDrought() + " d)", x + 22, y + 80, - fontColor.get("ledger.power.text")); - fontRendererObj.drawStringWithShadow(StringUtil.localize("gui.hydr.overall") + ":", x + 22, y + 92, fontColor.get("ledger.power.subheader")); - fontRendererObj.drawString(StringUtil.floatAsPercent(inventory.getHydrationModifier()), x + 22, y + 104, fontColor.get("ledger.power.text")); + drawHeader(StringUtil.localize("gui.hydration"), x + 22, y + 8); + drawSubheader(StringUtil.localize("gui.hydr.heat") + ':', x + 22, y + 20); + drawText(StringUtil.floatAsPercent(inventory.getHydrationTempModifier()), x + 22, y + 32); + + drawSubheader(StringUtil.localize("gui.hydr.humid") + ':', x + 22, y + 44); + drawText(StringUtil.floatAsPercent(inventory.getHydrationHumidModifier()), x + 22, y + 56); + + drawSubheader(StringUtil.localize("gui.hydr.rainfall") + ':', x + 22, y + 68); + drawText(StringUtil.floatAsPercent(inventory.getHydrationRainfallModifier()) + " (" + inventory.getDrought() + " d)", x + 22, y + 80); + + drawSubheader(StringUtil.localize("gui.hydr.overall") + ':', x + 22, y + 92); + drawText(StringUtil.floatAsPercent(inventory.getHydrationModifier()), x + 22, y + 104); } @Override public String getTooltip() { - return StringUtil.floatAsPercent(inventory.getHydrationModifier()) + " " + StringUtil.localize("gui.hydration"); + return StringUtil.floatAsPercent(inventory.getHydrationModifier()) + ' ' + StringUtil.localize("gui.hydration"); } } diff --git a/src/main/java/forestry/farming/logic/CropBasicAgriCraft.java b/src/main/java/forestry/farming/logic/CropBasicAgriCraft.java index 119b4d3e0..391777988 100644 --- a/src/main/java/forestry/farming/logic/CropBasicAgriCraft.java +++ b/src/main/java/forestry/farming/logic/CropBasicAgriCraft.java @@ -14,6 +14,7 @@ import java.util.ArrayList; import java.util.Collection; import net.minecraft.block.Block; +import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.world.World; @@ -44,7 +45,7 @@ public class CropBasicAgriCraft extends Crop { harvest.remove(1); //AgriCraft returns cropsticks in 0, seeds in 1 in getDrops, removing since harvesting doesn't return them. } harvest.remove(0); - Proxies.common.addBlockDestroyEffects(world, pos.x, pos.y, pos.z, block, 0); + Proxies.common.addBlockDestroyEffects(world, pos.x, pos.y, pos.z, Blocks.melon_block, 0); world.setBlockMetadataWithNotify(pos.x, pos.y, pos.z, 0, Defaults.FLAG_BLOCK_SYNCH); return harvest; } diff --git a/src/main/java/forestry/farming/logic/FarmLogic.java b/src/main/java/forestry/farming/logic/FarmLogic.java index cfd122166..41a847955 100755 --- a/src/main/java/forestry/farming/logic/FarmLogic.java +++ b/src/main/java/forestry/farming/logic/FarmLogic.java @@ -10,8 +10,6 @@ ******************************************************************************/ package forestry.farming.logic; -import com.google.common.collect.ImmutableSet; - import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.init.Blocks; @@ -23,10 +21,8 @@ import net.minecraftforge.common.util.ForgeDirection; import forestry.api.farming.IFarmHousing; import forestry.api.farming.IFarmLogic; import forestry.core.config.Defaults; -import forestry.core.config.ForestryBlock; import forestry.core.render.SpriteSheet; import forestry.core.vect.Vect; -import forestry.core.vect.VectUtil; public abstract class FarmLogic implements IFarmLogic { @@ -34,20 +30,6 @@ public abstract class FarmLogic implements IFarmLogic { protected boolean isManual; - private static final ImmutableSet breakableSoil = ImmutableSet.of( - Blocks.air, - Blocks.dirt, - Blocks.grass, - Blocks.sand, - Blocks.farmland, - Blocks.mycelium, - Blocks.soul_sand, - Blocks.water, - Blocks.flowing_water, - Blocks.end_stone, - ForestryBlock.soil.block() - ); - public FarmLogic(IFarmHousing housing) { this.housing = housing; } @@ -57,11 +39,6 @@ public abstract class FarmLogic implements IFarmLogic { return this; } - public static boolean canBreakSoil(World world, Vect position) { - Block block = VectUtil.getBlock(world, position); - return breakableSoil.contains(block) || block.isReplaceable(world, position.getX(), position.getY(), position.getZ()); - } - protected World getWorld() { return housing.getWorld(); } diff --git a/src/main/java/forestry/farming/logic/FarmLogicHomogeneous.java b/src/main/java/forestry/farming/logic/FarmLogicHomogeneous.java index b48440e8f..ba631bf3e 100644 --- a/src/main/java/forestry/farming/logic/FarmLogicHomogeneous.java +++ b/src/main/java/forestry/farming/logic/FarmLogicHomogeneous.java @@ -100,7 +100,7 @@ public abstract class FarmLogicHomogeneous extends FarmLogic { } ItemStack soilStack = VectUtil.getAsItemStack(world, position); - if (isAcceptedSoil(soilStack) || !canBreakSoil(world, position)) { + if (isAcceptedSoil(soilStack)) { continue; } diff --git a/src/main/java/forestry/farming/logic/FarmLogicWatered.java b/src/main/java/forestry/farming/logic/FarmLogicWatered.java index 629582beb..dd386528d 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicWatered.java +++ b/src/main/java/forestry/farming/logic/FarmLogicWatered.java @@ -28,6 +28,7 @@ import forestry.core.utils.StackUtils; import forestry.core.utils.Utils; import forestry.core.vect.Vect; import forestry.core.vect.VectUtil; +import forestry.farming.gadgets.StructureLogicFarm; public abstract class FarmLogicWatered extends FarmLogic { @@ -95,19 +96,25 @@ public abstract class FarmLogicWatered extends FarmLogic { for (int i = 0; i < extent; i++) { Vect position = translateWithOffset(x, y, z, direction, i); - Block block = VectUtil.getBlock(world, position); - if (!isAirBlock(block) && !Utils.isReplaceableBlock(block)) { - - ItemStack blockStack = VectUtil.getAsItemStack(world, position); - if (!isAcceptedGround(blockStack) && housing.hasResources(resources)) { - produce.addAll(BlockUtil.getBlockDrops(getWorld(), position)); - setBlock(position, Blocks.air, 0); - return trySetSoil(position); - } + Block soil = VectUtil.getBlock(world, position); + ItemStack soilStack = VectUtil.getAsItemStack(world, position); + if (isAcceptedGround(soilStack) || !housing.hasResources(resources)) { continue; } + Vect platformPosition = position.add(0, -1, 0); + Block platformBlock = VectUtil.getBlock(world, platformPosition); + if (!StructureLogicFarm.bricks.contains(platformBlock)) { + break; + } + + if (!isAirBlock(soil) && !Utils.isReplaceableBlock(soil)) { + produce.addAll(BlockUtil.getBlockDrops(getWorld(), position)); + setBlock(position, Blocks.air, 0); + return trySetSoil(position); + } + if (isManual || isWaterSourceBlock(world, position)) { continue; } @@ -128,6 +135,12 @@ public abstract class FarmLogicWatered extends FarmLogic { for (int i = 0; i < extent; i++) { Vect position = translateWithOffset(x, y, z, direction, i); + Vect platformPosition = position.add(0, -1, 0); + Block platformBlock = VectUtil.getBlock(world, platformPosition); + if (!StructureLogicFarm.bricks.contains(platformBlock)) { + break; + } + if (trySetWater(world, position)) { return true; } diff --git a/src/main/java/forestry/food/items/ItemInfuser.java b/src/main/java/forestry/food/items/ItemInfuser.java index a8d766800..b9951ec0a 100755 --- a/src/main/java/forestry/food/items/ItemInfuser.java +++ b/src/main/java/forestry/food/items/ItemInfuser.java @@ -250,7 +250,8 @@ public class ItemInfuser extends ItemForestry { super(player, 6, itemStack); } - private void trySeasoning() { + @Override + public void onSlotClick(EntityPlayer player) { // Need input ItemStack input = getStackInSlot(inputSlot); @@ -309,11 +310,6 @@ public class ItemInfuser extends ItemForestry { setInventorySlotContents(outputSlot, seasoned); } - @Override - public void markDirty() { - trySeasoning(); - } - @Override public String getInventoryName() { return "Infuser"; diff --git a/src/main/java/forestry/lepidopterology/genetics/Butterfly.java b/src/main/java/forestry/lepidopterology/genetics/Butterfly.java index 6c01727fb..d618778ae 100755 --- a/src/main/java/forestry/lepidopterology/genetics/Butterfly.java +++ b/src/main/java/forestry/lepidopterology/genetics/Butterfly.java @@ -135,7 +135,7 @@ public class Butterfly extends IndividualLiving implements IButterfly { return false; } - BiomeGenBase biome = Utils.getBiomeAt(world, (int) x, (int) z); + BiomeGenBase biome = world.getBiomeGenForCoordsBody((int) x, (int) z); if (getGenome().getPrimary().getSpawnBiomes().size() > 0) { boolean noneMatched = true; @@ -158,7 +158,7 @@ public class Butterfly extends IndividualLiving implements IButterfly { } } - return isAcceptedEnvironment(biome); + return isAcceptedEnvironment(world, x, y, z); } @Override @@ -166,7 +166,7 @@ public class Butterfly extends IndividualLiving implements IButterfly { if (!canFly(world)) { return false; } - return isAcceptedEnvironment(Utils.getBiomeAt(world, (int) x, (int) z)); + return isAcceptedEnvironment(world, x, y, z); } private boolean canFly(World world) { @@ -178,12 +178,14 @@ public class Butterfly extends IndividualLiving implements IButterfly { @Override public boolean isAcceptedEnvironment(World world, double x, double y, double z) { - return isAcceptedEnvironment(Utils.getBiomeAt(world, (int) x, (int) z)); + return isAcceptedEnvironment(world, (int)x, (int)y, (int)z); } - private boolean isAcceptedEnvironment(BiomeGenBase biome) { - return AlleleManager.climateHelper.isWithinLimits(EnumTemperature.getFromValue(biome.temperature), - EnumHumidity.getFromValue(biome.rainfall), + private boolean isAcceptedEnvironment(World world, int x, int y, int z) { + BiomeGenBase biome = world.getBiomeGenForCoords(x, z); + EnumTemperature biomeTemperature = EnumTemperature.getFromBiome(biome, x, y, z); + EnumHumidity biomeHumidity = EnumHumidity.getFromValue(biome.rainfall); + return AlleleManager.climateHelper.isWithinLimits(biomeTemperature, biomeHumidity, getGenome().getPrimary().getTemperature(), getGenome().getToleranceTemp(), getGenome().getPrimary().getHumidity(), getGenome().getToleranceHumid()); } @@ -221,7 +223,7 @@ public class Butterfly extends IndividualLiving implements IButterfly { return new Butterfly(new ButterflyGenome(chromosomes)); } - private IChromosome[] mutateSpecies(IButterflyNursery nursery, IGenome genomeOne, IGenome genomeTwo) { + private static IChromosome[] mutateSpecies(IButterflyNursery nursery, IGenome genomeOne, IGenome genomeTwo) { World world = nursery.getWorld(); diff --git a/src/main/java/forestry/lepidopterology/genetics/ButterflyGenome.java b/src/main/java/forestry/lepidopterology/genetics/ButterflyGenome.java index 962109daf..5a7981543 100755 --- a/src/main/java/forestry/lepidopterology/genetics/ButterflyGenome.java +++ b/src/main/java/forestry/lepidopterology/genetics/ButterflyGenome.java @@ -17,6 +17,7 @@ import forestry.api.genetics.EnumTolerance; import forestry.api.genetics.IAlleleFloat; import forestry.api.genetics.IAlleleFlowers; import forestry.api.genetics.IAlleleInteger; +import forestry.api.genetics.IAlleleSpecies; import forestry.api.genetics.IChromosome; import forestry.api.genetics.IFlowerProvider; import forestry.api.genetics.ISpeciesRoot; @@ -42,6 +43,11 @@ public class ButterflyGenome extends Genome implements IButterflyGenome { // NBT RETRIEVAL public static IAlleleButterflySpecies getSpecies(ItemStack itemStack) { + IAlleleSpecies species = getSpeciesDirectly(itemStack); + if (species instanceof IAlleleButterflySpecies) { + return (IAlleleButterflySpecies) species; + } + return (IAlleleButterflySpecies) getActiveAllele(itemStack, EnumButterflyChromosome.SPECIES, PluginLepidopterology.butterflyInterface); } diff --git a/src/main/java/forestry/lepidopterology/items/ItemFlutterlyzer.java b/src/main/java/forestry/lepidopterology/items/ItemFlutterlyzer.java index 75e3cabf2..4172e6814 100755 --- a/src/main/java/forestry/lepidopterology/items/ItemFlutterlyzer.java +++ b/src/main/java/forestry/lepidopterology/items/ItemFlutterlyzer.java @@ -39,7 +39,8 @@ public class ItemFlutterlyzer extends ItemInventoried { return PluginLepidopterology.butterflyInterface.isMember(itemStack); } - private void tryAnalyze() { + @Override + public void onSlotClick(EntityPlayer player) { // Source slot to analyze empty if (getStackInSlot(SLOT_SPECIMEN) == null) { return; @@ -76,11 +77,6 @@ public class ItemFlutterlyzer extends ItemInventoried { setInventorySlotContents(SLOT_SPECIMEN, null); } - @Override - public void markDirty() { - tryAnalyze(); - } - /* IHINTSOURCE */ @Override public boolean hasHints() { diff --git a/src/main/java/forestry/mail/GuiHandlerMail.java b/src/main/java/forestry/mail/GuiHandlerMail.java index d1103ed3a..65f519ca5 100755 --- a/src/main/java/forestry/mail/GuiHandlerMail.java +++ b/src/main/java/forestry/mail/GuiHandlerMail.java @@ -70,13 +70,13 @@ public class GuiHandlerMail extends GuiHandlerBase { } case MailboxGUI: - return new GuiMailbox(player.inventory, (MachineMailbox) getTileForestry(world, x, y, z)); + return new GuiMailbox(player.inventory, getTileForestry(world, x, y, z, player, MachineMailbox.class)); case PhilatelistGUI: - return new GuiPhilatelist(player.inventory, (MachinePhilatelist) getTileForestry(world, x, y, z)); + return new GuiPhilatelist(player.inventory, getTileForestry(world, x, y, z, player, MachinePhilatelist.class)); case TraderGUI: - return new GuiTrader(player.inventory, (MachineTrader) getTileForestry(world, x, y, z)); + return new GuiTrader(player.inventory, getTileForestry(world, x, y, z, player, MachineTrader.class)); case TraderNameGUI: - return new GuiTradeName(player.inventory, (MachineTrader) getTileForestry(world, x, y, z)); + return new GuiTradeName(player.inventory, getTileForestry(world, x, y, z, player, MachineTrader.class)); default: return null; @@ -116,13 +116,13 @@ public class GuiHandlerMail extends GuiHandlerBase { } case MailboxGUI: - return new ContainerMailbox(player.inventory, (MachineMailbox) getTileForestry(world, x, y, z)); + return new ContainerMailbox(player.inventory, getTileForestry(world, x, y, z, player, MachineMailbox.class)); case PhilatelistGUI: - return new ContainerPhilatelist(player.inventory, (MachinePhilatelist) getTileForestry(world, x, y, z)); + return new ContainerPhilatelist(player.inventory, getTileForestry(world, x, y, z, player, MachinePhilatelist.class)); case TraderGUI: - return new ContainerTrader(player.inventory, (MachineTrader) getTileForestry(world, x, y, z)); + return new ContainerTrader(player.inventory, getTileForestry(world, x, y, z, player, MachineTrader.class)); case TraderNameGUI: - return new ContainerTradeName(player.inventory, (MachineTrader) getTileForestry(world, x, y, z)); + return new ContainerTradeName(player.inventory, getTileForestry(world, x, y, z, player, MachineTrader.class)); default: return null; diff --git a/src/main/java/forestry/mail/MailAddress.java b/src/main/java/forestry/mail/MailAddress.java index e45803617..e4873e3c3 100644 --- a/src/main/java/forestry/mail/MailAddress.java +++ b/src/main/java/forestry/mail/MailAddress.java @@ -121,7 +121,7 @@ public class MailAddress implements INBTTagable, IMailAddress { public String toString() { String name = getName().toLowerCase(Locale.ENGLISH); if (isPlayer()) { - return type + "-" + name + "-" + gameProfile.getId(); + return type + "-" + name + '-' + gameProfile.getId(); } else { return type + "-" + name; } diff --git a/src/main/java/forestry/mail/PacketHandlerMail.java b/src/main/java/forestry/mail/PacketHandlerMail.java index ea5140853..7fb2c548c 100755 --- a/src/main/java/forestry/mail/PacketHandlerMail.java +++ b/src/main/java/forestry/mail/PacketHandlerMail.java @@ -10,15 +10,15 @@ ******************************************************************************/ package forestry.mail; -import java.io.DataInputStream; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; -import forestry.core.interfaces.IPacketHandler; -import forestry.core.network.PacketIds; -import forestry.core.network.PacketUpdate; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.IPacketHandler; +import forestry.core.network.PacketId; +import forestry.core.network.PacketString; import forestry.core.proxy.Proxies; import forestry.mail.gui.ContainerCatalogue; import forestry.mail.gui.ContainerLetter; @@ -26,48 +26,49 @@ import forestry.mail.gui.ContainerTradeName; import forestry.mail.gui.GuiMailboxInfo; import forestry.mail.network.PacketLetterInfo; import forestry.mail.network.PacketPOBoxInfo; +import forestry.mail.network.PacketRequestLetterInfo; public class PacketHandlerMail implements IPacketHandler { @Override - public boolean onPacketData(int packetID, DataInputStream data, EntityPlayer player) throws IOException { + public boolean onPacketData(PacketId packetID, DataInputStreamForestry data, EntityPlayer player) throws IOException { - PacketUpdate packet; switch (packetID) { - case PacketIds.LETTER_INFO: - PacketLetterInfo packetT = new PacketLetterInfo(); - packetT.readData(data); - onLetterInfo(packetT); + case LETTER_INFO: { + PacketLetterInfo packet = new PacketLetterInfo(data); + onLetterInfo(packet); return true; - case PacketIds.POBOX_INFO: - PacketPOBoxInfo packetP = new PacketPOBoxInfo(); - packetP.readData(data); - onPOBoxInfo(packetP); + } + case POBOX_INFO: { + PacketPOBoxInfo packet = new PacketPOBoxInfo(data); + onPOBoxInfo(packet); return true; - case PacketIds.LETTER_RECIPIENT: - packet = new PacketUpdate(); - packet.readData(data); - onLetterRecipient(player, packet); + } + case LETTER_REQUEST_INFO: { + PacketRequestLetterInfo packet = new PacketRequestLetterInfo(data); + onLetterRequestInfo(player, packet); return true; - case PacketIds.LETTER_TEXT: - packet = new PacketUpdate(); - packet.readData(data); + } + case LETTER_TEXT: { + PacketString packet = new PacketString(data); onLetterText(player, packet); return true; - case PacketIds.TRADING_ADDRESS_SET: - packet = new PacketUpdate(); - packet.readData(data); + } + case TRADING_ADDRESS_SET: { + PacketString packet = new PacketString(data); onAddressSet(player, packet); return true; - case PacketIds.POBOX_INFO_REQUEST: + } + case POBOX_INFO_REQUEST: { onPOBoxInfoRequest(player); return true; + } } return false; } - private void onLetterInfo(PacketLetterInfo packet) { + private static void onLetterInfo(PacketLetterInfo packet) { Container container = Proxies.common.getClientInstance().thePlayer.openContainer; if (container instanceof ContainerLetter) { @@ -78,11 +79,11 @@ public class PacketHandlerMail implements IPacketHandler { } - private void onPOBoxInfo(PacketPOBoxInfo packet) { + private static void onPOBoxInfo(PacketPOBoxInfo packet) { GuiMailboxInfo.instance.setPOBoxInfo(packet.poboxInfo); } - private void onAddressSet(EntityPlayer player, PacketUpdate packet) { + private static void onAddressSet(EntityPlayer player, PacketString packet) { if (!(player.openContainer instanceof ContainerTradeName)) { return; } @@ -90,7 +91,7 @@ public class PacketHandlerMail implements IPacketHandler { ((ContainerTradeName) player.openContainer).handleSetAddress(packet); } - private void onLetterText(EntityPlayer player, PacketUpdate packet) { + private static void onLetterText(EntityPlayer player, PacketString packet) { if (!(player.openContainer instanceof ContainerLetter)) { return; } @@ -98,22 +99,22 @@ public class PacketHandlerMail implements IPacketHandler { ((ContainerLetter) player.openContainer).handleSetText(packet); } - private void onLetterRecipient(EntityPlayer player, PacketUpdate packet) { + private static void onLetterRequestInfo(EntityPlayer player, PacketRequestLetterInfo packet) { if (!(player.openContainer instanceof ContainerLetter)) { return; } - ((ContainerLetter) player.openContainer).handleSetRecipient(player, packet); + ((ContainerLetter) player.openContainer).handleRequestLetterInfo(player, packet); } - private void onPOBoxInfoRequest(EntityPlayer player) { + private static void onPOBoxInfoRequest(EntityPlayer player) { MailAddress address = new MailAddress(player.getGameProfile()); - POBox pobox = PostRegistry.getPOBox(player.worldObj, address); + POBox pobox = PostRegistry.getOrCreatePOBox(player.worldObj, address); if (pobox == null) { return; } - Proxies.net.sendToPlayer(new PacketPOBoxInfo(PacketIds.POBOX_INFO, pobox.getPOBoxInfo()), player); + Proxies.net.sendToPlayer(new PacketPOBoxInfo(PacketId.POBOX_INFO, pobox.getPOBoxInfo()), player); } } diff --git a/src/main/java/forestry/mail/PostRegistry.java b/src/main/java/forestry/mail/PostRegistry.java index 6fc66c454..a0d77c01d 100755 --- a/src/main/java/forestry/mail/PostRegistry.java +++ b/src/main/java/forestry/mail/PostRegistry.java @@ -30,7 +30,7 @@ import forestry.api.mail.IPostalCarrier; import forestry.api.mail.ITradeStation; import forestry.api.mail.PostManager; import forestry.core.config.ForestryItem; -import forestry.core.network.PacketIds; +import forestry.core.network.PacketId; import forestry.core.proxy.Proxies; import forestry.mail.items.ItemLetter; import forestry.mail.network.PacketPOBoxInfo; @@ -75,7 +75,7 @@ public class PostRegistry implements IPostRegistry { EntityPlayer player = Proxies.common.getPlayer(world, address.getPlayerProfile()); if (player != null) { - Proxies.net.sendToPlayer(new PacketPOBoxInfo(PacketIds.POBOX_INFO, pobox.getPOBoxInfo()), player); + Proxies.net.sendToPlayer(new PacketPOBoxInfo(PacketId.POBOX_INFO, pobox.getPOBoxInfo()), player); } } diff --git a/src/main/java/forestry/mail/PostalCarrier.java b/src/main/java/forestry/mail/PostalCarrier.java index 19a3848e8..deb20e760 100755 --- a/src/main/java/forestry/mail/PostalCarrier.java +++ b/src/main/java/forestry/mail/PostalCarrier.java @@ -25,7 +25,7 @@ import forestry.api.mail.IPostalCarrier; import forestry.api.mail.IPostalState; import forestry.api.mail.ITradeStation; import forestry.api.mail.PostManager; -import forestry.core.network.PacketIds; +import forestry.core.network.PacketId; import forestry.core.proxy.Proxies; import forestry.core.render.TextureManager; import forestry.core.utils.StringUtil; @@ -87,7 +87,7 @@ public class PostalCarrier implements IPostalCarrier { } else { EntityPlayer player = Proxies.common.getPlayer(world, recipient.getPlayerProfile()); if (player != null) { - Proxies.net.sendToPlayer(new PacketPOBoxInfo(PacketIds.POBOX_INFO, pobox.getPOBoxInfo()), player); + Proxies.net.sendToPlayer(new PacketPOBoxInfo(PacketId.POBOX_INFO, pobox.getPOBoxInfo()), player); } } diff --git a/src/main/java/forestry/mail/TickHandlerMailClient.java b/src/main/java/forestry/mail/TickHandlerMailClient.java index 0eb5f5779..ea6c6c0b8 100755 --- a/src/main/java/forestry/mail/TickHandlerMailClient.java +++ b/src/main/java/forestry/mail/TickHandlerMailClient.java @@ -16,7 +16,7 @@ import cpw.mods.fml.common.gameevent.TickEvent.Phase; import cpw.mods.fml.common.gameevent.TickEvent.RenderTickEvent; import forestry.core.network.ForestryPacket; -import forestry.core.network.PacketIds; +import forestry.core.network.PacketId; import forestry.core.proxy.Proxies; import forestry.mail.gui.GuiMailboxInfo; @@ -34,7 +34,7 @@ public class TickHandlerMailClient { if (GuiMailboxInfo.instance.hasPOBoxInfo()) { GuiMailboxInfo.instance.render(0, 0); } else { - Proxies.net.sendToServer(new ForestryPacket(PacketIds.POBOX_INFO_REQUEST)); + Proxies.net.sendToServer(new ForestryPacket(PacketId.POBOX_INFO_REQUEST)); } } } diff --git a/src/main/java/forestry/mail/gadgets/MachineMailbox.java b/src/main/java/forestry/mail/gadgets/MachineMailbox.java index 1ca06e44d..ee0ace082 100755 --- a/src/main/java/forestry/mail/gadgets/MachineMailbox.java +++ b/src/main/java/forestry/mail/gadgets/MachineMailbox.java @@ -80,7 +80,7 @@ public class MachineMailbox extends TileBase implements IMailContainer { @Override public void updateServerSide() { if (!isLinked) { - getOrCreateMailInventory(worldObj, getOwnerProfile()); + getOrCreateMailInventory(worldObj, getOwner()); isLinked = true; } } @@ -112,7 +112,7 @@ public class MachineMailbox extends TileBase implements IMailContainer { @Override public boolean hasMail() { - IInventory mailInventory = getOrCreateMailInventory(worldObj, getOwnerProfile()); + IInventory mailInventory = getOrCreateMailInventory(worldObj, getOwner()); for (int i = 0; i < mailInventory.getSizeInventory(); i++) { if (mailInventory.getStackInSlot(i) != null) { return true; diff --git a/src/main/java/forestry/mail/gadgets/MachineTrader.java b/src/main/java/forestry/mail/gadgets/MachineTrader.java index 7bfeb8848..18b61c148 100755 --- a/src/main/java/forestry/mail/gadgets/MachineTrader.java +++ b/src/main/java/forestry/mail/gadgets/MachineTrader.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.mail.gadgets; +import java.io.IOException; import java.util.Collection; import java.util.LinkedList; @@ -31,8 +32,9 @@ import forestry.api.mail.PostManager; import forestry.core.EnumErrorCode; import forestry.core.gadgets.TileBase; import forestry.core.inventory.IInventoryAdapter; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.GuiId; -import forestry.core.network.PacketPayload; import forestry.core.proxy.Proxies; import forestry.core.utils.StackUtils; import forestry.mail.MailAddress; @@ -87,26 +89,19 @@ public class MachineTrader extends TileBase { } } - @Override - public PacketPayload getPacketPayload() { - if (address == null || address.getName() == null) { - return null; - } + /* NETWORK */ - PacketPayload payload = new PacketPayload(0, 0, 1); - payload.stringPayload[0] = address.getName(); - return payload; + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeUTF(address.getName()); } @Override - public void fromPacketPayload(PacketPayload payload) { - if (payload.isEmpty()) { - address = null; - return; - } - - String addressName = payload.stringPayload[0]; - address = PostManager.postRegistry.getMailAddress(addressName); + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + String address = data.readUTF(); + this.address = PostManager.postRegistry.getMailAddress(address); } /* UPDATING */ @@ -137,7 +132,7 @@ public class MachineTrader extends TileBase { setErrorCondition(!hasSupplies, EnumErrorCode.NOSUPPLIES); } - if (inventory instanceof TradeStation) { + if (inventory instanceof TradeStation && updateOnInterval(200)) { boolean canReceivePayment = ((TradeStation) inventory).canReceivePayment(); setErrorCondition(!canReceivePayment, EnumErrorCode.NOSPACE); } @@ -263,7 +258,7 @@ public class MachineTrader extends TileBase { if (hasValidTradeAddress & hasUniqueTradeAddress) { this.address = address; - PostManager.postRegistry.getOrCreateTradeStation(worldObj, getOwnerProfile(), address); + PostManager.postRegistry.getOrCreateTradeStation(worldObj, getOwner(), address); } } } @@ -275,7 +270,7 @@ public class MachineTrader extends TileBase { return super.getInternalInventory(); } - return (TradeStation) PostManager.postRegistry.getOrCreateTradeStation(worldObj, getOwnerProfile(), address); + return (TradeStation) PostManager.postRegistry.getOrCreateTradeStation(worldObj, getOwner(), address); } /* ITRIGGERPROVIDER */ diff --git a/src/main/java/forestry/mail/gui/ContainerCatalogue.java b/src/main/java/forestry/mail/gui/ContainerCatalogue.java index e6e4418e8..a0c4be0ac 100755 --- a/src/main/java/forestry/mail/gui/ContainerCatalogue.java +++ b/src/main/java/forestry/mail/gui/ContainerCatalogue.java @@ -29,9 +29,8 @@ import forestry.api.mail.ITradeStation; import forestry.api.mail.PostManager; import forestry.api.mail.TradeStationInfo; import forestry.core.gui.IGuiSelectable; -import forestry.core.network.PacketIds; -import forestry.core.network.PacketPayload; -import forestry.core.network.PacketUpdate; +import forestry.core.network.PacketGuiSelect; +import forestry.core.network.PacketId; import forestry.core.proxy.Proxies; import forestry.mail.EnumStationState; import forestry.mail.network.PacketLetterInfo; @@ -132,9 +131,7 @@ public class ContainerCatalogue extends Container implements IGuiSelectable { public void cycleFilter() { if (!Proxies.common.isSimulating(player.worldObj)) { - PacketPayload payload = new PacketPayload(1, 0, 0); - payload.intPayload[0] = 2; - PacketUpdate packet = new PacketUpdate(PacketIds.GUI_SELECTION_CHANGE, payload); + PacketGuiSelect packet = new PacketGuiSelect(PacketId.GUI_SELECTION_CHANGE, 2, 0); Proxies.net.sendToServer(packet); return; } @@ -144,10 +141,9 @@ public class ContainerCatalogue extends Container implements IGuiSelectable { rebuildStationsList(); } - private void sendSelection(boolean advance) { - PacketPayload payload = new PacketPayload(1, 0, 0); - payload.intPayload[0] = advance ? 0 : 1; - PacketUpdate packet = new PacketUpdate(PacketIds.GUI_SELECTION_CHANGE, payload); + private static void sendSelection(boolean advance) { + int value = advance ? 0 : 1; + PacketGuiSelect packet = new PacketGuiSelect(PacketId.GUI_SELECTION_CHANGE, value, 0); Proxies.net.sendToServer(packet); } @@ -191,7 +187,7 @@ public class ContainerCatalogue extends Container implements IGuiSelectable { crafter.sendProgressBarUpdate(this, 2, currentFilter); } - Proxies.net.sendToPlayer(new PacketLetterInfo(PacketIds.LETTER_INFO, EnumAddressee.TRADER, currentTrade, null), player); + Proxies.net.sendToPlayer(new PacketLetterInfo(PacketId.LETTER_INFO, EnumAddressee.TRADER, currentTrade, null), player); needsSynch = false; } } @@ -217,21 +213,24 @@ public class ContainerCatalogue extends Container implements IGuiSelectable { } @Override - public void handleSelectionChange(EntityPlayer player, PacketUpdate packet) { + public void handleSelectionChange(EntityPlayer player, PacketGuiSelect packet) { - if (packet.payload.intPayload[0] == 0) { - nextPage(); - } else if (packet.payload.intPayload[0] == 1) { - previousPage(); - } else if (packet.payload.intPayload[0] == 2) { - cycleFilter(); + switch (packet.getPrimaryIndex()) { + case 0: + nextPage(); + break; + case 1: + previousPage(); + break; + case 2: + cycleFilter(); + break; } needsSynch = true; } @Override - public void setSelection(PacketUpdate packet) { + public void setSelection(PacketGuiSelect packet) { } - } diff --git a/src/main/java/forestry/mail/gui/ContainerLetter.java b/src/main/java/forestry/mail/gui/ContainerLetter.java index b09624935..412def11c 100755 --- a/src/main/java/forestry/mail/gui/ContainerLetter.java +++ b/src/main/java/forestry/mail/gui/ContainerLetter.java @@ -13,8 +13,6 @@ package forestry.mail.gui; import java.util.Iterator; import java.util.UUID; -import org.apache.commons.lang3.StringUtils; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.server.MinecraftServer; import net.minecraft.world.World; @@ -30,13 +28,13 @@ import forestry.api.mail.PostManager; import forestry.api.mail.TradeStationInfo; import forestry.core.gui.ContainerItemInventory; import forestry.core.gui.slots.SlotFiltered; -import forestry.core.network.PacketIds; -import forestry.core.network.PacketPayload; -import forestry.core.network.PacketUpdate; +import forestry.core.network.PacketId; +import forestry.core.network.PacketString; import forestry.core.proxy.Proxies; import forestry.mail.Letter; import forestry.mail.items.ItemLetter.LetterInventory; import forestry.mail.network.PacketLetterInfo; +import forestry.mail.network.PacketRequestLetterInfo; public class ContainerLetter extends ContainerItemInventory { @@ -123,37 +121,11 @@ public class ContainerLetter extends ContainerItemInventory { setCarrierType(postal.getType()); } - public static void setRecipient(String recipientName, EnumAddressee type) { - if (StringUtils.isBlank(recipientName) || type == null) { - return; - } + public void handleRequestLetterInfo(EntityPlayer player, PacketRequestLetterInfo packet) { + String recipientName = packet.getRecipientName(); + EnumAddressee type = packet.getAddressType(); - // / Send to server - 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 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; - } + IMailAddress recipient = getRecipient(recipientName, type); getLetter().setRecipient(recipient); @@ -163,7 +135,24 @@ public class ContainerLetter extends ContainerItemInventory { } // Update info on client - Proxies.net.sendToPlayer(new PacketLetterInfo(PacketIds.LETTER_INFO, type, tradeInfo, recipient), player); + Proxies.net.sendToPlayer(new PacketLetterInfo(PacketId.LETTER_INFO, type, tradeInfo, recipient), player); + } + + public static IMailAddress getRecipient(String recipientName, EnumAddressee type) { + switch (type) { + case PLAYER: { + GameProfile gameProfile = MinecraftServer.getServer().func_152358_ax().func_152655_a(recipientName); + if (gameProfile == null) { + gameProfile = new GameProfile(new UUID(0, 0), recipientName); + } + return PostManager.postRegistry.getMailAddress(gameProfile); + } + case TRADER: { + return PostManager.postRegistry.getMailAddress(recipientName); + } + default: + return null; + } } public IMailAddress getRecipient() { @@ -181,17 +170,13 @@ public class ContainerLetter extends ContainerItemInventory { public void setText(String text) { getLetter().setText(text); - // / Send to server - PacketPayload payload = new PacketPayload(0, 0, 1); - payload.stringPayload[0] = text; - - PacketUpdate packet = new PacketUpdate(PacketIds.LETTER_TEXT, payload); + PacketString packet = new PacketString(PacketId.LETTER_TEXT, text); Proxies.net.sendToServer(packet); } - public void handleSetText(PacketUpdate packet) { - String text = packet.payload.stringPayload[0]; + public void handleSetText(PacketString packet) { + String text = packet.getString(); getLetter().setText(text); } diff --git a/src/main/java/forestry/mail/gui/ContainerMailbox.java b/src/main/java/forestry/mail/gui/ContainerMailbox.java index 397b971c6..a954b7988 100755 --- a/src/main/java/forestry/mail/gui/ContainerMailbox.java +++ b/src/main/java/forestry/mail/gui/ContainerMailbox.java @@ -17,7 +17,7 @@ import net.minecraft.item.ItemStack; import forestry.core.gui.ContainerTile; import forestry.core.gui.slots.SlotOutput; -import forestry.core.network.PacketIds; +import forestry.core.network.PacketId; import forestry.core.proxy.Proxies; import forestry.core.utils.GuiUtil; import forestry.mail.POBox; @@ -56,7 +56,7 @@ public class ContainerMailbox extends ContainerTile { if (GuiUtil.isIndexInRange(slotIndex, SLOT_LETTERS, SLOT_LETTERS_COUNT)) { if (Proxies.common.isSimulating(player.worldObj) && mailInventory != null) { POBoxInfo info = mailInventory.getPOBoxInfo(); - Proxies.net.sendToPlayer(new PacketPOBoxInfo(PacketIds.POBOX_INFO, info), player); + Proxies.net.sendToPlayer(new PacketPOBoxInfo(PacketId.POBOX_INFO, info), player); } } diff --git a/src/main/java/forestry/mail/gui/ContainerTradeName.java b/src/main/java/forestry/mail/gui/ContainerTradeName.java index d3d16efe0..6d2348de4 100755 --- a/src/main/java/forestry/mail/gui/ContainerTradeName.java +++ b/src/main/java/forestry/mail/gui/ContainerTradeName.java @@ -18,9 +18,8 @@ import net.minecraft.inventory.Container; import forestry.api.mail.IMailAddress; import forestry.api.mail.PostManager; -import forestry.core.network.PacketIds; -import forestry.core.network.PacketPayload; -import forestry.core.network.PacketUpdate; +import forestry.core.network.PacketId; +import forestry.core.network.PacketString; import forestry.core.proxy.Proxies; import forestry.mail.gadgets.MachineTrader; @@ -42,18 +41,15 @@ public class ContainerTradeName extends Container { return; } - PacketPayload payload = new PacketPayload(0, 0, 1); - payload.stringPayload[0] = addressName; - - PacketUpdate packet = new PacketUpdate(PacketIds.TRADING_ADDRESS_SET, payload); + PacketString packet = new PacketString(PacketId.TRADING_ADDRESS_SET, addressName); Proxies.net.sendToServer(packet); IMailAddress address = PostManager.postRegistry.getMailAddress(addressName); machine.setAddress(address); } - public void handleSetAddress(PacketUpdate packet) { - String addressName = packet.payload.stringPayload[0]; + public void handleSetAddress(PacketString packet) { + String addressName = packet.getString(); IMailAddress address = PostManager.postRegistry.getMailAddress(addressName); machine.setAddress(address); } diff --git a/src/main/java/forestry/mail/gui/GuiLetter.java b/src/main/java/forestry/mail/gui/GuiLetter.java index 9e3951dea..a7bb19e94 100755 --- a/src/main/java/forestry/mail/gui/GuiLetter.java +++ b/src/main/java/forestry/mail/gui/GuiLetter.java @@ -30,45 +30,13 @@ import forestry.core.gui.GuiForestry; import forestry.core.gui.GuiTextBox; import forestry.core.gui.widgets.Widget; import forestry.core.proxy.Proxies; +import forestry.core.render.SpriteSheet; import forestry.core.utils.StringUtil; import forestry.mail.items.ItemLetter.LetterInventory; +import forestry.mail.network.PacketRequestLetterInfo; public class GuiLetter extends GuiForestry { - protected class AddresseeSlot extends Widget { - - public AddresseeSlot(int xPos, int yPos) { - super(widgetManager, xPos, yPos); - this.width = 26; - this.height = 15; - } - - @Override - public void draw(int startX, int startY) { - - GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); - //mc.renderEngine.bindTexture(Defaults.TEXTURE_PATH_GUI + "/letter.png"); - IPostalCarrier carrier = PostManager.postRegistry.getCarrier(container.getCarrierType()); - if (carrier != null) { - drawTexturedModelRectFromIcon(startX + xPos, startY + yPos - 5, carrier.getIcon(), 26, 26); - } - - } - - @Override - protected String getLegacyTooltip(EntityPlayer player) { - return StringUtil.localize("gui.addressee." + container.getCarrierType().toString()); - } - - @Override - public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { - if (!isProcessedLetter) { - container.advanceCarrierType(); - } - } - - } - private final boolean isProcessedLetter; private boolean checkedSessionVars; @@ -271,7 +239,8 @@ public class GuiLetter extends GuiForestry { return; } - container.setRecipient(recipientName, type); + PacketRequestLetterInfo packet = new PacketRequestLetterInfo(recipientName, type); + Proxies.net.sendToServer(packet); } private void setText() { @@ -281,4 +250,37 @@ public class GuiLetter extends GuiForestry { container.setText(this.text.getText()); } + + protected class AddresseeSlot extends Widget { + + public AddresseeSlot(int xPos, int yPos) { + super(widgetManager, xPos, yPos); + this.width = 26; + this.height = 15; + } + + @Override + public void draw(int startX, int startY) { + IPostalCarrier carrier = PostManager.postRegistry.getCarrier(container.getCarrierType()); + if (carrier != null) { + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); + Proxies.common.bindTexture(SpriteSheet.ITEMS); + drawTexturedModelRectFromIcon(startX + xPos, startY + yPos - 5, carrier.getIcon(), 26, 26); + } + } + + @Override + protected String getLegacyTooltip(EntityPlayer player) { + return StringUtil.localize("gui.addressee." + container.getCarrierType().toString()); + } + + @Override + public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { + if (!isProcessedLetter) { + container.advanceCarrierType(); + } + } + + } + } diff --git a/src/main/java/forestry/mail/items/ItemLetter.java b/src/main/java/forestry/mail/items/ItemLetter.java index 8c7ffe179..9eee710b0 100755 --- a/src/main/java/forestry/mail/items/ItemLetter.java +++ b/src/main/java/forestry/mail/items/ItemLetter.java @@ -53,6 +53,97 @@ public class ItemLetter extends ItemInventoried { EMPTY, SMALL, BIG } + public static ItemStack createStampedLetterStack(ILetter letter) { + LetterSize size = getSize(letter); + int meta = encodeMeta(LetterState.STAMPED, size); + return ForestryItem.letters.getItemStack(1, meta); + } + + @Override + public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { + if (Proxies.common.isSimulating(world)) { + if (itemstack.stackSize == 1) { + entityplayer.openGui(ForestryAPI.instance, GuiId.LetterGUI.ordinal(), world, (int) entityplayer.posX, (int) entityplayer.posY, (int) entityplayer.posZ); + } else { + entityplayer.addChatMessage(new ChatComponentTranslation("for.chat.mail.wrongstacksize")); + } + } + + return itemstack; + } + + @Override + public boolean getShareTag() { + return true; + } + + /* ICONS */ + @SideOnly(Side.CLIENT) + private IIcon[][] icons; + + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(IIconRegister register) { + icons = new IIcon[3][4]; + for (int i = 0; i < 3; i++) { + icons[i][0] = TextureManager.getInstance().registerTex(register, "mail/letter." + i + ".fresh"); + icons[i][1] = TextureManager.getInstance().registerTex(register, "mail/letter." + i + ".stamped"); + icons[i][2] = TextureManager.getInstance().registerTex(register, "mail/letter." + i + ".opened"); + icons[i][3] = TextureManager.getInstance().registerTex(register, "mail/letter." + i + ".emptied"); + } + } + + @SideOnly(Side.CLIENT) + @Override + public IIcon getIconFromDamage(int damage) { + + LetterState state = getState(damage); + LetterSize size = getSize(damage); + + return icons[size.ordinal()][state.ordinal()]; + } + + public static int encodeMeta(LetterState state, LetterSize size) { + int meta = size.ordinal() << 4; + meta |= state.ordinal(); + return meta; + } + + public static LetterState getState(int meta) { + int ordinal = meta & 0x0f; + return LetterState.values()[ordinal]; + } + + public static LetterSize getSize(int meta) { + int ordinal = meta >> 4; + return LetterSize.values()[ordinal]; + } + + public static LetterSize getSize(ILetter letter) { + int count = letter.countAttachments(); + + if (count > 5) { + return LetterSize.BIG; + } else if (count > 1) { + return LetterSize.SMALL; + } else { + return LetterSize.EMPTY; + } + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + @Override + public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean flag) { + NBTTagCompound nbttagcompound = itemstack.getTagCompound(); + if (nbttagcompound == null) { + list.add('<' + StringUtil.localize("gui.blank") + '>'); + return; + } + + ILetter letter = new Letter(nbttagcompound); + letter.addTooltip(list); + } + public static class LetterInventory extends ItemInventory implements IErrorSource, IHintSource { private ILetter letter; @@ -152,11 +243,6 @@ public class ItemLetter extends ItemInventoried { return letter.getInventoryStackLimit(); } - @Override - public void markDirty() { - letter.markDirty(); - } - @Override public boolean isUseableByPlayer(EntityPlayer entityplayer) { return letter.isUseableByPlayer(entityplayer); @@ -210,94 +296,4 @@ public class ItemLetter extends ItemInventoried { } - public static ItemStack createStampedLetterStack(ILetter letter) { - LetterSize size = getSize(letter); - int meta = encodeMeta(LetterState.STAMPED, size); - return ForestryItem.letters.getItemStack(1, meta); - } - - @Override - public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { - if (Proxies.common.isSimulating(world)) { - if (itemstack.stackSize == 1) { - entityplayer.openGui(ForestryAPI.instance, GuiId.LetterGUI.ordinal(), world, (int) entityplayer.posX, (int) entityplayer.posY, (int) entityplayer.posZ); - } else { - entityplayer.addChatMessage(new ChatComponentTranslation("for.chat.mail.wrongstacksize")); - } - } - - return itemstack; - } - - @Override - public boolean getShareTag() { - return true; - } - - /* ICONS */ - @SideOnly(Side.CLIENT) - private IIcon[][] icons; - - @SideOnly(Side.CLIENT) - @Override - public void registerIcons(IIconRegister register) { - icons = new IIcon[3][4]; - for (int i = 0; i < 3; i++) { - icons[i][0] = TextureManager.getInstance().registerTex(register, "mail/letter." + i + ".fresh"); - icons[i][1] = TextureManager.getInstance().registerTex(register, "mail/letter." + i + ".stamped"); - icons[i][2] = TextureManager.getInstance().registerTex(register, "mail/letter." + i + ".opened"); - icons[i][3] = TextureManager.getInstance().registerTex(register, "mail/letter." + i + ".emptied"); - } - } - - @SideOnly(Side.CLIENT) - @Override - public IIcon getIconFromDamage(int damage) { - - LetterState state = getState(damage); - LetterSize size = getSize(damage); - - return icons[size.ordinal()][state.ordinal()]; - } - - public static int encodeMeta(LetterState state, LetterSize size) { - int meta = size.ordinal() << 4; - meta |= state.ordinal(); - return meta; - } - - public static LetterState getState(int meta) { - int ordinal = meta & 0x0f; - return LetterState.values()[ordinal]; - } - - public static LetterSize getSize(int meta) { - int ordinal = meta >> 4; - return LetterSize.values()[ordinal]; - } - - public static LetterSize getSize(ILetter letter) { - int count = letter.countAttachments(); - - if (count > 5) { - return LetterSize.BIG; - } else if (count > 1) { - return LetterSize.SMALL; - } else { - return LetterSize.EMPTY; - } - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - @Override - public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean flag) { - NBTTagCompound nbttagcompound = itemstack.getTagCompound(); - if (nbttagcompound == null) { - list.add('<' + StringUtil.localize("gui.blank") + '>'); - return; - } - - ILetter letter = new Letter(nbttagcompound); - letter.addTooltip(list); - } } diff --git a/src/main/java/forestry/mail/network/PacketLetterInfo.java b/src/main/java/forestry/mail/network/PacketLetterInfo.java index 8ce0d18c4..21ae6e4e7 100644 --- a/src/main/java/forestry/mail/network/PacketLetterInfo.java +++ b/src/main/java/forestry/mail/network/PacketLetterInfo.java @@ -10,8 +10,6 @@ ******************************************************************************/ package forestry.mail.network; -import java.io.DataInputStream; -import java.io.DataOutputStream; import java.io.IOException; import java.util.UUID; @@ -23,7 +21,10 @@ import forestry.api.mail.EnumAddressee; import forestry.api.mail.IMailAddress; import forestry.api.mail.PostManager; import forestry.api.mail.TradeStationInfo; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.ForestryPacket; +import forestry.core.network.PacketId; import forestry.mail.EnumStationState; public class PacketLetterInfo extends ForestryPacket { @@ -32,10 +33,11 @@ public class PacketLetterInfo extends ForestryPacket { public TradeStationInfo tradeInfo; public IMailAddress address; - public PacketLetterInfo() { + public PacketLetterInfo(DataInputStreamForestry data) throws IOException { + super(data); } - public PacketLetterInfo(int id, EnumAddressee type, TradeStationInfo info, IMailAddress address) { + public PacketLetterInfo(PacketId id, EnumAddressee type, TradeStationInfo info, IMailAddress address) { super(id); this.type = type; if (type == EnumAddressee.TRADER) { @@ -46,7 +48,7 @@ public class PacketLetterInfo extends ForestryPacket { } @Override - public void writeData(DataOutputStream data) throws IOException { + public void writeData(DataOutputStreamForestry data) throws IOException { if (type == null) { data.writeShort(-1); @@ -85,17 +87,15 @@ public class PacketLetterInfo extends ForestryPacket { 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.writeItemStack(tradeInfo.tradegood); + data.writeItemStacks(tradeInfo.required); + data.writeShort(tradeInfo.state.ordinal()); } } @Override - public void readData(DataInputStream data) throws IOException { + public void readData(DataInputStreamForestry data) throws IOException { if (data.readShort() < 0) { return; @@ -119,11 +119,8 @@ public class PacketLetterInfo extends ForestryPacket { ItemStack tradegood; ItemStack[] required; - tradegood = readItemStack(data); - required = new ItemStack[data.readShort()]; - for (int i = 0; i < required.length; i++) { - required[i] = readItemStack(data); - } + tradegood = data.readItemStack(); + required = data.readItemStacks(); this.tradeInfo = new TradeStationInfo(address, owner, tradegood, required, EnumStationState.values()[data.readShort()]); } diff --git a/src/main/java/forestry/mail/network/PacketPOBoxInfo.java b/src/main/java/forestry/mail/network/PacketPOBoxInfo.java index b85a78e97..4f6c04151 100755 --- a/src/main/java/forestry/mail/network/PacketPOBoxInfo.java +++ b/src/main/java/forestry/mail/network/PacketPOBoxInfo.java @@ -10,27 +10,29 @@ ******************************************************************************/ package forestry.mail.network; -import java.io.DataInputStream; -import java.io.DataOutputStream; import java.io.IOException; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.ForestryPacket; +import forestry.core.network.PacketId; import forestry.mail.POBoxInfo; public class PacketPOBoxInfo extends ForestryPacket { public POBoxInfo poboxInfo; - public PacketPOBoxInfo() { + public PacketPOBoxInfo(DataInputStreamForestry data) throws IOException { + super(data); } - public PacketPOBoxInfo(int id, POBoxInfo info) { + public PacketPOBoxInfo(PacketId id, POBoxInfo info) { super(id); this.poboxInfo = info; } @Override - public void writeData(DataOutputStream data) throws IOException { + protected void writeData(DataOutputStreamForestry data) throws IOException { if (poboxInfo == null) { data.writeShort(-1); return; @@ -42,7 +44,7 @@ public class PacketPOBoxInfo extends ForestryPacket { } @Override - public void readData(DataInputStream data) throws IOException { + protected void readData(DataInputStreamForestry data) throws IOException { short isNotNull = data.readShort(); if (isNotNull < 0) { diff --git a/src/main/java/forestry/mail/network/PacketRequestLetterInfo.java b/src/main/java/forestry/mail/network/PacketRequestLetterInfo.java new file mode 100644 index 000000000..398e62531 --- /dev/null +++ b/src/main/java/forestry/mail/network/PacketRequestLetterInfo.java @@ -0,0 +1,57 @@ +/******************************************************************************* + * 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.IOException; + +import forestry.api.mail.EnumAddressee; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.ForestryPacket; +import forestry.core.network.PacketId; + +public class PacketRequestLetterInfo extends ForestryPacket { + + private String recipientName; + private short addressType; + + public PacketRequestLetterInfo(DataInputStreamForestry data) throws IOException { + super(data); + } + + public PacketRequestLetterInfo(String recipientName, EnumAddressee addressType) { + super(PacketId.LETTER_REQUEST_INFO); + this.recipientName = recipientName; + this.addressType = (short) addressType.ordinal(); + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeUTF(recipientName); + data.writeShort(addressType); + } + + @Override + protected void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + recipientName = data.readUTF(); + addressType = data.readShort(); + } + + public String getRecipientName() { + return recipientName; + } + + public EnumAddressee getAddressType() { + return EnumAddressee.values()[addressType]; + } +} diff --git a/src/main/java/forestry/pipes/PipeItemsPropolis.java b/src/main/java/forestry/pipes/PipeItemsPropolis.java index 3767284d7..9e4d5c6cd 100755 --- a/src/main/java/forestry/pipes/PipeItemsPropolis.java +++ b/src/main/java/forestry/pipes/PipeItemsPropolis.java @@ -140,7 +140,7 @@ public class PipeItemsPropolis extends Pipe { // Bees need to match one of the genome filters for (IAllele[] pattern : filters) { - if (pipeLogic.matchAllele(pattern[0], bee.getIdent()) && pipeLogic.matchAllele(pattern[1], bee.getGenome().getSecondary().getUID())) { + if (matchAllele(pattern[0], bee.getIdent()) && matchAllele(pattern[1], bee.getGenome().getSecondary().getUID())) { filteredOrientations.add(dir); } } @@ -157,6 +157,14 @@ public class PipeItemsPropolis extends Pipe { } } + private static boolean matchAllele(IAllele filter, String ident) { + if (filter == null) { + return true; + } else { + return filter.getUID().equals(ident); + } + } + public void eventHandler(PipeEventItem.Entered event) { // A bit of speed to perhaps prevent bees from popping out of the pipe. try { diff --git a/src/main/java/forestry/pipes/PipeLogicPropolis.java b/src/main/java/forestry/pipes/PipeLogicPropolis.java index 39efb2186..bef850a76 100755 --- a/src/main/java/forestry/pipes/PipeLogicPropolis.java +++ b/src/main/java/forestry/pipes/PipeLogicPropolis.java @@ -20,24 +20,23 @@ import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAllele; import forestry.api.genetics.IAlleleSpecies; import forestry.core.network.PacketCoordinates; -import forestry.core.network.PacketIds; +import forestry.core.network.PacketId; import forestry.core.network.PacketNBT; -import forestry.core.network.PacketPayload; -import forestry.core.network.PacketUpdate; import forestry.core.proxy.Proxies; +import forestry.pipes.network.PacketGenomeFilterChange; +import forestry.pipes.network.PacketTypeFilterChange; import buildcraft.transport.Pipe; +import buildcraft.transport.PipeTransportItems; public class PipeLogicPropolis { - @SuppressWarnings("rawtypes") - private final Pipe pipe; + private final Pipe pipe; private final EnumFilterType[] typeFilter = new EnumFilterType[6]; private final IAllele[][][] genomeFilter = new IAllele[6][3][2]; - @SuppressWarnings("rawtypes") - public PipeLogicPropolis(Pipe pipe) { + public PipeLogicPropolis(Pipe pipe) { this.pipe = pipe; for (int i = 0; i < typeFilter.length; i++) { typeFilter[i] = EnumFilterType.CLOSED; @@ -51,11 +50,11 @@ public class PipeLogicPropolis { for (int i = 0; i < 6; i++) { for (int j = 0; j < 3; j++) { - if (nbttagcompound.hasKey("GenomeFilterS" + i + "-" + j + "-" + 0)) { - genomeFilter[i][j][0] = AlleleManager.alleleRegistry.getAllele(nbttagcompound.getString("GenomeFilterS" + i + "-" + j + "-" + 0)); + if (nbttagcompound.hasKey("GenomeFilterS" + i + '-' + j + '-' + 0)) { + genomeFilter[i][j][0] = AlleleManager.alleleRegistry.getAllele(nbttagcompound.getString("GenomeFilterS" + i + '-' + j + '-' + 0)); } - if (nbttagcompound.hasKey("GenomeFilterS" + i + "-" + j + "-" + 1)) { - genomeFilter[i][j][1] = AlleleManager.alleleRegistry.getAllele(nbttagcompound.getString("GenomeFilterS" + i + "-" + j + "-" + 1)); + if (nbttagcompound.hasKey("GenomeFilterS" + i + '-' + j + '-' + 1)) { + genomeFilter[i][j][1] = AlleleManager.alleleRegistry.getAllele(nbttagcompound.getString("GenomeFilterS" + i + '-' + j + '-' + 1)); } } } @@ -69,10 +68,10 @@ public class PipeLogicPropolis { for (int i = 0; i < 6; i++) { for (int j = 0; j < 3; j++) { if (genomeFilter[i][j][0] != null) { - nbttagcompound.setString("GenomeFilterS" + i + "-" + j + "-" + 0, genomeFilter[i][j][0].getUID()); + nbttagcompound.setString("GenomeFilterS" + i + '-' + j + '-' + 0, genomeFilter[i][j][0].getUID()); } if (genomeFilter[i][j][1] != null) { - nbttagcompound.setString("GenomeFilterS" + i + "-" + j + "-" + 1, genomeFilter[i][j][1].getUID()); + nbttagcompound.setString("GenomeFilterS" + i + '-' + j + '-' + 1, genomeFilter[i][j][1].getUID()); } } } @@ -89,7 +88,7 @@ public class PipeLogicPropolis { public boolean matchType(ForgeDirection orientation, EnumFilterType type, IBee bee) { EnumFilterType filter = typeFilter[orientation.ordinal()]; if (filter == EnumFilterType.BEE) { - return type != EnumFilterType.ITEM && type != EnumFilterType.CLOSED && type != EnumFilterType.CLOSED; + return type != EnumFilterType.ITEM && type != EnumFilterType.CLOSED; } // Special bee filtering @@ -124,14 +123,6 @@ public class PipeLogicPropolis { return filter == type; } - public boolean matchAllele(IAllele filter, String ident) { - if (filter == null) { - return true; - } else { - return filter.getUID().equals(ident); - } - } - public ArrayList getGenomeFilters(ForgeDirection orientation) { ArrayList filters = new ArrayList(); @@ -184,53 +175,43 @@ public class PipeLogicPropolis { } } - // Server side + /* NETWORK */ public void sendFilterSet(EntityPlayer player) { NBTTagCompound nbttagcompound = new NBTTagCompound(); this.writeToNBT(nbttagcompound); - Proxies.net.sendToPlayer(new PacketNBT(PacketIds.PROP_SEND_FILTER_SET, nbttagcompound), player); - } - - public void handleTypeFilterChange(PacketPayload payload) { - typeFilter[payload.intPayload[0]] = EnumFilterType.values()[payload.intPayload[1]]; - } - - public void handleGenomeFilterChange(PacketPayload payload) { - if (!payload.stringPayload[0].equals("NULL")) { - genomeFilter[payload.intPayload[0]][payload.intPayload[1]][payload.intPayload[2]] = AlleleManager.alleleRegistry - .getAllele(payload.stringPayload[0]); - } else { - genomeFilter[payload.intPayload[0]][payload.intPayload[1]][payload.intPayload[2]] = null; - } - } - - // Client side - public void requestFilterSet() { - Proxies.net.sendToServer(new PacketCoordinates(PacketIds.PROP_REQUEST_FILTER_SET, pipe.container.xCoord, pipe.container.yCoord, pipe.container.zCoord)); - } - - public void sendTypeFilterChange(ForgeDirection orientation, EnumFilterType filter) { - PacketPayload payload = new PacketPayload(2, 0, 0); - payload.intPayload[0] = orientation.ordinal(); - payload.intPayload[1] = filter.ordinal(); - Proxies.net.sendToServer(new PacketUpdate(PacketIds.PROP_SEND_FILTER_CHANGE_TYPE, pipe.container.xCoord, pipe.container.yCoord, pipe.container.zCoord, payload)); - } - - public void sendGenomeFilterChange(ForgeDirection orientation, int pattern, int allele, IAllele species) { - PacketPayload payload = new PacketPayload(3, 0, 1); - payload.intPayload[0] = orientation.ordinal(); - payload.intPayload[1] = pattern; - payload.intPayload[2] = allele; - if (species != null) { - payload.stringPayload[0] = species.getUID(); - } else { - payload.stringPayload[0] = "NULL"; - } - - Proxies.net.sendToServer(new PacketUpdate(PacketIds.PROP_SEND_FILTER_CHANGE_GENOME, pipe.container.xCoord, pipe.container.yCoord, pipe.container.zCoord, payload)); + Proxies.net.sendToPlayer(new PacketNBT(PacketId.PROP_SEND_FILTER_SET, nbttagcompound), player); } public void handleFilterSet(PacketNBT packet) { this.readFromNBT(packet.getTagCompound()); } + + public void requestFilterSet() { + Proxies.net.sendToServer(new PacketCoordinates(PacketId.PROP_REQUEST_FILTER_SET, pipe.container)); + } + + public void sendTypeFilterChange(ForgeDirection orientation, EnumFilterType filter) { + PacketTypeFilterChange packet = new PacketTypeFilterChange(pipe.container, orientation, filter); + Proxies.net.sendToServer(packet); + } + + public void handleTypeFilterChange(PacketTypeFilterChange packet) { + int orientation = packet.getOrientation(); + int filterOrdinal = packet.getFilter(); + typeFilter[orientation] = EnumFilterType.values()[filterOrdinal]; + } + + public void sendGenomeFilterChange(ForgeDirection orientation, int pattern, int allele, IAllele species) { + PacketGenomeFilterChange packet = new PacketGenomeFilterChange(pipe.container, orientation, pattern, allele, species); + Proxies.net.sendToServer(packet); + } + + public void handleGenomeFilterChange(PacketGenomeFilterChange packet) { + IAllele species = packet.getSpecies(); + int orientation = packet.getOrientation(); + int pattern = packet.getPattern(); + int allele = packet.getAllele(); + + genomeFilter[orientation][pattern][allele] = species; + } } diff --git a/src/main/java/forestry/pipes/gui/GuiPropolisPipe.java b/src/main/java/forestry/pipes/gui/GuiPropolisPipe.java index 9d7095733..68eb4a6cc 100755 --- a/src/main/java/forestry/pipes/gui/GuiPropolisPipe.java +++ b/src/main/java/forestry/pipes/gui/GuiPropolisPipe.java @@ -235,9 +235,11 @@ public class GuiPropolisPipe extends GuiForestryof( + )); + + // Powdery combs + RecipeManagers.centrifugeManager.addRecipe(20, ForestryItem.beeComb.getItemStack(1, 10), ImmutableMap.of( + ForestryItem.honeyDrop.getItemStack(), 0.2f, + ForestryItem.beeswax.getItemStack(), 0.2f, + new ItemStack(Items.gunpowder), 0.9f + )); + + // Wheaten Combs + RecipeManagers.centrifugeManager.addRecipe(20, ForestryItem.beeComb.getItemStack(1, 14), ImmutableMap.of( + ForestryItem.honeyDrop.getItemStack(), 0.2f, + ForestryItem.beeswax.getItemStack(), 0.2f, + new ItemStack(Items.wheat), 0.8f + )); + + // Mossy Combs + RecipeManagers.centrifugeManager.addRecipe(20, ForestryItem.beeComb.getItemStack(1, 15), ImmutableMap.of( + ForestryItem.beeswax.getItemStack(), 1.0f, + ForestryItem.honeyDrop.getItemStack(), 0.9f + )); + + // Mellow Combs + RecipeManagers.centrifugeManager.addRecipe(20, ForestryItem.beeComb.getItemStack(1, 16), ImmutableMap.of( + ForestryItem.honeydew.getItemStack(), 0.6f, + ForestryItem.beeswax.getItemStack(), 0.2f, + new ItemStack(Items.quartz), 0.3f + )); + + // Silky Propolis + RecipeManagers.centrifugeManager.addRecipe(5, ForestryItem.propolis.getItemStack(1, 3), ImmutableMap.of( + ForestryItem.craftingMaterial.getItemStack(1, 2), 0.6f, + ForestryItem.propolis.getItemStack(), 0.1f + )); // / FERMENTER RecipeManagers.fermenterManager.addRecipe(ForestryItem.honeydew.getItemStack(), 500, 1.0f, Fluids.SHORT_MEAD.getFluid(1), Fluids.HONEY.getFluid(1)); @@ -812,7 +859,7 @@ public class PluginApiculture extends ForestryPlugin { } private static void parseAdditionalFlowers(String list, ArrayList target) { - List flowers = StackUtils.parseItemStackStrings(list); + List flowers = StackUtils.parseItemStackStrings(list, 0); target.addAll(flowers); } @@ -853,30 +900,26 @@ public class PluginApiculture extends ForestryPlugin { if (message.key.equals("add-candle-lighting-id")) { ItemStack value = message.getItemStackValue(); if (value != null) { - ((BlockCandle) ForestryBlock.candle.block()).addItemToLightingList(value.getItem()); + BlockCandle.addItemToLightingList(value.getItem()); } else { - Logger.getLogger("Forestry").log(Level.WARNING, - "Received an invalid 'add-candle-lighting-id' request from mod %s. Please contact the author and report this issue.", - message.getSender()); + logInvalidIMCMessage(message); } return true; } else if (message.key.equals("add-alveary-slab") && message.isStringMessage()) { try { Block block = GameData.getBlockRegistry().getRaw(message.getStringValue()); - if (block == null || block == Blocks.air) { - Logger.getLogger("Forestry").log(Level.WARNING, - "Received an invalid 'add-alveary-slab' request from mod %s. Please contact the author and report this issue.", - message.getSender()); + if (block != null && block != Blocks.air) { + StructureLogicAlveary.addSlabBlock(block); } else { - StructureLogicAlveary.slabBlocks.add(block); + logInvalidIMCMessage(message); } } catch (Exception e) { - Logger.getLogger("Forestry").log(Level.WARNING, - "Received an invalid 'add-alveary-slab' request from mod %s. Please contact the author and report this issue.", - message.getSender()); + logInvalidIMCMessage(message); } + return true; } + return super.processIMCMessage(message); } diff --git a/src/main/java/forestry/plugins/PluginArboriculture.java b/src/main/java/forestry/plugins/PluginArboriculture.java index e9f9577da..9129128b0 100644 --- a/src/main/java/forestry/plugins/PluginArboriculture.java +++ b/src/main/java/forestry/plugins/PluginArboriculture.java @@ -46,7 +46,6 @@ import forestry.api.genetics.IClassification; import forestry.api.genetics.IClassification.EnumClassLevel; import forestry.api.genetics.IFruitFamily; import forestry.api.recipes.RecipeManagers; -import forestry.api.storage.BackpackManager; import forestry.api.storage.ICrateRegistry; import forestry.api.storage.StorageManager; import forestry.arboriculture.EventHandlerArboriculture; @@ -56,7 +55,6 @@ import forestry.arboriculture.FruitProviderPod.EnumPodType; import forestry.arboriculture.FruitProviderRandom; import forestry.arboriculture.FruitProviderRipening; import forestry.arboriculture.GuiHandlerArboriculture; -import forestry.arboriculture.PacketHandlerArboriculture; import forestry.arboriculture.VillageHandlerArboriculture; import forestry.arboriculture.WoodType; import forestry.arboriculture.commands.CommandTree; @@ -97,6 +95,7 @@ import forestry.arboriculture.items.ItemLeavesBlock; import forestry.arboriculture.items.ItemStairs; import forestry.arboriculture.items.ItemTreealyzer; import forestry.arboriculture.items.ItemWoodBlock; +import forestry.arboriculture.network.PacketHandlerArboriculture; import forestry.arboriculture.proxy.ProxyArboriculture; import forestry.arboriculture.worldgen.WorldGenAcacia; import forestry.arboriculture.worldgen.WorldGenAcaciaVanilla; @@ -143,9 +142,9 @@ import forestry.core.gadgets.BlockBase; import forestry.core.gadgets.MachineDefinition; import forestry.core.genetics.FruitFamily; import forestry.core.genetics.alleles.Allele; -import forestry.core.interfaces.IPacketHandler; import forestry.core.items.ItemForestryBlock; import forestry.core.items.ItemFruit.EnumFruit; +import forestry.core.network.IPacketHandler; import forestry.core.proxy.Proxies; import forestry.core.utils.RecipeUtil; import forestry.core.utils.ShapedRecipeCustom; @@ -281,9 +280,11 @@ public class PluginArboriculture extends ForestryPlugin { // Stairs ForestryBlock.stairs.registerBlock(new BlockArbStairs(ForestryBlock.planks1.block(), 0), ItemStairs.class, "stairs"); ForestryBlock.stairs.block().setHarvestLevel("axe", 0); + OreDictionary.registerOre("stairWood", ForestryBlock.stairs.getWildcard()); // Saplings ForestryBlock.saplingGE.registerBlock(new BlockSapling(), ItemForestryBlock.class, "saplingGE"); + OreDictionary.registerOre("treeSapling", ForestryBlock.saplingGE.getWildcard()); // Leaves ForestryBlock.leaves.registerBlock(new ForestryBlockLeaves(), ItemLeavesBlock.class, "leaves"); @@ -369,33 +370,6 @@ public class PluginArboriculture extends ForestryPlugin { } - @Override - protected void registerBackpackItems() { - - for (ForestryBlock block : logs) { - BackpackManager.definitions.get("forester").addValidItem(block.getWildcard()); - } - - for (ForestryBlock block : fireproofLogs) { - BackpackManager.definitions.get("forester").addValidItem(block.getWildcard()); - } - - BackpackManager.definitions.get("forester").addValidItem(ForestryItem.sapling.getWildcard()); - BackpackManager.definitions.get("forester").addValidItem(ForestryItem.fruits.getWildcard()); - - for (ForestryBlock block : slabs) { - BackpackManager.definitions.get("builder").addValidItem(block.getWildcard()); - } - for (ForestryBlock block : fences) { - BackpackManager.definitions.get("builder").addValidItem(block.getWildcard()); - } - for (ForestryBlock block : planks) { - BackpackManager.definitions.get("builder").addValidItem(block.getWildcard()); - } - - BackpackManager.definitions.get("builder").addValidItem(ForestryBlock.stairs.getWildcard()); - } - @Override protected void registerCrates() { ICrateRegistry crateRegistry = StorageManager.crateRegistry; @@ -538,9 +512,13 @@ public class PluginArboriculture extends ForestryPlugin { for (WoodType woodType : WoodType.values()) { int i = woodType.ordinal(); if (i < 16) { + // TODO remove first recipe on 1.8 Proxies.common.addRecipe(ForestryBlock.fences1.getItemStack(4, i % 16), "###", "# #", '#', ForestryBlock.planks1.getItemStack(1, i % 16)); + Proxies.common.addRecipe(ForestryBlock.fences1.getItemStack(3, i % 16), "#X#", "#X#", '#', ForestryBlock.planks1.getItemStack(1, i % 16), 'X', "stickWood"); } else if (i < 32) { + // TODO remove first recipe on 1.8 Proxies.common.addRecipe(ForestryBlock.fences2.getItemStack(4, i % 16), "###", "# #", '#', ForestryBlock.planks2.getItemStack(1, i % 16)); + Proxies.common.addRecipe(ForestryBlock.fences2.getItemStack(3, i % 16), "#X#", "#X#", '#', ForestryBlock.planks2.getItemStack(1, i % 16), 'X', "stickWood"); } else { throw new RuntimeException("Wood type has no fences defined"); } @@ -1231,11 +1209,12 @@ public class PluginArboriculture extends ForestryPlugin { if (message.key.equals("add-fence-block") && message.isStringMessage()) { Block block = GameData.getBlockRegistry().getRaw(message.getStringValue()); - if (block == null || block == Blocks.air) { - Proxies.log.warning("invalid add-fence-block IMC: can't resolve block name %s.", message.getStringValue()); - } else { + if (block != null && block != Blocks.air) { validFences.add(block); + } else { + logInvalidIMCMessage(message); } + return true; } return super.processIMCMessage(message); } diff --git a/src/main/java/forestry/plugins/PluginBuildCraftTransport.java b/src/main/java/forestry/plugins/PluginBuildCraftTransport.java index 9509540d4..76a0d4033 100644 --- a/src/main/java/forestry/plugins/PluginBuildCraftTransport.java +++ b/src/main/java/forestry/plugins/PluginBuildCraftTransport.java @@ -13,7 +13,6 @@ package forestry.plugins; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import cpw.mods.fml.common.Optional; import cpw.mods.fml.common.registry.GameRegistry; import forestry.core.config.Defaults; @@ -35,13 +34,16 @@ public class PluginBuildCraftTransport extends ForestryPlugin { return "BuildCraft|Transport not found"; } - @Optional.Method(modid = "BuildCraft|Transport") @Override protected void registerRecipes() { - - Item pipeWaterproof = GameRegistry.findItem(BCT, "pipeWaterproof"); - if (pipeWaterproof != null) { - Proxies.common.addRecipe(new ItemStack(pipeWaterproof), "#", '#', ForestryItem.beeswax); + Item beeswax = ForestryItem.beeswax.item(); + if (beeswax != null) { + Item pipeWaterproof = GameRegistry.findItem(BCT, "pipeWaterproof"); + if (pipeWaterproof != null) { + Proxies.common.addShapelessRecipe(new ItemStack(pipeWaterproof), beeswax); + } else { + Proxies.log.fine("No BuildCraft pipe waterproof found."); + } } } } diff --git a/src/main/java/forestry/plugins/PluginCore.java b/src/main/java/forestry/plugins/PluginCore.java index a3e2aee86..7be397075 100644 --- a/src/main/java/forestry/plugins/PluginCore.java +++ b/src/main/java/forestry/plugins/PluginCore.java @@ -100,8 +100,6 @@ public class PluginCore extends ForestryPlugin { AlleleManager.climateHelper = new ClimateHelper(); AlleleManager.alleleFactory = new AlleleFactory(); alleleRegistry.initialize(); - - Allele.setupAPI(); } @Override diff --git a/src/main/java/forestry/plugins/PluginEnderIO.java b/src/main/java/forestry/plugins/PluginEnderIO.java new file mode 100644 index 000000000..0f18b45b7 --- /dev/null +++ b/src/main/java/forestry/plugins/PluginEnderIO.java @@ -0,0 +1,67 @@ +package forestry.plugins; + +import net.minecraft.nbt.NBTTagCompound; + +import net.minecraftforge.fluids.Fluid; + +import cpw.mods.fml.common.event.FMLInterModComms; + +import forestry.core.GameMode; +import forestry.core.config.Defaults; +import forestry.core.fluids.Fluids; +import forestry.core.proxy.Proxies; + +@Plugin(pluginID = "EnderIO", name = "EnderIO", author = "mezz", url = Defaults.URL, unlocalizedDescription = "for.plugin.enderIO.description") +public class PluginEnderIO extends ForestryPlugin { + + private static final String EnderIO = "EnderIO"; + + private static final String FLUID_FUEL_ADD = "fluidFuel:add"; + private static final String FLUID_COOLANT_ADD = "fluidCoolant:add"; + + private static final String KEY_FLUID_NAME = "fluidName"; + private static final String KEY_POWER_PER_CYCLE = "powerPerCycle"; + private static final String KEY_TOTAL_BURN_TIME = "totalBurnTime"; + private static final String KEY_COOLING_PER_MB = "coolingPerMb"; + + @Override + public boolean isAvailable() { + return Proxies.common.isModLoaded(EnderIO); + } + + @Override + public String getFailMessage() { + return "EnderIO not found"; + } + + @Override + public void doInit() { + Fluid ethanol = Fluids.ETHANOL.getFluid(); + if (ethanol != null) { + int ethanolBurnTime = Math.round(Defaults.ENGINE_CYCLE_DURATION_ETHANOL * GameMode.getGameMode().getFloatSetting("fuel.ethanol.combustion")); + addFuel(ethanol, 40, ethanolBurnTime); + } + + Fluid crushedIce = Fluids.ICE.getFluid(); + if (crushedIce != null) { + addCoolant(crushedIce, 10.0f); + } + } + + private static void addFuel(Fluid fluid, int powerPerCycle, int totalBurnTime) { + NBTTagCompound fuelTag = new NBTTagCompound(); + fuelTag.setString(KEY_FLUID_NAME, fluid.getName()); + fuelTag.setInteger(KEY_POWER_PER_CYCLE, powerPerCycle); + fuelTag.setInteger(KEY_TOTAL_BURN_TIME, totalBurnTime); + + FMLInterModComms.sendMessage(EnderIO, FLUID_FUEL_ADD, fuelTag); + } + + private static void addCoolant(Fluid fluid, float coolingPerMb) { + NBTTagCompound coolantTag = new NBTTagCompound(); + coolantTag.setString(KEY_FLUID_NAME, fluid.getName()); + coolantTag.setFloat(KEY_COOLING_PER_MB, coolingPerMb); + + FMLInterModComms.sendMessage(EnderIO, FLUID_COOLANT_ADD, coolantTag); + } +} diff --git a/src/main/java/forestry/plugins/PluginFactory.java b/src/main/java/forestry/plugins/PluginFactory.java index d11c6c465..7c78dda93 100644 --- a/src/main/java/forestry/plugins/PluginFactory.java +++ b/src/main/java/forestry/plugins/PluginFactory.java @@ -32,6 +32,7 @@ import forestry.core.gadgets.MachineDefinition; import forestry.core.gadgets.MachineNBTDefinition; import forestry.core.items.ItemForestryBlock; import forestry.core.items.ItemNBTTile; +import forestry.core.network.IPacketHandler; import forestry.core.proxy.Proxies; import forestry.core.utils.RecipeUtil; import forestry.core.utils.ShapedRecipeCustom; @@ -48,6 +49,7 @@ import forestry.factory.gadgets.MachineSqueezer; import forestry.factory.gadgets.MachineStill; import forestry.factory.gadgets.MillRainmaker; import forestry.factory.gadgets.TileWorktable; +import forestry.factory.network.PacketHandlerFactory; import forestry.factory.recipes.CraftGuideIntegration; import forestry.factory.triggers.FactoryTriggers; @@ -82,6 +84,11 @@ public class PluginFactory extends ForestryPlugin { ); } + @Override + public IPacketHandler getPacketHandler() { + return new PacketHandlerFactory(); + } + @Override protected void disabledSetupAPI() { super.disabledSetupAPI(); @@ -256,14 +263,6 @@ public class PluginFactory extends ForestryPlugin { } } - @Override - protected void registerItems() { - } - - @Override - protected void registerBackpackItems() { - } - @Override protected void registerRecipes() { diff --git a/src/main/java/forestry/plugins/PluginFarming.java b/src/main/java/forestry/plugins/PluginFarming.java index 0faf6d04e..3291f679c 100644 --- a/src/main/java/forestry/plugins/PluginFarming.java +++ b/src/main/java/forestry/plugins/PluginFarming.java @@ -33,12 +33,9 @@ import forestry.api.farming.Farmables; import forestry.api.farming.IFarmable; import forestry.core.circuits.Circuit; import forestry.core.circuits.CircuitLayout; -import forestry.core.config.Config; import forestry.core.config.Defaults; import forestry.core.config.ForestryBlock; import forestry.core.config.ForestryItem; -import forestry.core.interfaces.IOreDictionaryHandler; -import forestry.core.interfaces.ISaveEventHandler; import forestry.core.items.ItemTypedBlock; import forestry.core.proxy.Proxies; import forestry.core.utils.ShapedRecipeCustom; @@ -193,21 +190,20 @@ public class PluginFarming extends ForestryPlugin { if (message.key.equals("add-farmable-sapling")) { String[] tokens = message.getStringValue().split("@"); - String errormsg = String.format("Received an invalid 'add-farmable-sapling' request '%s' from mod %s", message.getStringValue(), - message.getSender()); + String errormsg = getInvalidIMCMessageText(message); if (tokens.length != 2) { - Proxies.log.info(errormsg + "."); + Proxies.log.warning(errormsg); return true; } if (!Farmables.farmables.containsKey(tokens[0])) { - Proxies.log.info("%s for non-existent farm %s.", errormsg, tokens[0]); + Proxies.log.warning("%s For non-existent farm %s.", errormsg, tokens[0]); return true; } String[] items = tokens[1].split("[\\.]+"); if (items.length != 2 && items.length != 4) { - Proxies.log.info("%s for farm '%s': id definitions did not match.", errormsg, tokens[0]); + Proxies.log.warning("%s For farm '%s': id definitions did not match.", errormsg, tokens[0]); return true; } @@ -230,27 +226,27 @@ public class PluginFarming extends ForestryPlugin { new ItemStack(windfall, 1, Integer.parseInt(items[3])))); } } catch (Exception ex) { - Proxies.log.info("%s for farm '%s': ", errormsg, tokens[0], ex.getMessage()); + Proxies.log.warning("%s for farm '%s': %s", errormsg, tokens[0], ex.getMessage()); } return true; } else if (message.key.equals("add-farmable-crop")) { String[] tokens = message.getStringValue().split("@"); - String errormsg = String.format("Received an invalid 'add-farmable-crop' request '%s' from mod %s", message.getStringValue(), message.getSender()); + String errormsg = getInvalidIMCMessageText(message); if (tokens.length != 2) { - Proxies.log.info(errormsg + "."); + Proxies.log.warning(errormsg); return true; } if (!Farmables.farmables.containsKey(tokens[0])) { - Proxies.log.info("%s for non-existent farm %s.", errormsg, tokens[0]); + Proxies.log.warning("%s For non-existent farm %s.", errormsg, tokens[0]); return true; } String[] items = tokens[1].split("[\\.]+"); if (items.length != 4) { - Proxies.log.info("%s for farm '%s': id definitions did not match.", errormsg, tokens[0]); + Proxies.log.warning("%s For farm '%s': id definitions did not match.", errormsg, tokens[0]); return true; } @@ -269,7 +265,7 @@ public class PluginFarming extends ForestryPlugin { crop, Integer.parseInt(items[3]))); } catch (Exception ex) { - Proxies.log.info("%s for farm '%s': ", errormsg, tokens[0], ex.getMessage()); + Proxies.log.warning("%s for farm '%s': %s", errormsg, tokens[0], ex.getMessage()); } return true; @@ -283,28 +279,6 @@ public class PluginFarming extends ForestryPlugin { return new GuiHandlerFarming(); } - @Override - public ISaveEventHandler getSaveEventHandler() { - return null; - } - - @Override - public IOreDictionaryHandler getDictionaryHandler() { - return null; - } - - @Override - protected void registerItems() { - } - - @Override - protected void registerBackpackItems() { - } - - @Override - protected void registerCrates() { - } - @Override protected void registerRecipes() { diff --git a/src/main/java/forestry/plugins/PluginFood.java b/src/main/java/forestry/plugins/PluginFood.java index e4a3df810..a8ebbba7c 100755 --- a/src/main/java/forestry/plugins/PluginFood.java +++ b/src/main/java/forestry/plugins/PluginFood.java @@ -20,8 +20,6 @@ import forestry.api.food.IBeverageEffect; import forestry.core.config.Defaults; import forestry.core.config.ForestryItem; import forestry.core.fluids.Fluids; -import forestry.core.interfaces.IOreDictionaryHandler; -import forestry.core.interfaces.ISaveEventHandler; import forestry.core.items.ItemForestryFood; import forestry.core.proxy.Proxies; import forestry.core.utils.LiquidHelper; diff --git a/src/main/java/forestry/plugins/PluginIC2.java b/src/main/java/forestry/plugins/PluginIC2.java index f2c80a548..a774a664c 100644 --- a/src/main/java/forestry/plugins/PluginIC2.java +++ b/src/main/java/forestry/plugins/PluginIC2.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.plugins; +import com.google.common.collect.ImmutableMap; + import java.util.EnumSet; import net.minecraft.init.Blocks; @@ -28,6 +30,7 @@ import forestry.api.fuels.FuelManager; import forestry.api.fuels.GeneratorFuel; import forestry.api.recipes.RecipeManagers; import forestry.api.storage.BackpackManager; +import forestry.api.storage.IBackpackDefinition; import forestry.api.storage.ICrateRegistry; import forestry.api.storage.StorageManager; import forestry.core.GameMode; @@ -213,21 +216,23 @@ public class PluginIC2 extends ForestryPlugin { @Override @Optional.Method(modid = "IC2") protected void registerBackpackItems() { - if (BackpackManager.backpackItems == null) { + if (BackpackManager.definitions == null) { return; } + IBackpackDefinition forester = BackpackManager.definitions.get("forester"); + if (resin != null) { - BackpackManager.definitions.get("forester").addValidItem(resin); + forester.addValidItem(resin); } if (rubber != null) { - BackpackManager.definitions.get("forester").addValidItem(rubber); + forester.addValidItem(rubber); } if (rubbersapling != null) { - BackpackManager.definitions.get("forester").addValidItem(rubbersapling); + forester.addValidItem(rubbersapling); } if (rubberleaves != null) { - BackpackManager.definitions.get("forester").addValidItem(rubberleaves); + forester.addValidItem(rubberleaves); } } @@ -278,7 +283,7 @@ public class PluginIC2 extends ForestryPlugin { } if (resin != null) { - RecipeManagers.centrifugeManager.addRecipe(20, ForestryItem.propolis.getItemStack(), resin); + RecipeManagers.centrifugeManager.addRecipe(20, ForestryItem.propolis.getItemStack(), ImmutableMap.of(resin, 1.0f)); } else { Proxies.log.fine("Missing IC2 resin, skipping centrifuge recipe for propolis to resin."); } diff --git a/src/main/java/forestry/plugins/PluginMail.java b/src/main/java/forestry/plugins/PluginMail.java index fbb10069d..f1218fc21 100755 --- a/src/main/java/forestry/plugins/PluginMail.java +++ b/src/main/java/forestry/plugins/PluginMail.java @@ -29,9 +29,9 @@ import forestry.core.config.ForestryItem; import forestry.core.fluids.Fluids; import forestry.core.gadgets.BlockBase; import forestry.core.gadgets.MachineDefinition; -import forestry.core.interfaces.IPacketHandler; import forestry.core.interfaces.ISaveEventHandler; import forestry.core.items.ItemForestryBlock; +import forestry.core.network.IPacketHandler; import forestry.core.proxy.Proxies; import forestry.core.utils.ShapedRecipeCustom; import forestry.mail.GuiHandlerMail; diff --git a/src/main/java/forestry/plugins/PluginManager.java b/src/main/java/forestry/plugins/PluginManager.java index dd6c0e07a..bd865d45b 100644 --- a/src/main/java/forestry/plugins/PluginManager.java +++ b/src/main/java/forestry/plugins/PluginManager.java @@ -16,6 +16,7 @@ import com.google.common.collect.Lists; import java.io.File; import java.util.ArrayList; import java.util.EnumSet; +import java.util.HashSet; import java.util.Iterator; import java.util.Locale; import java.util.Random; @@ -37,11 +38,11 @@ import cpw.mods.fml.common.network.IGuiHandler; import cpw.mods.fml.common.registry.GameRegistry; import forestry.Forestry; -import forestry.core.interfaces.IOreDictionaryHandler; -import forestry.core.interfaces.IPacketHandler; +import forestry.api.core.ForestryAPI; import forestry.core.interfaces.IPickupHandler; import forestry.core.interfaces.IResupplyHandler; import forestry.core.interfaces.ISaveEventHandler; +import forestry.core.network.IPacketHandler; import forestry.core.proxy.Proxies; public class PluginManager { @@ -54,7 +55,6 @@ public class PluginManager { public static final ArrayList pickupHandlers = Lists.newArrayList(); public static final ArrayList saveEventHandlers = Lists.newArrayList(); public static final ArrayList resupplyHandlers = Lists.newArrayList(); - public static final ArrayList dictionaryHandlers = Lists.newArrayList(); private static final Set loadedModules = EnumSet.noneOf(Module.class); private static final Set unloadedModules = EnumSet.allOf(Module.class); @@ -88,6 +88,7 @@ public class PluginManager { AGRICRAFT(new PluginAgriCraft()), BIOMESOPLENTY(new PluginBiomesOPlenty()), CHISEL(new PluginChisel()), + ENDERIO(new PluginEnderIO()), EXTRAUTILITIES(new PluginExtraUtilities()), HARVESTCRAFT(new PluginHarvestCraft()), INDUSTRIALCRAFT(new PluginIC2()), @@ -113,7 +114,7 @@ public class PluginManager { } public boolean isEnabled() { - return isModuleLoaded(this); + return ForestryAPI.enabledPlugins.contains(toString()); } public boolean canBeDisabled() { @@ -136,10 +137,6 @@ public class PluginManager { return EnumSet.copyOf(loadedModules); } - public static boolean isModuleLoaded(Module module) { - return loadedModules.contains(module); - } - private static void registerHandlers(ForestryPlugin plugin) { Proxies.log.fine("Registering Handlers for Plugin: {0}", plugin); @@ -168,11 +165,6 @@ public class PluginManager { resupplyHandlers.add(resupplyHandler); } - IOreDictionaryHandler dictionaryHandler = plugin.getDictionaryHandler(); - if (dictionaryHandler != null) { - dictionaryHandlers.add(dictionaryHandler); - } - IFuelHandler fuelHandler = plugin.getFuelHandler(); if (fuelHandler != null) { GameRegistry.registerFuelHandler((fuelHandler)); @@ -228,6 +220,11 @@ public class PluginManager { unloadedModules.removeAll(toLoad); loadedModules.addAll(toLoad); + ForestryAPI.enabledPlugins = new HashSet(); + for (Module m : loadedModules) { + ForestryAPI.enabledPlugins.add(m.toString()); + } + if (config.hasChanged()) { config.save(); } diff --git a/src/main/java/forestry/plugins/PluginPropolisPipe.java b/src/main/java/forestry/plugins/PluginPropolisPipe.java index 5870abe73..18680697b 100755 --- a/src/main/java/forestry/plugins/PluginPropolisPipe.java +++ b/src/main/java/forestry/plugins/PluginPropolisPipe.java @@ -16,7 +16,7 @@ import cpw.mods.fml.common.network.IGuiHandler; import forestry.core.config.Defaults; import forestry.core.config.ForestryItem; -import forestry.core.interfaces.IPacketHandler; +import forestry.core.network.IPacketHandler; import forestry.core.proxy.Proxies; import forestry.pipes.GuiHandlerPipes; import forestry.pipes.network.PacketHandlerPipes; @@ -33,7 +33,8 @@ public class PluginPropolisPipe extends ForestryPlugin { @Override public boolean isAvailable() { - return Proxies.common.isModLoaded("BuildCraft|Transport"); + return Proxies.common.isModLoaded("BuildCraft|Transport") && + Proxies.common.isModLoaded("BuildCraft|Core", "[6.0, 7.0)"); } @Override diff --git a/src/main/java/forestry/plugins/PluginStorage.java b/src/main/java/forestry/plugins/PluginStorage.java index a2222241f..ecdc724ef 100755 --- a/src/main/java/forestry/plugins/PluginStorage.java +++ b/src/main/java/forestry/plugins/PluginStorage.java @@ -11,59 +11,59 @@ package forestry.plugins; import java.awt.Color; +import java.io.File; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; +import java.util.regex.Pattern; -import net.minecraft.block.Block; import net.minecraft.block.BlockBasePressurePlate; import net.minecraft.block.BlockButton; import net.minecraft.block.BlockChest; +import net.minecraft.block.BlockDoor; import net.minecraft.block.BlockFence; import net.minecraft.block.BlockFenceGate; import net.minecraft.block.BlockFurnace; import net.minecraft.block.BlockLadder; import net.minecraft.block.BlockLever; -import net.minecraft.block.BlockLog; -import net.minecraft.block.BlockMelon; -import net.minecraft.block.BlockPumpkin; import net.minecraft.block.BlockRedstoneDiode; +import net.minecraft.block.BlockSlab; import net.minecraft.block.BlockStairs; import net.minecraft.block.BlockTorch; import net.minecraft.block.BlockTrapDoor; import net.minecraft.block.BlockWall; import net.minecraft.block.BlockWorkbench; +import net.minecraft.block.IGrowable; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemDoor; -import net.minecraft.item.ItemFood; import net.minecraft.item.ItemStack; import net.minecraftforge.common.IPlantable; import net.minecraftforge.common.IShearable; +import net.minecraftforge.common.config.Configuration; +import net.minecraftforge.common.config.Property; +import net.minecraftforge.oredict.OreDictionary; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; import cpw.mods.fml.common.network.IGuiHandler; +import forestry.Forestry; import forestry.api.core.Tabs; import forestry.api.recipes.RecipeManagers; import forestry.api.storage.BackpackManager; import forestry.api.storage.EnumBackpackType; import forestry.api.storage.IBackpackDefinition; import forestry.api.storage.StorageManager; -import forestry.core.config.Configuration; import forestry.core.config.Defaults; import forestry.core.config.ForestryBlock; import forestry.core.config.ForestryItem; -import forestry.core.config.Property; import forestry.core.fluids.Fluids; -import forestry.core.interfaces.IOreDictionaryHandler; import forestry.core.interfaces.IPickupHandler; import forestry.core.interfaces.IResupplyHandler; -import forestry.core.interfaces.ISaveEventHandler; import forestry.core.items.ItemCrated; import forestry.core.network.GuiId; import forestry.core.proxy.Proxies; @@ -81,10 +81,9 @@ import forestry.storage.items.ItemNaturalistBackpack.BackpackDefinitionLepidopte import forestry.storage.proxy.ProxyStorage; @Plugin(pluginID = "Storage", name = "Storage", author = "SirSengir", url = Defaults.URL, unlocalizedDescription = "for.plugin.storage.description") -public class PluginStorage extends ForestryPlugin implements IOreDictionaryHandler { +public class PluginStorage extends ForestryPlugin { private static final List crates = new ArrayList(); - private static final String CONFIG_CATEGORY = "backpacks"; @SidedProxy(clientSide = "forestry.storage.proxy.ClientProxyStorage", serverSide = "forestry.storage.proxy.ProxyStorage") public static ProxyStorage proxy; @@ -94,7 +93,6 @@ public class PluginStorage extends ForestryPlugin implements IOreDictionaryHandl private final ArrayList hunterItems = new ArrayList(); private final ArrayList adventurerItems = new ArrayList(); private final ArrayList builderItems = new ArrayList(); - private Configuration config; @Override @SuppressWarnings({"unchecked", "rawtypes"}) @@ -147,37 +145,313 @@ public class PluginStorage extends ForestryPlugin implements IOreDictionaryHandl @Override public void postInit() { - scanForItems(); + File configFile = new File(Forestry.instance.getConfigFolder(), "backpacks.cfg"); + if (!configFile.exists()) { + setDefaultsForConfig(); + } - config = new Configuration(); + File oldConfigFile = new File(Forestry.instance.getConfigFolder(), "backpacks.conf"); + if (oldConfigFile.exists()) { + loadOldConfig(); - Property backpackConf = config.get("backpacks.miner.items", CONFIG_CATEGORY, ""); - backpackConf.comment = "add additional blocks and items for the miner's backpack here in the format modid:name:meta. separate blocks and items using ';'. wildcard for metadata: '*'"; - parseBackpackItems(backpackConf.value, BackpackManager.definitions.get("miner")); - backpackConf = config.get("backpacks.digger.items", CONFIG_CATEGORY, ""); - backpackConf.comment = "add additional blocks and items for the digger's backpack here in the format modid:name:meta. separate blocks and items using ';'. wildcard for metadata: '*'"; - parseBackpackItems(backpackConf.value, BackpackManager.definitions.get("digger")); - backpackConf = config.get("backpacks.forester.items", CONFIG_CATEGORY, ""); - backpackConf.comment = "add additional blocks and items for the forester's backpack here in the format modid:name:meta. separate blocks and items using ';'. wildcard for metadata: '*'"; - parseBackpackItems(backpackConf.value, BackpackManager.definitions.get("forester")); - backpackConf = config.get("backpacks.hunter.items", CONFIG_CATEGORY, ""); - backpackConf.comment = "add additional blocks and items for the hunter's backpack here in the format modid:name:meta. separate blocks and items using ';'. wildcard for metadata: '*'"; - parseBackpackItems(backpackConf.value, BackpackManager.definitions.get("hunter")); - backpackConf = config.get("backpacks.adventurer.items", CONFIG_CATEGORY, ""); - backpackConf.comment = "add blocks and items for the adventurer's backpack here in the format modid:name:meta. separate blocks and items using ';'. wildcard for metadata: '*'"; - parseBackpackItems(backpackConf.value, BackpackManager.definitions.get("adventurer")); - backpackConf = config.get("backpacks.builder.items", CONFIG_CATEGORY, ""); - backpackConf.comment = "add blocks and items for the builder's backpack here in the format modid:name:meta. separate blocks and items using ';'. wildcard for metadata: '*'"; - parseBackpackItems(backpackConf.value, BackpackManager.definitions.get("builder")); + File oldConfigFileRenamed = new File(Forestry.instance.getConfigFolder(), "backpacks.conf.old"); + if (oldConfigFile.renameTo(oldConfigFileRenamed)) { + Proxies.log.info("Migrated backpack settings to the new file 'backpacks.cfg' and renamed 'backpacks.config' to 'backpacks.conf.old'."); + } + } + + Configuration config = new Configuration(configFile); + + handleBackpackConfig(config, "miner"); + handleBackpackConfig(config, "digger"); + handleBackpackConfig(config, "forester"); + handleBackpackConfig(config, "hunter"); + handleBackpackConfig(config, "adventurer"); + handleBackpackConfig(config, "builder"); config.save(); - BackpackManager.definitions.get("miner").addValidItems(minerItems); - BackpackManager.definitions.get("digger").addValidItems(diggerItems); - BackpackManager.definitions.get("forester").addValidItems(foresterItems); - BackpackManager.definitions.get("hunter").addValidItems(hunterItems); - BackpackManager.definitions.get("adventurer").addValidItems(adventurerItems); - BackpackManager.definitions.get("builder").addValidItems(builderItems); + BackpackDefinition forester = (BackpackDefinition) BackpackManager.definitions.get("forester"); + forester.addValidBlockClasses(Arrays.asList( + IPlantable.class, + IGrowable.class, + IShearable.class + )); + forester.addValidItemClasses(Arrays.asList( + IPlantable.class, + IGrowable.class + )); + + BackpackDefinition builder = (BackpackDefinition) BackpackManager.definitions.get("builder"); + builder.addValidBlockClasses(Arrays.asList( + BlockStairs.class, + BlockFence.class, + BlockFenceGate.class, + BlockWall.class, + BlockBasePressurePlate.class, + BlockLever.class, + BlockButton.class, + BlockTorch.class, + BlockRedstoneDiode.class, + BlockChest.class, + BlockWorkbench.class, + BlockFurnace.class, + BlockLadder.class, + BlockTrapDoor.class, + BlockDoor.class, + BlockSlab.class + )); + builder.addValidItemClass(ItemDoor.class); + } + + private static void loadOldConfig() { + + final forestry.core.config.Configuration config = new forestry.core.config.Configuration(); + + final String CONFIG_CATEGORY = "backpacks"; + + forestry.core.config.Property backpackConf = config.get("backpacks.miner.items", CONFIG_CATEGORY, ""); + backpackConf.comment = "add additional blocks and items for the miner's backpack here in the format modid:name:meta. separate blocks and items using ';'. wildcard for metadata: '*'"; + old_parseBackpackItems(backpackConf.value, BackpackManager.definitions.get("miner")); + backpackConf = config.get("backpacks.digger.items", CONFIG_CATEGORY, ""); + backpackConf.comment = "add additional blocks and items for the digger's backpack here in the format modid:name:meta. separate blocks and items using ';'. wildcard for metadata: '*'"; + old_parseBackpackItems(backpackConf.value, BackpackManager.definitions.get("digger")); + backpackConf = config.get("backpacks.forester.items", CONFIG_CATEGORY, ""); + backpackConf.comment = "add additional blocks and items for the forester's backpack here in the format modid:name:meta. separate blocks and items using ';'. wildcard for metadata: '*'"; + old_parseBackpackItems(backpackConf.value, BackpackManager.definitions.get("forester")); + backpackConf = config.get("backpacks.hunter.items", CONFIG_CATEGORY, ""); + backpackConf.comment = "add additional blocks and items for the hunter's backpack here in the format modid:name:meta. separate blocks and items using ';'. wildcard for metadata: '*'"; + old_parseBackpackItems(backpackConf.value, BackpackManager.definitions.get("hunter")); + backpackConf = config.get("backpacks.adventurer.items", CONFIG_CATEGORY, ""); + backpackConf.comment = "add blocks and items for the adventurer's backpack here in the format modid:name:meta. separate blocks and items using ';'. wildcard for metadata: '*'"; + old_parseBackpackItems(backpackConf.value, BackpackManager.definitions.get("adventurer")); + backpackConf = config.get("backpacks.builder.items", CONFIG_CATEGORY, ""); + backpackConf.comment = "add blocks and items for the builder's backpack here in the format modid:name:meta. separate blocks and items using ';'. wildcard for metadata: '*'"; + old_parseBackpackItems(backpackConf.value, BackpackManager.definitions.get("builder")); + } + + private static void old_parseBackpackItems(String list, IBackpackDefinition backpackDefinition) { + List backpackItems = StackUtils.parseItemStackStrings(list, 0); + backpackDefinition.addValidItems(backpackItems); + } + + private void setDefaultsForConfig() { + + final BackpackDefinition miner = (BackpackDefinition) BackpackManager.definitions.get("miner"); + final BackpackDefinition digger = (BackpackDefinition) BackpackManager.definitions.get("digger"); + final BackpackDefinition forester = (BackpackDefinition) BackpackManager.definitions.get("forester"); + final BackpackDefinition adventurer = (BackpackDefinition) BackpackManager.definitions.get("adventurer"); + final BackpackDefinition builder = (BackpackDefinition) BackpackManager.definitions.get("builder"); + final BackpackDefinition hunter = (BackpackDefinition) BackpackManager.definitions.get("hunter"); + + miner.addValidItems(minerItems); + digger.addValidItems(diggerItems); + forester.addValidItems(foresterItems); + hunter.addValidItems(hunterItems); + adventurer.addValidItems(adventurerItems); + builder.addValidItems(builderItems); + + final Pattern minerOreDictPattern = Pattern.compile("(ore|dust|gem|ingot|nugget|crushed|cluster|denseore)[A-Z].*"); + final Pattern diggerOreDictPattern = Pattern.compile("(stone)[A-Z].*"); + final Pattern foresterOreDictPattern = Pattern.compile("(crop|seed|tree)[A-Z].*"); + final Pattern builderOreDictPattern = Pattern.compile("(block|paneGlass|slabWood|stainedClay|stainedGlass)[A-Z].*"); + + final List minerOreDictNames = new ArrayList(); + final List diggerOreDictNames = new ArrayList(Arrays.asList( + "cobblestone", + "stone", + "sand" + )); + final List foresterOreDictNames = new ArrayList(Arrays.asList( + "logWood", + "stickWood", + "woodStick", + "saplingTree" + )); + final List builderOreDictNames = new ArrayList(Arrays.asList( + "stone", + "plankWood", + "stairWood", + "slabWood", + "fenceWood", + "glass", + "blockGlass", + "paneGlass" + )); + + for (String name : OreDictionary.getOreNames()) { + if (minerOreDictPattern.matcher(name).matches()) { + minerOreDictNames.add(name); + } else if (diggerOreDictPattern.matcher(name).matches()) { + if (name.equals("stoneRod")) { + continue; + } + diggerOreDictNames.add(name); + } else if (foresterOreDictPattern.matcher(name).matches()) { + foresterOreDictNames.add(name); + } else if (builderOreDictPattern.matcher(name).matches()) { + if (name.equals("blockHopper")) { + continue; + } + builderOreDictNames.add(name); + } + } + + miner.addValidOreDictNames(minerOreDictNames); + miner.addValidItems(Arrays.asList( + new ItemStack(Blocks.obsidian), + new ItemStack(Blocks.coal_ore), + new ItemStack(Items.coal), + ForestryItem.bronzePickaxe.getItemStack(), + ForestryItem.kitPickaxe.getItemStack(), + ForestryItem.brokenBronzePickaxe.getItemStack() + )); + + digger.addValidOreDictNames(diggerOreDictNames); + digger.addValidItems(Arrays.asList( + new ItemStack(Blocks.dirt, 1, Defaults.WILDCARD), + new ItemStack(Blocks.gravel), + new ItemStack(Items.flint), + new ItemStack(Blocks.netherrack), + new ItemStack(Blocks.sandstone, 1, 0), + new ItemStack(Items.clay_ball), + new ItemStack(Blocks.soul_sand), + ForestryItem.bronzeShovel.getItemStack(), + ForestryItem.kitShovel.getItemStack(), + ForestryItem.brokenBronzeShovel.getItemStack() + )); + + forester.addValidOreDictNames(foresterOreDictNames); + forester.addValidItems(Arrays.asList( + new ItemStack(Blocks.red_mushroom), + new ItemStack(Blocks.brown_mushroom), + new ItemStack(Blocks.red_flower), + new ItemStack(Blocks.yellow_flower), + new ItemStack(Blocks.cactus), + new ItemStack(Blocks.tallgrass, 1, Defaults.WILDCARD), + new ItemStack(Blocks.vine), + new ItemStack(Blocks.pumpkin), + new ItemStack(Blocks.melon_block), + new ItemStack(Items.golden_apple), + new ItemStack(Items.nether_wart), + new ItemStack(Items.pumpkin_seeds), + new ItemStack(Items.melon_seeds) + )); + + hunter.addValidItems(Arrays.asList( + new ItemStack(Items.feather), + new ItemStack(Items.gunpowder), + new ItemStack(Items.blaze_powder), + new ItemStack(Items.blaze_rod), + new ItemStack(Items.bone), + new ItemStack(Items.string), + new ItemStack(Items.rotten_flesh), + new ItemStack(Items.ghast_tear), + new ItemStack(Items.gold_nugget), + new ItemStack(Items.arrow), + new ItemStack(Items.porkchop), + new ItemStack(Items.cooked_porkchop), + new ItemStack(Items.beef), + new ItemStack(Items.cooked_beef), + new ItemStack(Items.chicken), + new ItemStack(Items.cooked_chicken), + new ItemStack(Items.leather), + new ItemStack(Items.egg), + new ItemStack(Items.ender_pearl), + new ItemStack(Items.spider_eye), + new ItemStack(Items.fermented_spider_eye), + new ItemStack(Items.slime_ball), + new ItemStack(Items.dye, 1, 0), + new ItemStack(Blocks.hay_block), + new ItemStack(Blocks.wool, 1, Defaults.WILDCARD), + new ItemStack(Items.ender_eye), + new ItemStack(Items.magma_cream), + new ItemStack(Items.speckled_melon), + new ItemStack(Items.fish), + new ItemStack(Items.cooked_fished), + new ItemStack(Items.lead), + new ItemStack(Items.fishing_rod), + new ItemStack(Items.name_tag), + new ItemStack(Items.saddle), + new ItemStack(Items.diamond_horse_armor), + new ItemStack(Items.golden_horse_armor), + new ItemStack(Items.iron_horse_armor) + )); + + builder.addValidOreDictNames(builderOreDictNames); + builder.addValidItems(Arrays.asList( + new ItemStack(Blocks.torch), + new ItemStack(Blocks.redstone_torch), + new ItemStack(Blocks.redstone_lamp), + new ItemStack(Blocks.stonebrick, 1, Defaults.WILDCARD), + new ItemStack(Blocks.sandstone, 1, 1), + new ItemStack(Blocks.sandstone, 1, 2), + new ItemStack(Blocks.brick_block), + new ItemStack(Blocks.clay), + new ItemStack(Blocks.hardened_clay, 1, Defaults.WILDCARD), + new ItemStack(Blocks.stained_hardened_clay, 1, Defaults.WILDCARD), + new ItemStack(Blocks.packed_ice), + new ItemStack(Blocks.nether_brick), + new ItemStack(Blocks.crafting_table), + new ItemStack(Blocks.furnace), + new ItemStack(Blocks.lever), + new ItemStack(Blocks.dispenser), + new ItemStack(Blocks.dropper), + new ItemStack(Blocks.ladder), + new ItemStack(Blocks.iron_bars), + new ItemStack(Blocks.quartz_block, 1, Defaults.WILDCARD), + new ItemStack(Items.sign), + new ItemStack(Items.item_frame) + )); + + if (PluginManager.Module.APICULTURE.isEnabled()) { + builder.addValidItem(ForestryBlock.candle.getWildcard()); + builder.addValidItem(ForestryBlock.stump.getWildcard()); + } + } + + private static void handleBackpackConfig(Configuration config, String backpackName) { + BackpackDefinition backpackDefinition = (BackpackDefinition) BackpackManager.definitions.get(backpackName); + + List backpackItems; + List backpackOreDict = new ArrayList(); + + { + List validItems = backpackDefinition.getValidItemStacks(); + Collections.sort(validItems); + String[] defaultValidItems = validItems.toArray(new String[validItems.size()]); + + Property backpackConf = config.get("backpacks." + backpackName, "itemStacks", defaultValidItems); + backpackConf.comment = "Add itemStacks for the " + backpackName + "'s backpack here in the format 'modid:name:meta'. For wildcard metadata the format is 'modid:name'."; + + String[] backpackItemList = backpackConf.getStringList(); + backpackItems = StackUtils.parseItemStackStrings(backpackItemList, OreDictionary.WILDCARD_VALUE); + } + + { + List oreIds = backpackDefinition.getValidOreIds(); + String[] defaultOreNames = new String[oreIds.size()]; + for (int i = 0; i < oreIds.size(); i++) { + int oreId = oreIds.get(i); + defaultOreNames[i] = OreDictionary.getOreName(oreId); + } + + List defaultOreNamesList = new ArrayList(); + Collections.addAll(defaultOreNamesList, defaultOreNames); + Collections.sort(defaultOreNamesList); + defaultOreNames = defaultOreNamesList.toArray(new String[defaultOreNamesList.size()]); + + Property backpackConf = config.get("backpacks." + backpackName, "oreDict", defaultOreNames); + backpackConf.comment = "Add ore dictionary names for the " + backpackName + "'s backpack here in the format 'oreDictName'."; + + String[] oreDictNameList = backpackConf.getStringList(); + Collections.addAll(backpackOreDict, oreDictNameList); + } + + backpackDefinition.clearAllValid(); + + backpackDefinition.addValidItems(backpackItems); + backpackDefinition.addValidOreDictNames(backpackOreDict); } public static void registerCrate(ItemCrated crate) { @@ -197,91 +471,24 @@ public class PluginStorage extends ForestryPlugin implements IOreDictionaryHandl } } - public static void addBackpackItem(String pack, ItemStack stack) { - if (stack == null) { - return; - } - BackpackManager.definitions.get(pack).addValidItem(stack); - } - - public static void addBackpackItem(String pack, Block block) { - BackpackManager.definitions.get(pack).addValidItem(new ItemStack(block, 1, Defaults.WILDCARD)); - } - - public static void addBackpackItem(String pack, Item item) { - BackpackManager.definitions.get(pack).addValidItem(new ItemStack(item, 1, Defaults.WILDCARD)); - } - - public static void scanForItems() { - for (Object id : Block.blockRegistry.getKeys()) { - try { - Block block = (Block) Block.blockRegistry.getObject(id); - - if (block instanceof IPlantable - || block instanceof IShearable - || block instanceof BlockLog - || block instanceof BlockMelon - || block instanceof BlockPumpkin) { - addBackpackItem("forester", block); - } - if (block instanceof BlockStairs || block.getRenderType() == 10 - || block instanceof BlockFence || block.getRenderType() == 11 - || block instanceof BlockFenceGate || block.getRenderType() == 21 - || block instanceof BlockWall || block.getRenderType() == 32 - || block instanceof BlockBasePressurePlate - || block instanceof BlockLever - || block instanceof BlockButton - || block instanceof BlockTorch - || block instanceof BlockRedstoneDiode - || block instanceof BlockChest || block.getRenderType() == 22 - || block instanceof BlockWorkbench - || block instanceof BlockFurnace - || block instanceof BlockLadder || block.getRenderType() == 8 - || block instanceof BlockTrapDoor - || block.getUnlocalizedName().contains("door")) { - addBackpackItem("builder", block); - } - } catch (Throwable error) { - error.printStackTrace(); - } - } - - for (Object id : Item.itemRegistry.getKeys()) { - try { - Item item = (Item) Item.itemRegistry.getObject(id); - - if (item instanceof IPlantable) { - addBackpackItem("forester", item); - } else if (item instanceof ItemFood) { - addBackpackItem("hunter", item); - } else if (item instanceof ItemDoor) { - addBackpackItem("builder", item); - } - } catch (Throwable error) { - error.printStackTrace(); - } - } - } - @Override public boolean processIMCMessage(IMCMessage message) { if (message.key.equals("add-backpack-items")) { String[] tokens = message.getStringValue().split("@"); if (tokens.length != 2) { - Logger.getLogger("Forestry").log(Level.INFO, - String.format("Received an invalid 'add-backpack-items' request %s from mod %s", message.getStringValue(), message.getSender())); + logInvalidIMCMessage(message); return true; } if (!BackpackManager.definitions.containsKey(tokens[0])) { - Logger.getLogger("Forestry").log( - Level.INFO, - String.format("Received an invalid 'add-backpack-items' request %s from mod %s for non-existent backpack %s.", - message.getStringValue(), message.getSender(), tokens[0])); + String errorMessage = getInvalidIMCMessageText(message); + Proxies.log.warning("%s For non-existent backpack %s.", errorMessage, tokens[0]); return true; } - parseBackpackItems(tokens[1], BackpackManager.definitions.get(tokens[0])); + IBackpackDefinition backpackDefinition = BackpackManager.definitions.get(tokens[0]); + List itemStacks = StackUtils.parseItemStackStrings(tokens[1], 0); + backpackDefinition.addValidItems(itemStacks); return true; } @@ -348,173 +555,6 @@ public class PluginStorage extends ForestryPlugin implements IOreDictionaryHandl ForestryItem.builderBackpackT2.registerItem(BackpackManager.backpackInterface.addBackpack(definition, EnumBackpackType.T2), "builderBagT2"); } - @Override - protected void registerBackpackItems() { - - // [0] Set valid items in miner's backpack - minerItems.add(new ItemStack(Blocks.obsidian)); - minerItems.add(new ItemStack(Blocks.coal_ore)); - minerItems.add(new ItemStack(Items.coal)); - minerItems.add(new ItemStack(Blocks.diamond_ore)); - minerItems.add(new ItemStack(Items.diamond)); - minerItems.add(new ItemStack(Blocks.gold_ore)); - minerItems.add(new ItemStack(Items.gold_ingot)); - minerItems.add(new ItemStack(Blocks.iron_ore)); - minerItems.add(new ItemStack(Items.iron_ingot)); - minerItems.add(new ItemStack(Blocks.lapis_ore)); - minerItems.add(new ItemStack(Blocks.redstone_ore)); - minerItems.add(new ItemStack(Items.redstone)); - minerItems.add(new ItemStack(Items.dye, 1, 4)); - minerItems.add(new ItemStack(Items.glowstone_dust)); - minerItems.add(new ItemStack(Items.emerald)); - minerItems.add(new ItemStack(Blocks.diamond_block)); - minerItems.add(new ItemStack(Blocks.emerald_block)); - minerItems.add(new ItemStack(Blocks.gold_block)); - minerItems.add(new ItemStack(Blocks.iron_block)); - minerItems.add(new ItemStack(Blocks.lapis_block)); - minerItems.add(ForestryItem.bronzePickaxe.getItemStack()); - minerItems.add(ForestryItem.kitPickaxe.getItemStack()); - minerItems.add(ForestryItem.brokenBronzePickaxe.getItemStack()); - minerItems.add(new ItemStack(Items.quartz)); - minerItems.add(new ItemStack(Blocks.emerald_ore)); - minerItems.add(new ItemStack(Blocks.quartz_ore)); - - // [1] Set valid items in digger's backpack - diggerItems.add(new ItemStack(Blocks.dirt)); - diggerItems.add(new ItemStack(Blocks.cobblestone)); - diggerItems.add(new ItemStack(Blocks.sand)); - diggerItems.add(new ItemStack(Blocks.sandstone)); - diggerItems.add(new ItemStack(Blocks.gravel)); - diggerItems.add(new ItemStack(Items.flint)); - diggerItems.add(new ItemStack(Blocks.netherrack)); - diggerItems.add(new ItemStack(Items.clay_ball)); - diggerItems.add(new ItemStack(Blocks.soul_sand)); - diggerItems.add(ForestryItem.bronzeShovel.getItemStack()); - diggerItems.add(ForestryItem.kitShovel.getItemStack()); - diggerItems.add(ForestryItem.brokenBronzeShovel.getItemStack()); - - // [2] Set valid items in forester's backpack - foresterItems.add(new ItemStack(Blocks.sapling, 1, Defaults.WILDCARD)); - foresterItems.add(new ItemStack(Blocks.red_mushroom)); - foresterItems.add(new ItemStack(Blocks.brown_mushroom)); - foresterItems.add(new ItemStack(Blocks.log, 1, Defaults.WILDCARD)); - foresterItems.add(new ItemStack(Items.wheat_seeds)); - foresterItems.add(new ItemStack(Blocks.red_flower)); - foresterItems.add(new ItemStack(Blocks.yellow_flower)); - foresterItems.add(new ItemStack(Blocks.leaves, 1, Defaults.WILDCARD)); - foresterItems.add(new ItemStack(Blocks.cactus)); - foresterItems.add(new ItemStack(Blocks.tallgrass, 1, Defaults.WILDCARD)); - foresterItems.add(new ItemStack(Blocks.vine)); - foresterItems.add(new ItemStack(Blocks.pumpkin)); - foresterItems.add(new ItemStack(Blocks.melon_block)); - foresterItems.add(new ItemStack(Items.apple)); - foresterItems.add(new ItemStack(Items.golden_apple)); - foresterItems.add(new ItemStack(Items.nether_wart)); - foresterItems.add(new ItemStack(Items.pumpkin_seeds)); - foresterItems.add(new ItemStack(Items.melon_seeds)); - foresterItems.add(new ItemStack(Items.wheat)); - if (PluginManager.Module.ARBORICULTURE.isEnabled()) { - foresterItems.add(ForestryBlock.saplingGE.getWildcard()); - } - - // [3] Set valid items in hunter's backpack - hunterItems.add(new ItemStack(Items.feather)); - hunterItems.add(new ItemStack(Items.gunpowder)); - hunterItems.add(new ItemStack(Items.blaze_powder)); - hunterItems.add(new ItemStack(Items.blaze_rod)); - hunterItems.add(new ItemStack(Items.bone)); - hunterItems.add(new ItemStack(Items.string)); - hunterItems.add(new ItemStack(Items.rotten_flesh)); - hunterItems.add(new ItemStack(Items.ghast_tear)); - hunterItems.add(new ItemStack(Items.gold_nugget)); - hunterItems.add(new ItemStack(Items.arrow)); - hunterItems.add(new ItemStack(Items.porkchop)); - hunterItems.add(new ItemStack(Items.cooked_porkchop)); - hunterItems.add(new ItemStack(Items.beef)); - hunterItems.add(new ItemStack(Items.cooked_beef)); - hunterItems.add(new ItemStack(Items.chicken)); - hunterItems.add(new ItemStack(Items.cooked_chicken)); - hunterItems.add(new ItemStack(Items.leather)); - hunterItems.add(new ItemStack(Items.egg)); - hunterItems.add(new ItemStack(Items.ender_pearl)); - hunterItems.add(new ItemStack(Items.spider_eye)); - hunterItems.add(new ItemStack(Items.fermented_spider_eye)); - hunterItems.add(new ItemStack(Items.slime_ball)); - hunterItems.add(new ItemStack(Items.dye, 1, 0)); - hunterItems.add(new ItemStack(Blocks.hay_block)); - hunterItems.add(new ItemStack(Blocks.wool)); - hunterItems.add(new ItemStack(Blocks.wool, 1, Defaults.WILDCARD)); - hunterItems.add(new ItemStack(Items.ender_eye)); - hunterItems.add(new ItemStack(Items.magma_cream)); - hunterItems.add(new ItemStack(Items.speckled_melon)); - hunterItems.add(new ItemStack(Items.fish)); - hunterItems.add(new ItemStack(Items.cooked_fished)); - hunterItems.add(new ItemStack(Items.lead)); - hunterItems.add(new ItemStack(Items.fishing_rod)); - hunterItems.add(new ItemStack(Items.name_tag)); - hunterItems.add(new ItemStack(Items.saddle)); - hunterItems.add(new ItemStack(Items.diamond_horse_armor)); - hunterItems.add(new ItemStack(Items.golden_horse_armor)); - hunterItems.add(new ItemStack(Items.iron_horse_armor)); - - // [4] Set valid items in adventurer's backpack - - // [5] Set valid items in builder's backpack - if (PluginManager.Module.APICULTURE.isEnabled()) { - builderItems.add(ForestryBlock.candle.getWildcard()); - builderItems.add(ForestryBlock.stump.getWildcard()); - } - - builderItems.add(new ItemStack(Blocks.torch)); - builderItems.add(new ItemStack(Blocks.redstone_torch)); - builderItems.add(new ItemStack(Blocks.redstone_lamp)); - builderItems.add(new ItemStack(Blocks.stonebrick, 1, Defaults.WILDCARD)); - builderItems.add(new ItemStack(Blocks.sandstone, 1, 1)); - builderItems.add(new ItemStack(Blocks.sandstone, 1, 2)); - builderItems.add(new ItemStack(Blocks.stone)); - builderItems.add(new ItemStack(Blocks.brick_block)); - builderItems.add(new ItemStack(Blocks.planks, 1, Defaults.WILDCARD)); - builderItems.add(new ItemStack(Blocks.clay)); - builderItems.add(new ItemStack(Blocks.hardened_clay, 1, Defaults.WILDCARD)); - builderItems.add(new ItemStack(Blocks.stained_hardened_clay, 1, Defaults.WILDCARD)); - builderItems.add(new ItemStack(Blocks.packed_ice)); - builderItems.add(new ItemStack(Blocks.nether_brick)); - builderItems.add(new ItemStack(Blocks.nether_brick_fence)); - builderItems.add(new ItemStack(Blocks.stone_stairs)); - builderItems.add(new ItemStack(Blocks.oak_stairs)); - builderItems.add(new ItemStack(Blocks.brick_stairs)); - builderItems.add(new ItemStack(Blocks.nether_brick_stairs)); - builderItems.add(new ItemStack(Blocks.stone_brick_stairs)); - builderItems.add(new ItemStack(Blocks.glass)); - builderItems.add(new ItemStack(Blocks.glass_pane)); - builderItems.add(new ItemStack(Blocks.chest)); - builderItems.add(new ItemStack(Blocks.crafting_table)); - builderItems.add(new ItemStack(Blocks.furnace)); - builderItems.add(new ItemStack(Blocks.lever)); - builderItems.add(new ItemStack(Blocks.wooden_button)); - builderItems.add(new ItemStack(Blocks.stone_button)); - builderItems.add(new ItemStack(Blocks.dispenser)); - builderItems.add(new ItemStack(Blocks.dropper)); - builderItems.add(new ItemStack(Blocks.ladder)); - builderItems.add(new ItemStack(Blocks.fence)); - builderItems.add(new ItemStack(Blocks.fence_gate)); - builderItems.add(new ItemStack(Blocks.iron_bars)); - builderItems.add(new ItemStack(Blocks.stone_slab, 1, Defaults.WILDCARD)); - builderItems.add(new ItemStack(Blocks.quartz_block, 1, Defaults.WILDCARD)); - builderItems.add(new ItemStack(Blocks.quartz_stairs)); - builderItems.add(new ItemStack(Blocks.sandstone_stairs)); - builderItems.add(new ItemStack(Blocks.birch_stairs)); - builderItems.add(new ItemStack(Blocks.spruce_stairs)); - builderItems.add(new ItemStack(Blocks.jungle_stairs)); - builderItems.add(new ItemStack(Blocks.cobblestone_wall, 1, Defaults.WILDCARD)); - builderItems.add(new ItemStack(Items.iron_door)); - builderItems.add(new ItemStack(Items.wooden_door)); - builderItems.add(new ItemStack(Items.sign)); - builderItems.add(new ItemStack(Items.repeater)); - builderItems.add(new ItemStack(Items.comparator)); - builderItems.add(new ItemStack(Items.item_frame)); - } - @Override protected void registerRecipes() { @@ -593,57 +633,4 @@ public class PluginStorage extends ForestryPlugin implements IOreDictionaryHandl } } - @Override - protected void registerCrates() { - } - - private static void parseBackpackItems(String list, IBackpackDefinition target) { - List backpackItems = StackUtils.parseItemStackStrings(list); - target.addValidItems(backpackItems); - } - - @Override - public ISaveEventHandler getSaveEventHandler() { - return null; - } - - @Override - public IOreDictionaryHandler getDictionaryHandler() { - return this; - } - - @Override - public void onOreRegistration(String name, ItemStack ore) { - - if (ore == null) { - Proxies.log.warning("An ore/item of type %s was registered with the Forge ore dictionary, however the passed itemstack is null. Someone broke it. :(", name); - return; - } - - if (name.startsWith("ingot")) { - minerItems.add(ore); - } else if (name.startsWith("ore")) { - minerItems.add(ore); - } else if (name.startsWith("gem")) { - minerItems.add(ore); - } else if (name.startsWith("dust")) { - 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")) { - foresterItems.add(ore); - } else if (name.equals("stairWood") || name.equals("plankWood") || name.equals("slabWood")) { - builderItems.add(ore); - } else if (name.startsWith("wood")) { - foresterItems.add(ore); - } - } } diff --git a/src/main/java/forestry/storage/BackpackDefinition.java b/src/main/java/forestry/storage/BackpackDefinition.java index a265d3417..680b65b2e 100755 --- a/src/main/java/forestry/storage/BackpackDefinition.java +++ b/src/main/java/forestry/storage/BackpackDefinition.java @@ -15,13 +15,15 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.StatCollector; +import net.minecraftforge.oredict.OreDictionary; + import forestry.api.storage.IBackpackDefinition; -import forestry.core.utils.StackUtils; public class BackpackDefinition implements IBackpackDefinition { @@ -30,7 +32,10 @@ public class BackpackDefinition implements IBackpackDefinition { private final int primaryColor; // - c03384 private final int secondaryColor; - private final ArrayList validItems = new ArrayList(); + private final List validItemStacks = new ArrayList(); + private final List validOreIds = new ArrayList(); + private final List validItemClasses = new ArrayList(); + private final List validBlockClasses = new ArrayList(); public BackpackDefinition(String name, int primaryColor) { this(name, primaryColor, 0xffffff); @@ -75,19 +80,88 @@ public class BackpackDefinition implements IBackpackDefinition { @Override public void addValidItem(ItemStack validItem) { - if (validItem.getItem() != null) { - this.validItems.add(validItem); + if (validItem == null) { + return; } + + Item item = validItem.getItem(); + if (item == null) { + return; + } + + String itemStackString = item.delegate.name(); + + int meta = validItem.getItemDamage(); + if (meta != OreDictionary.WILDCARD_VALUE) { + itemStackString = itemStackString + ':' + meta; + } + + this.validItemStacks.add(itemStackString); } + public void clearAllValid() { + validItemStacks.clear(); + validOreIds.clear(); + } + + @Override public void addValidItems(List validItems) { for (ItemStack validItem : validItems) { addValidItem(validItem); } } - public ArrayList getValidItems() { - return validItems; + public void addValidOreDictName(String oreDictName) { +// if (OreDictionary.doesOreNameExist(oreDictName)) { //TODO: add this back when using a forge version that supports it + int oreId = OreDictionary.getOreID(oreDictName); + validOreIds.add(oreId); +// } + } + + public void addValidOreDictNames(List oreDictNames) { + for (String oreDictName : oreDictNames) { + addValidOreDictName(oreDictName); + } + } + + public void addValidItemClass(Class itemClass) { + if (itemClass != null) { + validItemClasses.add(itemClass); + } + } + + public void addValidItemClasses(List itemClasses) { + for (Class itemClass : itemClasses) { + addValidItemClass(itemClass); + } + } + + public void addValidBlockClass(Class blockClass) { + if (blockClass != null) { + validBlockClasses.add(blockClass); + } + } + + public void addValidBlockClasses(List blockClasses) { + for (Class blockClass : blockClasses) { + addValidBlockClass(blockClass); + } + } + + public List getValidItemStacks() { + return validItemStacks; + } + + public List getValidOreIds() { + return validOreIds; + } + + public List getValidBlockClasses() { + return validBlockClasses; + } + + public List getValidItemClasses() { + return validItemClasses; } // isValidItem can get called multiple times per tick if the player's inventory is full @@ -96,20 +170,65 @@ public class BackpackDefinition implements IBackpackDefinition { private final Map isValidItemCache = new ValidItemCache(); @Override - public boolean isValidItem(ItemStack itemstack) { - Boolean cached = isValidItemCache.get(itemstack); - if (cached != null) { - return cached; + public boolean isValidItem(ItemStack itemStack) { + if (itemStack == null) { + return false; } - for (ItemStack stack : getValidItems()) { - if (StackUtils.isCraftingEquivalent(stack, itemstack, true, false)) { - isValidItemCache.put(itemstack, true); + Boolean isValid = isValidItemCache.get(itemStack); + if (isValid != null) { + return isValid; + } + + isValid = isValidItemUncached(itemStack); + isValidItemCache.put(itemStack, isValid); + return isValid; + } + + private boolean isValidItemUncached(ItemStack itemStack) { + Item item = itemStack.getItem(); + if (item == null) { + return false; + } + + String itemStackStringWild = item.delegate.name(); + if (validItemStacks.contains(itemStackStringWild)) { + return true; + } + + int meta = itemStack.getItemDamage(); + if (meta != OreDictionary.WILDCARD_VALUE) { + String itemStackString = itemStackStringWild + ':' + meta; + if (validItemStacks.contains(itemStackString)) { return true; } } - isValidItemCache.put(itemstack, false); + int[] oreIds = OreDictionary.getOreIDs(itemStack); + for (int oreId : oreIds) { + if (validOreIds.contains(oreId)) { + validItemStacks.add(itemStackStringWild); + return true; + } + } + + for (Class itemClass : validItemClasses) { + if (itemClass.isInstance(item)) { + validItemStacks.add(itemStackStringWild); + return true; + } + } + + Block block = Block.getBlockFromItem(item); + if (block != null) { + for (Class blockClass : validBlockClasses) { + if (blockClass.isInstance(block)) { + validItemStacks.add(itemStackStringWild); + return true; + } + } + } + return false; } diff --git a/src/main/java/forestry/storage/gui/ContainerNaturalistBackpack.java b/src/main/java/forestry/storage/gui/ContainerNaturalistBackpack.java index d0ade8435..78609638b 100755 --- a/src/main/java/forestry/storage/gui/ContainerNaturalistBackpack.java +++ b/src/main/java/forestry/storage/gui/ContainerNaturalistBackpack.java @@ -15,7 +15,7 @@ import net.minecraft.entity.player.EntityPlayer; import forestry.core.gui.ContainerItemInventory; import forestry.core.gui.IGuiSelectable; import forestry.core.gui.slots.SlotFiltered; -import forestry.core.network.PacketUpdate; +import forestry.core.network.PacketGuiSelect; import forestry.storage.GuiHandlerStorage.PagedBackpackInventory; public class ContainerNaturalistBackpack extends ContainerItemInventory implements IGuiSelectable { @@ -32,11 +32,11 @@ public class ContainerNaturalistBackpack extends ContainerItemInventory