Attempt to fix issues with structure inventories.

Also cleaned up the Hatch pipe/inventory interaction code, modernizing it and removing duplicate code.
This involved adding my AdjecentInventoryCache and AdjecentTileCache code from Railcraft for greatly improved performance.
ISpecialInventory is now 100% unused.
This commit is contained in:
CovertJaguar committed 2014-12-16 03:09:15 -08:00
1 parent c7d88d73d3
commit 89c3fb8bdf
17 files changed
+535 -239

No files matched your search

@@ -26,6 +26,7 @@ import forestry.core.proxy.Proxies;
import java.util.Collection;
import java.util.LinkedList;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.util.ForgeDirection;
@@ -125,7 +126,6 @@ public abstract class TileAlveary extends TileForestry implements IAlvearyCompon
}
/* ITILESTRUCTURE */
@Override
public String getTypeUID() {
return structureLogic.getTypeUID();
@@ -208,7 +208,12 @@ public abstract class TileAlveary extends TileForestry implements IAlvearyCompon
}
@Override
public IInventory getInventory() {
public final IInventory getInventory() {
return getStructureInventory();
}
@Override
public ISidedInventory getStructureInventory() {
return getInternalInventory();
}
@@ -134,9 +134,8 @@ public class TileAlvearyHygroregulator extends TileAlveary implements IInventory
TileInventoryAdapter canInventory = getInternalInventory();
// Check if we have suitable items waiting in the item slot
if (canInventory.getStackInSlot(0) != null) {
if (canInventory.getStackInSlot(0) != null)
FluidHelper.drainContainers(tankManager, canInventory, 0);
}
}
@@ -179,11 +178,6 @@ public class TileAlvearyHygroregulator extends TileAlveary implements IInventory
return BlockAlveary.ALVEARY_HYGRO;
}
@Override
public IInventory getInventory() {
return getInternalInventory();
}
/* IINVENTORY */
@Override
public int getSizeInventory() {
@@ -22,14 +22,12 @@ import forestry.api.core.EnumHumidity;
import forestry.api.core.EnumTemperature;
import forestry.api.core.ForestryAPI;
import forestry.api.core.IErrorState;
import forestry.api.core.ISpecialInventory;
import forestry.api.core.ITileStructure;
import forestry.api.genetics.IIndividual;
import forestry.apiculture.gui.ContainerAlveary;
import forestry.core.EnumErrorCode;
import forestry.core.config.Config;
import forestry.core.config.Defaults;
import forestry.core.config.ForestryItem;
import forestry.core.interfaces.IClimatised;
import forestry.core.interfaces.IErrorSource;
import forestry.core.interfaces.IHintSource;
@@ -50,9 +48,8 @@ import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraftforge.common.util.ForgeDirection;
public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, ISpecialInventory, IBeeHousing, IClimatised, IHintSource {
public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IBeeHousing, IClimatised, IHintSource {
// / CONSTANTS
public static final int SLOT_QUEEN = 0;
@@ -144,7 +141,7 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IS
// Add swarm effects
if (worldObj.getTotalWorldTime() % 200 * 10 == 0)
onQueenChange(getInternalInventory().getStackInSlot(SLOT_QUEEN));
onQueenChange(getStructureInventory().getStackInSlot(SLOT_QUEEN));
if (getErrorState() == EnumErrorCode.OK)
queen.doFX(beekeepingLogic.getEffectData(), this);
@@ -169,13 +166,13 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IS
if (!isMaster())
return;
if (getInternalInventory() == null)
if (getStructureInventory() == null)
return;
// / Multiplayer FX
if (PluginApiculture.beeInterface.isMated(getInternalInventory().getStackInSlot(SLOT_QUEEN)))
if (PluginApiculture.beeInterface.isMated(getStructureInventory().getStackInSlot(SLOT_QUEEN)))
if (getErrorState() == EnumErrorCode.OK && worldObj.getTotalWorldTime() % 2 == 0) {
IBee displayQueen = PluginApiculture.beeInterface.getMember(getInternalInventory().getStackInSlot(SLOT_QUEEN));
IBee displayQueen = PluginApiculture.beeInterface.getMember(getStructureInventory().getStackInSlot(SLOT_QUEEN));
displayQueen.doFX(beekeepingLogic.getEffectData(), this);
}
}
@@ -200,7 +197,7 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IS
/* STATE INFORMATION */
private int getHealthDisplay() {
IInventory inventory = getInternalInventory();
IInventory inventory = getStructureInventory();
if (inventory == null || inventory.getStackInSlot(SLOT_QUEEN) == null)
return 0;
@@ -213,7 +210,7 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IS
}
private int getMaxHealthDisplay() {
IInventory inventory = getInternalInventory();
IInventory inventory = getStructureInventory();
if (inventory == null || inventory.getStackInSlot(SLOT_QUEEN) == null)
return 0;
@@ -431,7 +428,7 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IS
@Override
public boolean addProduct(ItemStack product, boolean all) {
TileInventoryAdapter inventory = getInternalInventory();
TileInventoryAdapter inventory = getStructureInventory();
if (inventory == null)
return false;
@@ -530,7 +527,8 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IS
}
/* IINVENTORY */
private IInventory getStructureInventory() {
@Override
public TileInventoryAdapter getStructureInventory() {
TileInventoryAdapter inventory = getInternalInventory();
if (inventory != null) {
if (isMaster() || !Proxies.common.isSimulating(worldObj))
@@ -538,9 +536,8 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IS
} else if (hasMaster()) {
ITileStructure central = getCentralTE();
if (central != null)
return central.getInventory();
return (TileInventoryAdapter) central.getInventory();
}
return null;
}
@@ -582,12 +579,13 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IS
@Override
public void setInventorySlotContents(int slotIndex, ItemStack itemstack) {
TileInventoryAdapter inventory = getInternalInventory();
// Client side handling for container synch
if (inventory == null && !Proxies.common.isSimulating(worldObj))
createInventory();
IInventory inv = getStructureInventory();
// Client side handling for container synch
if (inv == null && !Proxies.common.isSimulating(worldObj)) {
createInventory();
inv = getInternalInventory();
}
if (inv != null)
inv.setInventorySlotContents(slotIndex, itemstack);
}
@@ -626,7 +624,7 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IS
@Override
public boolean isItemValidForSlot(int slotIndex, ItemStack itemstack) {
TileInventoryAdapter inventory = getInternalInventory();
ISidedInventory inventory = getStructureInventory();
if (inventory == null)
return false;
@@ -646,7 +644,7 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IS
@Override
public boolean canExtractItem(int slotIndex, ItemStack itemstack, int side) {
TileInventoryAdapter inventory = getInternalInventory();
ISidedInventory inventory = getStructureInventory();
if (inventory == null)
return false;
if (!inventory.canExtractItem(slotIndex, itemstack, side))
@@ -657,83 +655,83 @@ public class TileAlvearyPlain extends TileAlveary implements ISidedInventory, IS
@Override
public int[] getAccessibleSlotsFromSide(int side) {
TileInventoryAdapter inventory = getInternalInventory();
ISidedInventory inventory = getStructureInventory();
if (inventory == null)
return Defaults.FACINGS_NONE;
return inventory.getAccessibleSlotsFromSide(side);
}
/* ISPECIALINVENTORY */
@Override
public int addItem(ItemStack stack, boolean doAdd, ForgeDirection from) {
IInventory inv = getStructureInventory();
if (inv == null)
return 0;
// Princesses && Queens
if (ForestryItem.beePrincessGE.isItemEqual(stack) || ForestryItem.beeQueenGE.isItemEqual(stack))
if (inv.getStackInSlot(SLOT_QUEEN) == null) {
if (doAdd) {
inv.setInventorySlotContents(SLOT_QUEEN, stack.copy());
inv.getStackInSlot(SLOT_QUEEN).stackSize = 1;
}
return 1;
}
// Drones
if (ForestryItem.beeDroneGE.isItemEqual(stack)) {
ItemStack droneStack = inv.getStackInSlot(SLOT_DRONE);
if (droneStack == null) {
if (doAdd)
inv.setInventorySlotContents(SLOT_DRONE, stack.copy());
return stack.stackSize;
} else {
if (!droneStack.isItemEqual(stack))
return 0;
if (!ItemStack.areItemStackTagsEqual(droneStack, stack))
return 0;
int space = droneStack.getMaxStackSize() - droneStack.stackSize;
if (space <= 0)
return 0;
int added = space > stack.stackSize ? stack.stackSize : space;
if (doAdd)
droneStack.stackSize += added;
return added;
}
}
return 0;
}
@Override
public ItemStack[] extractItem(boolean doRemove, ForgeDirection from, int maxItemCount) {
IInventory inv = getStructureInventory();
if (inv == null)
return new ItemStack[0];
ItemStack product = null;
for (int i = SLOT_PRODUCT_1; i < inv.getSizeInventory(); i++) {
if (inv.getStackInSlot(i) == null)
continue;
ItemStack stack = inv.getStackInSlot(i);
if (doRemove)
product = inv.decrStackSize(i, 1);
else {
product = stack.copy();
product.stackSize = 1;
}
break;
}
return new ItemStack[]{product};
}
// @Override
// public int addItem(ItemStack stack, boolean doAdd, ForgeDirection from) {
//
// IInventory inv = getStructureInventory();
// if (inv == null)
// return 0;
//
// // Princesses && Queens
// if (ForestryItem.beePrincessGE.isItemEqual(stack) || ForestryItem.beeQueenGE.isItemEqual(stack))
// if (inv.getStackInSlot(SLOT_QUEEN) == null) {
// if (doAdd) {
// inv.setInventorySlotContents(SLOT_QUEEN, stack.copy());
// inv.getStackInSlot(SLOT_QUEEN).stackSize = 1;
// }
// return 1;
// }
//
// // Drones
// if (ForestryItem.beeDroneGE.isItemEqual(stack)) {
//
// ItemStack droneStack = inv.getStackInSlot(SLOT_DRONE);
// if (droneStack == null) {
// if (doAdd)
// inv.setInventorySlotContents(SLOT_DRONE, stack.copy());
// return stack.stackSize;
// } else {
// if (!droneStack.isItemEqual(stack))
// return 0;
// if (!ItemStack.areItemStackTagsEqual(droneStack, stack))
// return 0;
// int space = droneStack.getMaxStackSize() - droneStack.stackSize;
// if (space <= 0)
// return 0;
//
// int added = space > stack.stackSize ? stack.stackSize : space;
// if (doAdd)
// droneStack.stackSize += added;
// return added;
// }
// }
//
// return 0;
// }
//
// @Override
// public ItemStack[] extractItem(boolean doRemove, ForgeDirection from, int maxItemCount) {
//
// IInventory inv = getStructureInventory();
// if (inv == null)
// return new ItemStack[0];
//
// ItemStack product = null;
//
// for (int i = SLOT_PRODUCT_1; i < inv.getSizeInventory(); i++) {
// if (inv.getStackInSlot(i) == null)
// continue;
//
// ItemStack stack = inv.getStackInSlot(i);
//
// if (doRemove)
// product = inv.decrStackSize(i, 1);
// else {
// product = stack.copy();
// product.stackSize = 1;
// }
// break;
// }
//
// return new ItemStack[]{product};
// }
/* SMP GUI */
public void getGUINetworkData(int i, int j) {
@@ -53,6 +53,7 @@ public class TileAlvearyStabiliser extends TileAlveary implements IBeeModifier {
}
/* TEXTURES */
@Override
public int getIcon(int side, int metadata) {
if(side == 0 || side == 1)
return BlockAlveary.BOTTOM;
@@ -32,7 +32,6 @@ import forestry.plugins.PluginApiculture;
import java.util.Map.Entry;
import java.util.Stack;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
@@ -219,11 +218,6 @@ public class TileAlvearySwarmer extends TileAlveary implements ISidedInventory {
setInternalInventory(new TileInventoryAdapter(this, 4, "SwarmInv"));
}
@Override
public IInventory getInventory() {
return getInternalInventory();
}
/* IINVENTORY */
@Override
public int getSizeInventory() {
@@ -130,6 +130,7 @@ public class BlockSapling extends BlockTreeContainer {
@Override
public void onNeighborBlockChange(World world, int x, int y, int z, Block neighbour) {
super.onNeighborBlockChange(world, x, y, z, neighbour);
if (Proxies.common.isSimulating(world) && !this.canBlockStay(world, x, y, z)) {
dropAsSapling(world, x, y, z);
world.setBlockToAir(x, y, z);
@@ -22,6 +22,7 @@ import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import org.apache.logging.log4j.Level;
public abstract class BlockForestry extends BlockContainer {
@@ -65,4 +66,17 @@ public abstract class BlockForestry extends BlockContainer {
if (entityliving instanceof EntityPlayer)
tile.setOwner(((EntityPlayer) entityliving));
}
@Override
public void onNeighborBlockChange(World world, int x, int y, int z, Block block) {
try {
TileEntity tile = world.getTileEntity(x, y, z);
if (tile instanceof TileForestry)
((TileForestry) tile).onNeighborBlockChange(block);
} catch (StackOverflowError error) {
Proxies.log.logThrowable(Level.ERROR, "Stack Overflow Error in BlockMachine.onNeighborBlockChange()", 10, error);
throw error;
}
}
}
@@ -87,7 +87,7 @@ public abstract class BlockStructure extends BlockForestry {
@Override
public void onNeighborBlockChange(World world, int x, int y, int z, Block neighbor) {
super.onNeighborBlockChange(world, x, y, z, neighbor);
if (!Proxies.common.isSimulating(world))
return;
@@ -27,10 +27,12 @@ import forestry.core.network.INetworkedEntity;
import forestry.core.network.PacketPayload;
import forestry.core.network.PacketTileUpdate;
import forestry.core.proxy.Proxies;
import forestry.core.utils.AdjacentTileCache;
import forestry.core.utils.EnumAccess;
import forestry.core.utils.PlayerUtil;
import forestry.core.utils.Vect;
import java.util.Collection;
import net.minecraft.block.Block;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
@@ -45,9 +47,30 @@ import net.minecraftforge.common.util.ForgeDirection;
@Optional.Interface(iface = "buildcraft.api.statements.ITriggerProvider", modid = "BuildCraftAPI|statements")
public abstract class TileForestry extends TileEntity implements INetworkedEntity, IOwnable, IErrorSource, ITriggerProvider {
protected final AdjacentTileCache tileCache = new AdjacentTileCache(this);
protected boolean isInited = false;
private TileInventoryAdapter inventory;
public AdjacentTileCache getTileCache() {
return tileCache;
}
public void onNeighborBlockChange(Block id) {
tileCache.onNeighborChange();
}
@Override
public void invalidate() {
tileCache.purge();
super.invalidate();
}
@Override
public void validate() {
tileCache.purge();
super.validate();
}
public Vect Coords() {
return new Vect(xCoord, yCoord, zCoord);
}
@@ -0,0 +1,84 @@
/*******************************************************************************
* 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.inventory;
import forestry.core.utils.AdjacentTileCache;
import java.util.*;
import net.minecraft.inventory.IInventory;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.util.ForgeDirection;
/**
*
* @author CovertJaguar <http://www.railcraft.info/>
*/
public final class AdjacentInventoryCache implements AdjacentTileCache.ICacheListener {
private final AdjacentTileCache cache;
private boolean changed = true;
private final List<IInventory> invs = new LinkedList<IInventory>();
private final IInventory[] sides = new IInventory[6];
private final Comparator<IInventory> sorter;
private final ITileFilter filter;
public AdjacentInventoryCache(TileEntity tile, AdjacentTileCache cache) {
this(tile, cache, null, null);
}
public AdjacentInventoryCache(TileEntity tile, AdjacentTileCache cache, ITileFilter filter, Comparator<IInventory> sorter) {
this.cache = cache;
this.filter = filter;
this.sorter = sorter;
cache.addListener(this);
}
public IInventory getAdjecentInventory(ForgeDirection side) {
checkChanged();
return sides[side.ordinal()];
}
public Collection<IInventory> getAdjecentInventories() {
checkChanged();
return invs;
}
@Override
public void changed() {
changed = true;
}
@Override
public void purge() {
invs.clear();
Arrays.fill(sides, null);
}
private void checkChanged() {
cache.refresh();
if (changed) {
changed = false;
purge();
for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) {
TileEntity tile = cache.getTileOnSide(side);
if (tile != null && (filter == null || filter.matches(tile))) {
IInventory inv = InvTools.getInventoryFromTile(tile, side.getOpposite());
if (inv != null) {
sides[side.ordinal()] = inv;
invs.add(inv);
}
}
}
if (sorter != null)
Collections.sort(invs, sorter);
}
}
}
@@ -10,8 +10,8 @@
******************************************************************************/
package forestry.core.inventory;
import buildcraft.api.transport.IPipeTile;
import buildcraft.api.transport.PipeManager;
import forestry.api.core.ISpecialInventory;
import forestry.core.inventory.filters.ArrayStackFilter;
import forestry.core.inventory.filters.IStackFilter;
import forestry.core.inventory.filters.InvertedStackFilter;
@@ -19,9 +19,11 @@ import forestry.core.inventory.filters.StackFilter;
import forestry.core.inventory.manipulators.InventoryManipulator;
import forestry.core.inventory.wrappers.ChestWrapper;
import forestry.core.inventory.wrappers.IInvSlot;
import forestry.core.inventory.wrappers.InventoryCopy;
import forestry.core.inventory.wrappers.InventoryIterator;
import forestry.core.inventory.wrappers.InventoryMapper;
import forestry.core.inventory.wrappers.SidedInventoryMapper;
import forestry.core.utils.AdjacentTileCache;
import forestry.core.utils.PlainInventory;
import java.util.ArrayList;
import java.util.Collection;
@@ -46,9 +48,9 @@ import net.minecraftforge.oredict.OreDictionary;
public abstract class InvTools {
/*private static final String TAG_ID = "id";
private static final String TAG_SIZE = "stackSize";
private static final String TAG_DAMAGE = "Damage";
private static final String TAG_COUNT = "Count";*/
private static final String TAG_SIZE = "stackSize";
private static final String TAG_DAMAGE = "Damage";
private static final String TAG_COUNT = "Count";*/
private static final String TAG_SLOT = "Slot";
public static int getXOnSide(int x, ForgeDirection side) {
@@ -168,15 +170,14 @@ public abstract class InvTools {
}
/*public static void addItemToolTip(ItemStack stack, String tag, String msg) {
NBTTagCompound nbt = getItemData(stack);
NBTTagCompound display = nbt.getCompoundTag("display");
nbt.setTag("display", display);
NBTTagList lore = display.getTagList("Lore", 8); // 8 = String
display.setTag("Lore", lore);
//lore.appendTag(new NBTTagString(tag, msg));
lore.appendTag(new NBTTagString(msg));
}*/
NBTTagCompound nbt = getItemData(stack);
NBTTagCompound display = nbt.getCompoundTag("display");
nbt.setTag("display", display);
NBTTagList lore = display.getTagList("Lore", 8); // 8 = String
display.setTag("Lore", lore);
//lore.appendTag(new NBTTagString(tag, msg));
lore.appendTag(new NBTTagString(msg));
}*/
public static NBTTagCompound getItemData(ItemStack stack) {
NBTTagCompound nbt = stack.getTagCompound();
if (nbt == null) {
@@ -321,7 +322,7 @@ public abstract class InvTools {
return count;
}
public static int countItems(Collection<IInventory> inventories, ItemStack... filter) {
public static int countItems(Iterable<IInventory> inventories, ItemStack... filter) {
int count = 0;
for (IInventory inv : inventories) {
count += InvTools.countItems(inv, filter);
@@ -409,7 +410,7 @@ public abstract class InvTools {
* @param filters
* @return
*/
public static ItemStack moveOneItem(Collection<IInventory> sources, IInventory dest, ItemStack... filters) {
public static ItemStack moveOneItem(Iterable<IInventory> sources, IInventory dest, ItemStack... filters) {
for (IInventory inv : sources) {
ItemStack moved = InvTools.moveOneItem(inv, dest, filters);
if (moved != null)
@@ -426,7 +427,7 @@ public abstract class InvTools {
* @param filter
* @return
*/
public static ItemStack moveOneItem(Collection<IInventory> sources, IInventory dest, IStackFilter filter) {
public static ItemStack moveOneItem(Iterable<IInventory> sources, IInventory dest, IStackFilter filter) {
for (IInventory inv : sources) {
ItemStack moved = InvTools.moveOneItem(inv, dest, filter);
if (moved != null)
@@ -443,7 +444,7 @@ public abstract class InvTools {
* @param filters
* @return
*/
public static ItemStack moveOneItem(IInventory source, Collection<IInventory> destinations, ItemStack... filters) {
public static ItemStack moveOneItem(IInventory source, Iterable<IInventory> destinations, ItemStack... filters) {
for (IInventory dest : destinations) {
ItemStack moved = InvTools.moveOneItem(source, dest, filters);
if (moved != null)
@@ -474,7 +475,7 @@ public abstract class InvTools {
* @param filters
* @return
*/
public static ItemStack moveOneItemExcept(Collection<IInventory> sources, IInventory dest, ItemStack... filters) {
public static ItemStack moveOneItemExcept(Iterable<IInventory> sources, IInventory dest, ItemStack... filters) {
for (IInventory inv : sources) {
ItemStack moved = InvTools.moveOneItemExcept(inv, dest, filters);
if (moved != null)
@@ -491,7 +492,7 @@ public abstract class InvTools {
* @param filters
* @return
*/
public static ItemStack moveOneItemExcept(IInventory source, Collection<IInventory> destinations, ItemStack... filters) {
public static ItemStack moveOneItemExcept(IInventory source, Iterable<IInventory> destinations, ItemStack... filters) {
for (IInventory dest : destinations) {
ItemStack moved = InvTools.moveOneItemExcept(source, dest, filters);
if (moved != null)
@@ -650,6 +651,41 @@ public abstract class InvTools {
return im.addStack(stack);
}
/**
* Attempts to move an ItemStack from one inventory to another.
*
* @param source The source IInventory.
* @param dest The destination IInventory.
* @return true if any items were moved
*/
public static boolean moveItemStack(IInventory source, IInventory dest) {
InventoryManipulator im = InventoryManipulator.get(dest);
for (IInvSlot slot : InventoryIterator.getIterable(source)) {
ItemStack stack = slot.getStackInSlot();
if (stack != null) {
ItemStack remainder = im.addStack(stack);
slot.setStackInSlot(remainder);
return !isItemEqualStrict(stack, remainder);
}
}
return false;
}
/**
* Attempts to move an ItemStack from one inventory to another.
*
* @param source The source IInventory.
* @param destinations The destination IInventory.
* @return true if any items were moved
*/
public static boolean moveItemStack(IInventory source, Iterable<IInventory> destinations) {
for (IInventory dest : destinations) {
if (moveItemStack(source, dest))
return true;
}
return false;
}
/**
* Checks if there is room for the ItemStack in the inventory.
*
@@ -673,8 +709,6 @@ public abstract class InvTools {
* @return
*/
public static ItemStack[] removeItems(IInventory inv, int numItems) {
if (inv instanceof ISpecialInventory)
return ((ISpecialInventory) inv).extractItem(true, ForgeDirection.UNKNOWN, numItems);
PlainInventory output = new PlainInventory(27, "temp");
for (int i = 0; i < inv.getSizeInventory(); i++) {
if (numItems <= 0)
@@ -743,7 +777,7 @@ public abstract class InvTools {
* @param filter EnumItemType to match against
* @return An ItemStack
*/
public static ItemStack removeOneItem(Collection<IInventory> invs, IStackFilter filter) {
public static ItemStack removeOneItem(Iterable<IInventory> invs, IStackFilter filter) {
for (IInventory inv : invs) {
ItemStack stack = removeOneItem(inv, filter);
if (stack != null)
@@ -752,6 +786,51 @@ public abstract class InvTools {
return null;
}
/**
* Attempts to move a single item from the source inventory into a adjacent Buildcraft pipe.
* If the attempt fails, the source Inventory will not be modified.
*
* @param source The source inventory
* @param tileCache The tile cache of the source block.
* @return true if an item was inserted, otherwise false.
*/
public static boolean moveOneItemToPipe(IInventory source, AdjacentTileCache tileCache) {
IInventory invClone = new InventoryCopy(source);
ItemStack stackToMove = removeOneItem(invClone);
if (stackToMove == null)
return false;
if (stackToMove.stackSize <= 0)
return false;
IPipeTile[] pipes = new IPipeTile[6];
boolean foundPipe = false;
for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) {
TileEntity tile = tileCache.getTileOnSide(side);
if (tile instanceof IPipeTile) {
IPipeTile pipe = (IPipeTile) tile;
if (pipe.getPipeType() == IPipeTile.PipeType.ITEM && pipe.isPipeConnected(side.getOpposite())) {
pipes[side.ordinal()] = pipe;
foundPipe = true;
}
}
}
if (!foundPipe)
return false;
int choice = tileCache.getSource().getWorldObj().rand.nextInt(6);
ForgeDirection side = ForgeDirection.getOrientation(choice);
IPipeTile pipe = pipes[choice];
if (pipe.injectItem(stackToMove, false, side.getOpposite()) > 0)
if (removeOneItem(source, stackToMove) != null) {
pipe.injectItem(stackToMove, true, side.getOpposite());
return true;
}
return false;
}
public static void writeInvToNBT(IInventory inv, String tag, NBTTagCompound data) {
NBTTagList list = new NBTTagList();
for (byte slot = 0; slot < inv.getSizeInventory(); slot++) {
@@ -0,0 +1,134 @@
/*******************************************************************************
* Copyright (c) 2011-2014 SirSengir.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Various Contributors including, but not limited to:
* SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges
******************************************************************************/
package forestry.core.utils;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
import net.minecraft.init.Blocks;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
/**
*
* @author CovertJaguar <http://www.railcraft.info>
*/
public final class AdjacentTileCache {
private static final int DELAY_MIN = 20;
private static final int DELAY_MAX = 2400;
private static final int DELAY_STEP = 2;
private final Timer[] timer = new Timer[6];
private final TileEntity[] cache = new TileEntity[6];
private final int[] delay = new int[6];
private final TileEntity source;
private final Set<ICacheListener> listeners = new LinkedHashSet<ICacheListener>();
public static interface ICacheListener {
void changed();
void purge();
}
public AdjacentTileCache(TileEntity tile) {
this.source = tile;
Arrays.fill(delay, DELAY_MIN);
for (int i = 0; i < timer.length; i++) {
timer[i] = new Timer();
}
}
public void addListener(ICacheListener listener) {
listeners.add(listener);
}
private TileEntity searchSide(ForgeDirection side) {
World world = source.getWorldObj();
int sx = source.xCoord + side.offsetX;
int sy = source.yCoord + side.offsetY;
int sz = source.zCoord + side.offsetZ;
if (world.blockExists(sx, sy, sz) && world.getBlock(sx, sy, sz) != Blocks.air)
return world.getTileEntity(sx, sy, sz);
return null;
}
public void refresh() {
for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) {
getTileOnSide(side);
}
}
public void purge() {
Arrays.fill(cache, null);
Arrays.fill(delay, DELAY_MIN);
for (Timer t : timer) {
t.reset();
}
changed();
for (ICacheListener listener : listeners) {
listener.purge();
}
}
public void onNeighborChange() {
Arrays.fill(delay, DELAY_MIN);
}
protected void setTile(int side, TileEntity tile) {
if (cache[side] != tile) {
cache[side] = tile;
changed();
}
}
private void changed() {
for (ICacheListener listener : listeners) {
listener.changed();
}
}
private boolean areCoordinatesOnSide(ForgeDirection side, TileEntity target) {
return source.xCoord + side.offsetX == target.xCoord && source.yCoord + side.offsetY == target.yCoord && source.zCoord + side.offsetZ == target.zCoord;
}
public TileEntity getTileOnSide(ForgeDirection side) {
int s = side.ordinal();
if (cache[s] != null)
if (cache[s].isInvalid() || !areCoordinatesOnSide(side, cache[s]))
setTile(s, null);
else
return cache[s];
if (timer[s].hasTriggered(source.getWorldObj(), delay[s])) {
setTile(s, searchSide(side));
if (cache[s] == null)
incrementDelay(s);
else
delay[s] = DELAY_MIN;
}
return cache[s];
}
private void incrementDelay(int side) {
delay[side] += DELAY_STEP;
if (delay[side] > DELAY_MAX)
delay[side] = DELAY_MAX;
}
public TileEntity getSource() {
return source;
}
}
@@ -49,10 +49,13 @@ public class BlockUtil {
* @param blockPos
* @param from
* @return
* @deprecated Use AdjacentInventoryCache instead
*/
@Deprecated
public static IInventory[] getAdjacentInventories(World world, Vect blockPos, ForgeDirection from) {
ArrayList<IInventory> inventories = new ArrayList<IInventory>();
// WTF is this? A loop that only picks the opposite direction? -CovertJaguar
for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) {
if (from != ForgeDirection.UNKNOWN && from != dir.getOpposite())
continue;
@@ -88,12 +91,12 @@ public class BlockUtil {
TileEntity pipeEntry = world.getTileEntity((int) posPipe.x, (int) posPipe.y, (int) posPipe.z);
if (pipeEntry instanceof IPipeTile) {
IPipeTile pipe = (IPipeTile)pipeEntry;
IPipeTile pipe = (IPipeTile) pipeEntry;
if (from != ForgeDirection.UNKNOWN && pipeEntry instanceof IPipeConnection) {
if (((IPipeConnection) pipeEntry).overridePipeConnection(PipeType.ITEM, from) != ConnectOverride.DISCONNECT)
possiblePipes.add(dir);
} else if(pipe.getPipeType() == PipeType.ITEM && pipe.isPipeConnected(dir.getOpposite()))
} else if (pipe.getPipeType() == PipeType.ITEM && pipe.isPipeConnected(dir.getOpposite()))
possiblePipes.add(dir);
}
}
@@ -106,9 +109,10 @@ public class BlockUtil {
ArrayList<ForgeDirection> filtered = new ArrayList<ForgeDirection>();
ArrayList<ForgeDirection> excludeList = new ArrayList<ForgeDirection>(Arrays.asList(exclude));
for (ForgeDirection direction : allDirections)
for (ForgeDirection direction : allDirections) {
if (!excludeList.contains(direction))
filtered.add(direction);
}
return filtered;
@@ -137,7 +141,7 @@ public class BlockUtil {
IPipeTile pipe = (IPipeTile) tile.getWorldObj().getTileEntity((int) pipePos.x, (int) pipePos.y, (int) pipePos.z);
ItemStack payload = stack.splitStack(1);
if(pipe.injectItem(payload, true, itemPos.orientation.getOpposite()) > 0)
if (pipe.injectItem(payload, true, itemPos.orientation.getOpposite()) > 0)
return true;
else
pipes.remove(choice);
@@ -0,0 +1,36 @@
/*******************************************************************************
* Copyright (c) 2011-2014 SirSengir.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Various Contributors including, but not limited to:
* SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges
******************************************************************************/
package forestry.core.utils;
import net.minecraft.world.World;
/**
*
* @author CovertJaguar <http://www.railcraft.info>
*/
public class Timer {
private long startTime = Long.MIN_VALUE;
public boolean hasTriggered(World world, int ticks) {
long currentTime = world.getTotalWorldTime();
if (currentTime >= (ticks + startTime) || startTime > currentTime) {
startTime = currentTime;
return true;
}
return false;
}
public void reset() {
startTime = Long.MIN_VALUE;
}
}
@@ -27,6 +27,7 @@ import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
@@ -315,7 +316,12 @@ public abstract class TileFarm extends TileForestry implements IFarmComponent {
}
@Override
public IInventory getInventory() {
public final IInventory getInventory() {
return getStructureInventory();
}
@Override
public ISidedInventory getStructureInventory() {
return getInternalInventory();
}
@@ -13,13 +13,14 @@ package forestry.farming.gadgets;
import buildcraft.api.statements.ITriggerExternal;
import cpw.mods.fml.common.Optional;
import forestry.api.core.ITileStructure;
import forestry.core.utils.BlockUtil;
import forestry.core.utils.StackUtils;
import forestry.core.inventory.AdjacentInventoryCache;
import forestry.core.inventory.ITileFilter;
import forestry.core.inventory.InvTools;
import forestry.core.inventory.TileInventoryAdapter;
import forestry.core.inventory.wrappers.InventoryMapper;
import forestry.core.utils.Utils;
import forestry.farming.triggers.FarmingTriggers;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
@@ -31,6 +32,14 @@ import net.minecraftforge.fluids.FluidContainerRegistry;
public class TileHatch extends TileFarm implements ISidedInventory {
private final AdjacentInventoryCache inventoryCache = new AdjacentInventoryCache(this, getTileCache(), new ITileFilter() {
@Override
public boolean matches(TileEntity tile) {
return !(tile instanceof TileFarm);
}
}, null);
public TileHatch() {
fixedType = TYPE_HATCH;
}
@@ -47,82 +56,30 @@ public class TileHatch extends TileFarm implements ISidedInventory {
}
/* AUTO-EJECTING */
private IInventory getProductInventory() {
return new InventoryMapper(getStructureInventory(), TileFarmPlain.SLOT_PRODUCTION_1, TileFarmPlain.SLOT_COUNT_PRODUCTION);
}
protected void dumpStash() {
if (!hasMaster())
return;
ArrayList<ForgeDirection> pipes = new ArrayList<ForgeDirection>();
ForgeDirection[] tmp = BlockUtil.getPipeDirections(worldObj, Coords(), ForgeDirection.UP);
Collections.addAll(pipes, tmp);
if (pipes.size() > 0)
dumpToPipe(pipes);
else {
IInventory[] inventories = BlockUtil.getAdjacentInventories(worldObj, Coords(), ForgeDirection.UP);
dumpToInventory(inventories);
if (!InvTools.moveOneItemToPipe(getProductInventory(), tileCache)) {
IInventory struct = getStructureInventory();
if (struct != null)
InvTools.moveItemStack(getProductInventory(), inventoryCache.getAdjecentInventories());
}
}
private void dumpToPipe(ArrayList<ForgeDirection> pipes) {
ItemStack[] products = extractItem(true, ForgeDirection.DOWN, 1);
for (ItemStack product : products) {
while (product.stackSize > 0) {
BlockUtil.putFromStackIntoPipe(this, pipes, product);
}
}
}
private void dumpToInventory(IInventory[] inventories) {
ITileStructure central = getCentralTE();
if (central == null)
return;
IInventory inv = central.getInventory();
for (int i = TileFarmPlain.SLOT_PRODUCTION_1; i < TileFarmPlain.SLOT_PRODUCTION_1 + TileFarmPlain.SLOT_COUNT_PRODUCTION; i++) {
if (inv.getStackInSlot(i) == null)
continue;
ItemStack stack = inv.getStackInSlot(i);
if (stack.stackSize <= 0)
continue;
for (IInventory inventory : inventories) {
// Don't dump in arboretums!
if (inventory.getSizeInventory() < 4)
continue;
// Get complete inventory (for double chests)
IInventory completeInventory = Utils.getChest(inventory);
if (completeInventory instanceof ISidedInventory) {
ISidedInventory sidedInventory = (ISidedInventory) completeInventory;
int[] slots = sidedInventory.getAccessibleSlotsFromSide(ForgeDirection.UP.ordinal());
for (int sl = 0; sl < slots.length; ++sl) {
StackUtils.stowInInventory(stack, sidedInventory, true, sl, 1);
}
} else {
StackUtils.stowInInventory(stack, completeInventory, true);
if (stack.stackSize <= 0) {
inv.setInventorySlotContents(i, null);
break;
}
}
}
}
}
/* IINVENTORY */
private ISidedInventory getStructureInventory() {
@Override
public TileInventoryAdapter getStructureInventory() {
if (hasMaster()) {
ITileStructure central = getCentralTE();
if (central != null)
return (ISidedInventory) central.getInventory();
if (central != null){
return (TileInventoryAdapter) central.getInventory();
}
}
return null;
@@ -248,40 +205,6 @@ public class TileHatch extends TileFarm implements ISidedInventory {
return getStructureInventory().getAccessibleSlotsFromSide(side);
}
public ItemStack[] extractItem(boolean doRemove, ForgeDirection from, int maxItemCount) {
IInventory inv;
if (hasMaster()) {
ITileStructure central = getCentralTE();
if (central == null)
return new ItemStack[0];
inv = getCentralTE().getInventory();
} else
return StackUtils.EMPTY_STACK_ARRAY;
ItemStack product = null;
for (int i = TileFarmPlain.SLOT_PRODUCTION_1; i < TileFarmPlain.SLOT_PRODUCTION_1 + TileFarmPlain.SLOT_COUNT_PRODUCTION; i++) {
if (inv.getStackInSlot(i) == null)
continue;
ItemStack stack = inv.getStackInSlot(i);
if (doRemove)
product = inv.decrStackSize(i, 1);
else {
product = stack.copy();
product.stackSize = 1;
}
break;
}
if (product != null)
return new ItemStack[]{product};
else
return StackUtils.EMPTY_STACK_ARRAY;
}
/* ITRIGGERPROVIDER */
@Optional.Method(modid = "BuildCraftAPI|statements")
@Override