Overhaul InvStack to be more efficient, better designed and thoroughly documented. Also, add in sanity checks to IItemHandler wraps so we can fix any potential issues.

This commit is contained in:
aidancbrady committed 2019-03-29 15:22:29 -04:00
1 parent 8c276b6b1a
commit 2e16622b84
6 files changed
+230 -167

No files matched your search

@@ -0,0 +1,49 @@
package mekanism.common.content.transporter;
import mekanism.common.util.InventoryUtils;
import net.minecraft.item.ItemStack;
/**
* A wrapper of an ItemStack which tests equality and hashes based on item type, damage and NBT
* data, ignoring stack size.
*
* @author aidancbrady
*
*/
public class HashedItem {
private final ItemStack itemStack;
private final int hashCode;
public HashedItem(ItemStack stack) {
itemStack = stack;
hashCode = initHashCode();
}
public ItemStack getStack() {
return itemStack;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof HashedItem) {
HashedItem other = (HashedItem) obj;
return InventoryUtils.areItemsStackable(itemStack, other.itemStack);
}
return false;
}
@Override
public int hashCode() {
return hashCode;
}
private int initHashCode() {
int code = 1;
code = 31 * code + itemStack.getItem().hashCode();
if (itemStack.hasTagCompound())
code = 31 * code + itemStack.getTagCompound().hashCode();
code = 31 * code + itemStack.getItemDamage();
return code;
}
}
@@ -1,8 +1,8 @@
package mekanism.common.content.transporter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import mekanism.common.Mekanism;
import mekanism.common.util.InventoryUtils;
import mekanism.common.util.StackUtils;
import net.minecraft.item.ItemStack;
@@ -10,78 +10,111 @@ import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.items.IItemHandler;
/**
* An InvStack attaches to an inventory and tracks a specific homogenous item in a variable amount
* of slots. An InvStack can either track the entirety of these slots or portions of their contents.
* Utility methods in this class allow for the strategic removal of clustered items from
* inventories.
*
* @author aidancbrady
*
*/
public final class InvStack {
public TileEntity tileEntity;
public ArrayList<ItemStack> itemStacks;
public ArrayList<Integer> slotIDs;
/** The TileEntity owning the container this InvStack belongs to. */
private TileEntity tileEntity;
/**
* A map associating the slot IDs in consideration to the amount of items in those slots we care
* about. Note that the associated item counts may not be the full count of items in the actual
* inventory slots.
*/
private Map<Integer, Integer> itemMap = new HashMap<>();
/** The item type of this InvStack. Will be null until we have an insertion via appendStack. */
private HashedItem itemType;
/** The total amount of items tracked by this InvStack. */
private int itemCount;
/** The side of the inventory we are accessing with this InvStack. */
public EnumFacing side;
public InvStack(TileEntity inv, EnumFacing facing) {
tileEntity = inv;
itemStacks = new ArrayList<>();
slotIDs = new ArrayList<>();
side = facing;
}
public InvStack(TileEntity inv, int slotID, ItemStack stack, EnumFacing facing) {
this(inv, stack, getMap(slotID, stack), facing);
}
public InvStack(TileEntity inv, ItemStack stack, Map<Integer, Integer> idMap, EnumFacing facing) {
tileEntity = inv;
itemStacks = new ArrayList<>();
slotIDs = new ArrayList<>();
side = facing;
for(Map.Entry<Integer, Integer> entry : idMap.entrySet()) {
appendStack(entry.getKey(), StackUtils.size(stack, entry.getValue()));
}
itemMap = idMap;
}
/**
* Gets an ItemStack of the defined type and total item count tracked by this InvStack.
*
* @return the total ItemStack contents of this InvStack
*/
public ItemStack getStack() {
int size = 0;
for (ItemStack stack : itemStacks) {
size += stack.getCount();
if (itemType == null || itemCount == 0) {
return ItemStack.EMPTY;
}
if (!itemStacks.isEmpty()) {
ItemStack ret = itemStacks.get(0).copy();
ret.setCount(size);
return ret;
}
return ItemStack.EMPTY;
return StackUtils.size(itemType.getStack(), itemCount);
}
/**
* Appends a slot ID and specified ItemStack count to the tracked map of this InvStack.
*
* @param id - slot ID of items to track
* @param stack - an ItemStack representing the count of items to track in the given slot ID
*/
public void appendStack(int id, ItemStack stack) {
slotIDs.add(id);
itemStacks.add(stack);
if (itemType == null) {
itemType = new HashedItem(stack);
}
itemMap.put(id, stack.getCount());
itemCount += stack.getCount();
}
/**
* Removes a specified amount of items from the parent inventory.
*
* @param amount - the amount of items to remove
*/
public void use(int amount) {
if (InventoryUtils.isItemHandler(tileEntity, side)) {
IItemHandler handler = InventoryUtils.getItemHandler(tileEntity, side);
if (!InventoryUtils.isItemHandler(tileEntity, side)) {
Mekanism.logger
.warn("An InvStack was wrapped around a non-IItemHandler inventory. This should not happen!");
return;
}
for (int i = 0; i < slotIDs.size(); i++) {
ItemStack stack = itemStacks.get(i);
int toUse = Math.min(amount, stack.getCount());
handler.extractItem(slotIDs.get(i), toUse, false);
amount -= toUse;
IItemHandler handler = InventoryUtils.getItemHandler(tileEntity, side);
if (amount == 0) {
return;
}
for (Map.Entry<Integer, Integer> entry : itemMap.entrySet()) {
int toUse = Math.min(amount, entry.getValue());
handler.extractItem(entry.getKey(), toUse, false);
amount -= toUse;
if (amount == 0) {
return;
}
}
}
/**
* Removes all the items being tracked by this InvStack.
*/
public void use() {
use(getStack().getCount());
}
private static Map<Integer, Integer> getMap(int slotID, ItemStack stack) {
Map<Integer, Integer> map = new HashMap<>();
map.put(slotID, stack.getCount());
@@ -1,5 +1,6 @@
package mekanism.common.content.transporter;
import mekanism.common.Mekanism;
import mekanism.common.util.InventoryUtils;
import mekanism.common.util.StackUtils;
import net.minecraft.item.ItemStack;
@@ -23,15 +24,19 @@ public class StackSearcher {
}
public InvStack takeTopStack(Finder id) {
if (InventoryUtils.isItemHandler(tileEntity, side.getOpposite())) {
IItemHandler inventory = InventoryUtils.getItemHandler(tileEntity, side.getOpposite());
if (!InventoryUtils.isItemHandler(tileEntity, side.getOpposite())) {
Mekanism.logger
.warn("A StackSearcher was wrapped around a non-IItemHandler inventory. This should not happen!");
return null;
}
IItemHandler inventory = InventoryUtils.getItemHandler(tileEntity, side.getOpposite());
for (i = i - 1; i >= 0; i--) {
ItemStack stack = inventory.extractItem(i, 64, true);
for (i = i - 1; i >= 0; i--) {
ItemStack stack = inventory.extractItem(i, 64, true);
if (!stack.isEmpty() && id.modifies(stack)) {
return new InvStack(tileEntity, i, stack, side.getOpposite());
}
if (!stack.isEmpty() && id.modifies(stack)) {
return new InvStack(tileEntity, i, stack, side.getOpposite());
}
}
@@ -40,27 +45,31 @@ public class StackSearcher {
public InvStack takeDefinedItem(ItemStack type, int min, int max) {
InvStack ret = new InvStack(tileEntity, side.getOpposite());
if (!InventoryUtils.isItemHandler(tileEntity, side.getOpposite())) {
Mekanism.logger
.warn("A StackSearcher was wrapped around a non-IItemHandler inventory. This should not happen!");
return null;
}
if (InventoryUtils.isItemHandler(tileEntity, side.getOpposite())) {
IItemHandler inventory = InventoryUtils.getItemHandler(tileEntity, side.getOpposite());
IItemHandler inventory = InventoryUtils.getItemHandler(tileEntity, side.getOpposite());
for (i = i - 1; i >= 0; i--) {
ItemStack stack = inventory.extractItem(i, max, true);
for (i = i - 1; i >= 0; i--) {
ItemStack stack = inventory.extractItem(i, max, true);
if (!stack.isEmpty() && StackUtils.equalsWildcard(stack, type)) {
int current = !ret.getStack().isEmpty() ? ret.getStack().getCount() : 0;
if (!stack.isEmpty() && StackUtils.equalsWildcard(stack, type)) {
int current = !ret.getStack().isEmpty() ? ret.getStack().getCount() : 0;
if (current + stack.getCount() <= max) {
ret.appendStack(i, stack.copy());
} else {
ItemStack copy = stack.copy();
copy.setCount(max - current);
ret.appendStack(i, copy);
}
if (current + stack.getCount() <= max) {
ret.appendStack(i, stack.copy());
} else {
ItemStack copy = stack.copy();
copy.setCount(max - current);
ret.appendStack(i, copy);
}
if (!ret.getStack().isEmpty() && ret.getStack().getCount() == max) {
return ret;
}
if (!ret.getStack().isEmpty() && ret.getStack().getCount() == max) {
return ret;
}
}
}
@@ -2,6 +2,8 @@ package mekanism.common.content.transporter;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.tuple.Pair;
import mekanism.common.Mekanism;
import mekanism.common.content.transporter.Finder.FirstFinder;
import mekanism.common.util.InventoryUtils;
import mekanism.common.util.StackUtils;
@@ -9,7 +11,6 @@ import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.items.IItemHandler;
import org.apache.commons.lang3.tuple.Pair;
public class TransitRequest {
@@ -38,41 +39,45 @@ public class TransitRequest {
* side. The algorithm will use the specified Finder to ensure the resulting map will only capture
* desired items. The amount of each item type present in the resulting item type will cap at the
* given 'amount' parameter.
*
* @param side - the side from an adjacent connected inventory, *not* the inventory itself.
*/
public static TransitRequest buildInventoryMap(TileEntity tile, EnumFacing side, int amount, Finder finder) {
TransitRequest ret = new TransitRequest();
// so we can keep track of how many of each item type we have in this inventory mapping
Map<HashedItem, Integer> itemCountMap = new HashMap<>();
if (InventoryUtils.isItemHandler(tile, side.getOpposite())) {
IItemHandler inventory = InventoryUtils.getItemHandler(tile, side.getOpposite());
if (!InventoryUtils.isItemHandler(tile, side.getOpposite())) {
Mekanism.logger.warn(
"A TransitRequest was built with a non-IItemHandler origin inventory. This should not happen!");
return ret;
}
// count backwards- we start from the bottom of the inventory and go back for consistency
for (int i = inventory.getSlots() - 1; i >= 0; i--) {
ItemStack stack = inventory.extractItem(i, amount, true);
IItemHandler inventory = InventoryUtils.getItemHandler(tile, side.getOpposite());
if (!stack.isEmpty() && finder.modifies(stack)) {
HashedItem hashed = new HashedItem(stack);
int currentCount = itemCountMap.getOrDefault(hashed, -1);
int toUse = currentCount != -1
? Math.min(stack.getCount(), amount - currentCount)
: stack.getCount();
if (toUse == 0)
continue; // continue if we don't need anymore of this item type
ret.addItem(StackUtils.size(stack, toUse), i);
// count backwards- we start from the bottom of the inventory and go back for consistency
for (int i = inventory.getSlots() - 1; i >= 0; i--) {
ItemStack stack = inventory.extractItem(i, amount, true);
if (currentCount != -1) {
itemCountMap.put(hashed, currentCount + toUse);
} else {
itemCountMap.put(hashed, toUse);
}
if (!stack.isEmpty() && finder.modifies(stack)) {
HashedItem hashed = new HashedItem(stack);
int currentCount = itemCountMap.getOrDefault(hashed, -1);
int toUse = currentCount != -1 ? Math.min(stack.getCount(), amount - currentCount) : stack.getCount();
if (toUse == 0)
continue; // continue if we don't need anymore of this item type
ret.addItem(StackUtils.size(stack, toUse), i);
if (currentCount != -1) {
itemCountMap.put(hashed, currentCount + toUse);
} else {
itemCountMap.put(hashed, toUse);
}
}
}
return ret;
}
public Map<HashedItem, Pair<Integer, Map<Integer, Integer>>> getItemMap() {
return itemMap;
}
@@ -157,49 +162,4 @@ public class TransitRequest {
return new InvStack(tile, toSend, idMap, side);
}
}
/**
* A wrapper of an ItemStack which tests equality and hashes based on item type, damage and NBT
* data, ignoring stack size.
*
* @author aidancbrady
*
*/
public static class HashedItem {
private final ItemStack itemStack;
private final int hashCode;
public HashedItem(ItemStack stack) {
itemStack = stack;
hashCode = initHashCode();
}
public ItemStack getStack() {
return itemStack;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof HashedItem) {
HashedItem other = (HashedItem) obj;
return InventoryUtils.areItemsStackable(itemStack, other.itemStack);
}
return false;
}
@Override
public int hashCode() {
return hashCode;
}
private int initHashCode() {
int code = 1;
code = 31 * code + itemStack.getItem().hashCode();
if (itemStack.hasTagCompound())
code = 31 * code + itemStack.getTagCompound().hashCode();
code = 31 * code + itemStack.getItemDamage();
return code;
}
}
}
@@ -11,7 +11,6 @@ import mekanism.api.Coord4D;
import mekanism.api.EnumColor;
import mekanism.common.Mekanism;
import mekanism.common.base.ISideConfiguration;
import mekanism.common.content.transporter.TransitRequest.HashedItem;
import mekanism.common.content.transporter.TransitRequest.TransitResponse;
import mekanism.common.content.transporter.TransporterStack.Path;
import mekanism.common.util.InventoryUtils;
@@ -1,11 +1,13 @@
package mekanism.common.util;
import java.util.Map;
import org.apache.commons.lang3.tuple.Pair;
import mekanism.api.EnumColor;
import mekanism.common.Mekanism;
import mekanism.common.base.ISideConfiguration;
import mekanism.common.content.transporter.HashedItem;
import mekanism.common.content.transporter.InvStack;
import mekanism.common.content.transporter.TransitRequest;
import mekanism.common.content.transporter.TransitRequest.HashedItem;
import mekanism.common.content.transporter.TransitRequest.TransitResponse;
import mekanism.common.content.transporter.TransporterManager;
import mekanism.common.tile.TileEntityLogisticalSorter;
@@ -14,7 +16,6 @@ import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import org.apache.commons.lang3.tuple.Pair;
public final class InventoryUtils {
@@ -40,20 +41,24 @@ public final class InventoryUtils {
.entrySet()) {
ItemStack origInsert = StackUtils.size(requestEntry.getKey().getStack(), requestEntry.getValue().getLeft());
ItemStack toInsert = origInsert.copy();
if (!isItemHandler(tile, side.getOpposite())) {
Mekanism.logger
.warn("A transporter attempted to place an item in a non-IItemHandler inventory. This should not happen!");
return TransitResponse.EMPTY;
}
if (isItemHandler(tile, side.getOpposite())) {
IItemHandler inventory = getItemHandler(tile, side.getOpposite());
IItemHandler inventory = getItemHandler(tile, side.getOpposite());
for (int i = 0; i < inventory.getSlots(); i++) {
// Check validation
if (inventory.isItemValid(i, toInsert)) {
// Do insert
toInsert = inventory.insertItem(i, toInsert, false);
for (int i = 0; i < inventory.getSlots(); i++) {
// Check validation
if (inventory.isItemValid(i, toInsert)) {
// Do insert
toInsert = inventory.insertItem(i, toInsert, false);
// If empty, end
if (toInsert.isEmpty()) {
return new TransitResponse(origInsert, requestEntry.getValue().getRight());
}
// If empty, end
if (toInsert.isEmpty()) {
return new TransitResponse(origInsert, requestEntry.getValue().getRight());
}
}
}
@@ -77,27 +82,31 @@ public final class InventoryUtils {
public static InvStack takeDefinedItem(TileEntity tile, EnumFacing side, ItemStack type, int min, int max) {
InvStack ret = new InvStack(tile, side.getOpposite());
if (!isItemHandler(tile, side.getOpposite())) {
Mekanism.logger
.warn("A defined item pull was attempted from a non-IItemHandler inventory. This should not happen!");
return null;
}
if (isItemHandler(tile, side.getOpposite())) {
IItemHandler inventory = getItemHandler(tile, side.getOpposite());
IItemHandler inventory = getItemHandler(tile, side.getOpposite());
for (int i = inventory.getSlots() - 1; i >= 0; i--) {
ItemStack stack = inventory.extractItem(i, max, true);
for (int i = inventory.getSlots() - 1; i >= 0; i--) {
ItemStack stack = inventory.extractItem(i, max, true);
if (!stack.isEmpty() && StackUtils.equalsWildcard(stack, type)) {
int current = !ret.getStack().isEmpty() ? ret.getStack().getCount() : 0;
if (!stack.isEmpty() && StackUtils.equalsWildcard(stack, type)) {
int current = !ret.getStack().isEmpty() ? ret.getStack().getCount() : 0;
if (current + stack.getCount() <= max) {
ret.appendStack(i, stack.copy());
} else {
ItemStack copy = stack.copy();
copy.setCount(max - current);
ret.appendStack(i, copy);
}
if (current + stack.getCount() <= max) {
ret.appendStack(i, stack.copy());
} else {
ItemStack copy = stack.copy();
copy.setCount(max - current);
ret.appendStack(i, copy);
}
if (!ret.getStack().isEmpty() && ret.getStack().getCount() == max) {
return ret;
}
if (!ret.getStack().isEmpty() && ret.getStack().getCount() == max) {
return ret;
}
}
}
@@ -125,19 +134,23 @@ public final class InventoryUtils {
return false;
}
}
if (!isItemHandler(tileEntity, side.getOpposite())) {
Mekanism.logger
.warn("A transporter attempted to place an item in a non-IItemHandler inventory. This should not happen!");
return false;
}
if (isItemHandler(tileEntity, side.getOpposite())) {
IItemHandler inventory = getItemHandler(tileEntity, side.getOpposite());
IItemHandler inventory = getItemHandler(tileEntity, side.getOpposite());
for (int i = 0; i < inventory.getSlots(); i++) {
// Check validation
if (inventory.isItemValid(i, itemStack)) {
// Simulate insert
ItemStack rejects = inventory.insertItem(i, itemStack, true);
for (int i = 0; i < inventory.getSlots(); i++) {
// Check validation
if (inventory.isItemValid(i, itemStack)) {
// Simulate insert
ItemStack rejects = inventory.insertItem(i, itemStack, true);
if (TransporterManager.didEmit(itemStack, rejects)) {
return true;
}
if (TransporterManager.didEmit(itemStack, rejects)) {
return true;
}
}
}