Compare commits

...

33 Commits

Author SHA1 Message Date
PrototypeTrousers 7d1c502b41 workss 2022-04-04 15:44:22 -03:00
PrototypeTrousers 63653c1833 added packets for missing items report 2022-04-04 03:55:51 -03:00
PrototypeTrousers 6cadfbdcdc 3 2022-04-01 19:30:18 -03:00
PrototypeTrousers d054c6ab91 2 2022-04-01 19:30:18 -03:00
PrototypeTrousers 234b1c5dc6 meh. crafting gets stuck if the output loops 2022-04-01 19:30:18 -03:00
PrototypeTrousers 8cc29734a2 positive loop support 2022-04-01 19:30:18 -03:00
PrototypeTrousers 1e9e8d2639 more checks if "gregtech" mod is loaded 2022-03-31 21:16:14 -03:00
PrototypeTrousers 19c6e2ff2d support for IC2 damageable items 2022-03-27 08:52:37 -03:00
PrototypeTrousers 4f25c1551b increase internal buffer of ME Chest
Fix item amount not refreshing when inserted/extracted
2022-03-27 08:10:02 -03:00
PrototypeTrousers 3b94e9420d fix NPE with ae2fc and blocking mode 2022-03-25 23:46:52 -03:00
PrototypeTrousers f30f334a23 move nonblocking call out of method used by ae2fc coremod 2022-03-24 23:25:28 -03:00
PrototypeTrousers 706e577dab Fix container item crafting (again)
avoid making some copies
fix crash without JEI
2022-03-16 00:52:38 -03:00
PrototypeTrousers ccc8486571 check if gregtech is loaded before checking for MetaTools 2022-03-12 22:36:22 -03:00
PrototypeTrousers 3e8440644e fix autocrafting with container items 2022-03-12 22:21:04 -03:00
PrototypeTrousers 50f4e08b64 Merge remote-tracking branch 'origin/AE2-Omnifactory' into AE2-Omnifactory 2022-03-12 17:27:17 -03:00
PrototypeTrousers cfa9fa2843 invalidate cached itemstack if its gonna be used in a real insertion 2022-03-12 17:14:37 -03:00
PrototypeTrousers 47f819e021 invalidate cached itemstack if its gonna be used in a real insertion 2022-03-12 11:03:04 -03:00
PrototypeTrousers 6d151bb890 GTCEu blocking mode fix 2022-03-11 23:11:52 -03:00
PrototypeTrousers 3305270a71 clean-up 2022-03-11 22:04:58 -03:00
PrototypeTrousers f824bfd2e1 small optimization 2022-03-10 21:35:18 -03:00
PrototypeTrousers 036f4e1c5b heavily tweaked auto-crafting 2022-03-09 23:14:02 -03:00
PrototypeTrousers 146d3f5628 fix fluid dupe 2022-03-06 08:24:29 -03:00
PrototypeTrousers 9c821cb015 cleaning 2022-03-05 23:29:20 -03:00
PrototypeTrousers 3a83c99b1f fix container items return properly 2022-03-05 11:15:32 -03:00
PrototypeTrousers 447c6debab account for interfaces priority affecting which items are extractable 2022-03-04 22:49:55 -03:00
PrototypeTrousers 50470ae3cf version 2022-03-04 21:44:58 -03:00
PrototypeTrousers 993be652c9 delay container item return when simulating crafting tree 2022-03-04 21:30:26 -03:00
PrototypeTrousers b3bfbd0b58 remove debugging log 2022-03-04 17:08:23 -03:00
PrototypeTrousers 49b3dc8b60 undo partially pattern cache rebuild optimization
enabled pattern substitution now can use substitute patterned items
2022-03-03 22:25:10 -03:00
PrototypeTrousers 71ffcfb839 JEI transfer handler OutOfBounds fix 2022-03-01 13:02:09 -03:00
PrototypeTrousers 73f76a6654 clean up 2022-02-28 23:30:52 -03:00
PrototypeTrousers 645de1d868 Merge branch 'craftingtree-tweaks' into AE2-Omnifactory 2022-02-28 23:17:21 -03:00
PrototypeTrousers 3ddc846648 Merge branch 'craftingtree-tweaks' into AE2-Omnifactory 2022-02-28 23:06:11 -03:00
25 changed files with 1308 additions and 997 deletions
+2 -1
View File
@@ -4,7 +4,7 @@ aebuild=7
aegroup=appeng
aebasename=appliedenergistics2
extended=extended_life
extendedversion=v50g
extendedversion=v52b
#########################################################
# Versions #
#########################################################
@@ -26,6 +26,7 @@ cofhcore_version=1.12.2-4.5.2.19
crafttweaker_version=4.1.8.9
inventorytweaks_version=1.63
ctm_version=MC1.12.2-0.3.1.16
forestry_version=5.8.2.387
#########################################################
# Deployment #
#########################################################
+2
View File
@@ -97,6 +97,8 @@ dependencies {
compileOnly "inventory-tweaks:InventoryTweaks:${inventorytweaks_version}:api"
compileOnly "team.chisel.ctm:CTM:${ctm_version}"
compileOnly "de.ellpeck.actuallyadditions:ActuallyAdditions:1.12.2-r152.16:api"
deobfCompile "net.sengir.forestry:forestry_${minecraft_version}:$forestry_version"
// at runtime, use the full JEI jar
runtime "mezz.jei:jei_${minecraft_version}:${jei_version}"
+24 -37
View File
@@ -33,6 +33,7 @@ import java.util.Set;
import java.util.concurrent.TimeUnit;
import appeng.container.slot.*;
import appeng.util.Platform;
import com.google.common.base.Joiner;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Lists;
@@ -159,7 +160,7 @@ public abstract class AEBaseGui extends GuiContainer implements IMTModGuiContain
final List<Slot> slots = this.getInventorySlots();
final Iterator<Slot> i = slots.iterator();
while( i.hasNext() )
while ( i.hasNext() )
{
if( i.next() instanceof SlotME )
{
@@ -208,13 +209,17 @@ public abstract class AEBaseGui extends GuiContainer implements IMTModGuiContain
}
}
GlStateManager.enableDepth();
bookmarkedJEIghostItem(mouseX,mouseY);
if( Platform.isModLoaded( "jei" ) )
{
bookmarkedJEIghostItem( mouseX, mouseY );
}
GlStateManager.disableDepth();
}
void bookmarkedJEIghostItem(final int mouseX, final int mouseY) {
if (!isJeiGhostItem)
@Optional.Method( modid = "jei" )
void bookmarkedJEIghostItem( final int mouseX, final int mouseY )
{
if( !isJeiGhostItem )
{
bookmarkedIngredient = runtime.getBookmarkOverlay().getIngredientUnderMouse();
}
@@ -248,7 +253,9 @@ public abstract class AEBaseGui extends GuiContainer implements IMTModGuiContain
}
}
}
private void drawTargets(int mouseX, int mouseY) {
private void drawTargets( int mouseX, int mouseY )
{
GlStateManager.disableLighting();
for( IGhostIngredientHandler.Target target : hoveredIngredientTargets )
{
@@ -377,17 +384,13 @@ public abstract class AEBaseGui extends GuiContainer implements IMTModGuiContain
final AppEngSlot aeSlot = (AppEngSlot) slot;
if( aeSlot.isSlotEnabled() )
{
this.drawTexturedModalRect( ox + aeSlot.xPos - 1, oy + aeSlot.yPos - 1, optionalSlot.getSourceX() - 1, optionalSlot.getSourceY() - 1,
18,
18 );
this.drawTexturedModalRect( ox + aeSlot.xPos - 1, oy + aeSlot.yPos - 1, optionalSlot.getSourceX() - 1, optionalSlot.getSourceY() - 1, 18, 18 );
}
else
{
GlStateManager.color( 1.0F, 1.0F, 1.0F, 0.4F );
GlStateManager.enableBlend();
this.drawTexturedModalRect( ox + aeSlot.xPos - 1, oy + aeSlot.yPos - 1, optionalSlot.getSourceX() - 1, optionalSlot.getSourceY() - 1,
18,
18 );
this.drawTexturedModalRect( ox + aeSlot.xPos - 1, oy + aeSlot.yPos - 1, optionalSlot.getSourceX() - 1, optionalSlot.getSourceY() - 1, 18, 18 );
GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F );
}
}
@@ -506,7 +509,7 @@ public abstract class AEBaseGui extends GuiContainer implements IMTModGuiContain
{
final EntityPlayer player = Minecraft.getMinecraft().player;
if( this.isJeiGhostItem && isDraggingJeiGhostItem)
if( this.isJeiGhostItem && isDraggingJeiGhostItem )
{
for( IGhostIngredientHandler.Target target : hoveredIngredientTargets )
{
@@ -759,7 +762,8 @@ public abstract class AEBaseGui extends GuiContainer implements IMTModGuiContain
this.disableShiftClick = false;
}
if (clickType == ClickType.PICKUP && isJeiGhostItem && !isDraggingJeiGhostItem) {
if( clickType == ClickType.PICKUP && isJeiGhostItem && !isDraggingJeiGhostItem )
{
this.isDraggingJeiGhostItem = true;
return;
}
@@ -879,7 +883,7 @@ public abstract class AEBaseGui extends GuiContainer implements IMTModGuiContain
if( stack != ItemStack.EMPTY )
{
InventoryAction direction = wheel > 0 ? InventoryAction.PLACE_SINGLE : InventoryAction.PICKUP_SINGLE;
final PacketInventoryAction p = new PacketInventoryAction( direction , slot.slotNumber , 0);
final PacketInventoryAction p = new PacketInventoryAction( direction, slot.slotNumber, 0 );
NetworkHandler.instance().sendToServer( p );
}
}
@@ -1032,27 +1036,11 @@ public abstract class AEBaseGui extends GuiContainer implements IMTModGuiContain
final float f1 = 0.00390625F;
final float f = 0.00390625F;
final float par6 = 16;
vb.pos( par1 + 0, par2 + par6, this.zLevel )
.tex( ( par3 + 0 ) * f, ( par4 + par6 ) * f1 )
.color( 1.0f, 1.0f, 1.0f,
aes.getOpacityOfIcon() )
.endVertex();
vb.pos( par1 + 0, par2 + par6, this.zLevel ).tex( ( par3 + 0 ) * f, ( par4 + par6 ) * f1 ).color( 1.0f, 1.0f, 1.0f, aes.getOpacityOfIcon() ).endVertex();
final float par5 = 16;
vb.pos( par1 + par5, par2 + par6, this.zLevel )
.tex( ( par3 + par5 ) * f, ( par4 + par6 ) * f1 )
.color( 1.0f, 1.0f, 1.0f,
aes.getOpacityOfIcon() )
.endVertex();
vb.pos( par1 + par5, par2 + 0, this.zLevel )
.tex( ( par3 + par5 ) * f, ( par4 + 0 ) * f1 )
.color( 1.0f, 1.0f, 1.0f,
aes.getOpacityOfIcon() )
.endVertex();
vb.pos( par1 + 0, par2 + 0, this.zLevel )
.tex( ( par3 + 0 ) * f, ( par4 + 0 ) * f1 )
.color( 1.0f, 1.0f, 1.0f,
aes.getOpacityOfIcon() )
.endVertex();
vb.pos( par1 + par5, par2 + par6, this.zLevel ).tex( ( par3 + par5 ) * f, ( par4 + par6 ) * f1 ).color( 1.0f, 1.0f, 1.0f, aes.getOpacityOfIcon() ).endVertex();
vb.pos( par1 + par5, par2 + 0, this.zLevel ).tex( ( par3 + par5 ) * f, ( par4 + 0 ) * f1 ).color( 1.0f, 1.0f, 1.0f, aes.getOpacityOfIcon() ).endVertex();
vb.pos( par1 + 0, par2 + 0, this.zLevel ).tex( ( par3 + 0 ) * f, ( par4 + 0 ) * f1 ).color( 1.0f, 1.0f, 1.0f, aes.getOpacityOfIcon() ).endVertex();
tessellator.draw();
}
@@ -1066,8 +1054,7 @@ public abstract class AEBaseGui extends GuiContainer implements IMTModGuiContain
{
if( ( (AppEngSlot) s ).getIsValid() == hasCalculatedValidness.NotAvailable )
{
boolean isValid = s.isItemValid(
is ) || s instanceof SlotOutput || s instanceof AppEngCraftingSlot || s instanceof SlotDisabled || s instanceof SlotInaccessible || s instanceof SlotFake || s instanceof SlotRestrictedInput || s instanceof SlotDisconnected;
boolean isValid = s.isItemValid( is ) || s instanceof SlotOutput || s instanceof AppEngCraftingSlot || s instanceof SlotDisabled || s instanceof SlotInaccessible || s instanceof SlotFake || s instanceof SlotRestrictedInput || s instanceof SlotDisconnected;
if( isValid && s instanceof SlotRestrictedInput )
{
try
+3
View File
@@ -25,6 +25,7 @@ import java.util.concurrent.TimeUnit;
import javax.annotation.Nonnull;
import appeng.helpers.NonBlockingItems;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Lists;
@@ -238,6 +239,8 @@ public final class AppEng
AppEng.proxy.postInit();
AEConfig.instance().save();
NonBlockingItems.INSTANCE.init();
NetworkRegistry.INSTANCE.registerGuiHandler( this, GuiBridge.GUI_Handler );
NetworkHandler.init( "AE2" );
@@ -24,34 +24,9 @@ import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import appeng.core.sync.packets.*;
import io.netty.buffer.ByteBuf;
import appeng.core.sync.packets.PacketAssemblerAnimation;
import appeng.core.sync.packets.PacketClick;
import appeng.core.sync.packets.PacketCompassRequest;
import appeng.core.sync.packets.PacketCompassResponse;
import appeng.core.sync.packets.PacketCompressedNBT;
import appeng.core.sync.packets.PacketConfigButton;
import appeng.core.sync.packets.PacketCraftRequest;
import appeng.core.sync.packets.PacketFluidSlot;
import appeng.core.sync.packets.PacketInventoryAction;
import appeng.core.sync.packets.PacketJEIRecipe;
import appeng.core.sync.packets.PacketLightning;
import appeng.core.sync.packets.PacketMEFluidInventoryUpdate;
import appeng.core.sync.packets.PacketMEInventoryUpdate;
import appeng.core.sync.packets.PacketMatterCannon;
import appeng.core.sync.packets.PacketMockExplosion;
import appeng.core.sync.packets.PacketPaintedEntity;
import appeng.core.sync.packets.PacketPartPlacement;
import appeng.core.sync.packets.PacketPatternSlot;
import appeng.core.sync.packets.PacketProgressBar;
import appeng.core.sync.packets.PacketSwapSlots;
import appeng.core.sync.packets.PacketSwitchGuis;
import appeng.core.sync.packets.PacketTargetFluidStack;
import appeng.core.sync.packets.PacketTargetItemStack;
import appeng.core.sync.packets.PacketTransitionEffect;
import appeng.core.sync.packets.PacketValueConfig;
public class AppEngPacketHandlerBase
{
@@ -107,7 +82,10 @@ public class AppEngPacketHandlerBase
PACKET_PAINTED_ENTITY( PacketPaintedEntity.class ),
PACKET_FLUID_TANK( PacketFluidSlot.class );
PACKET_FLUID_TANK( PacketFluidSlot.class ),
PACKET_INFORM_PLAYER( PacketInformPlayer.class );
private final Class<? extends AppEngPacket> packetClass;
private final Constructor<? extends AppEngPacket> packetConstructor;
@@ -0,0 +1,89 @@
package appeng.core.sync.packets;
import appeng.api.storage.data.IAEItemStack;
import appeng.core.AppEng;
import appeng.core.sync.AppEngPacket;
import appeng.core.sync.network.INetworkInfo;
import appeng.util.item.AEItemStack;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.text.TextComponentString;
import java.io.IOException;
public class PacketInformPlayer extends AppEngPacket
{
private IAEItemStack actualItem = null;
private IAEItemStack reportedItem = null;
private final InfoType type;
public PacketInformPlayer( ByteBuf stream ) throws IOException
{
this.type = InfoType.values()[stream.readInt()];
if( type == InfoType.PARTIAL_ITEM_EXTRACTION )
{
this.reportedItem = AEItemStack.fromPacket( stream );
this.actualItem = AEItemStack.fromPacket( stream );
}
else if( type == InfoType.NO_ITEMS_EXTRACTED )
{
this.reportedItem = AEItemStack.fromPacket( stream );
}
}
public PacketInformPlayer( final IAEItemStack iaeItemStack ) throws IOException
{
this( iaeItemStack, null );
}
public PacketInformPlayer( IAEItemStack extra, IAEItemStack result ) throws IOException
{
this.reportedItem = extra;
this.actualItem = result;
if( actualItem == null )
{
this.type = InfoType.NO_ITEMS_EXTRACTED;
}
else
{
this.type = InfoType.PARTIAL_ITEM_EXTRACTION;
}
final ByteBuf data = Unpooled.buffer();
data.writeInt( this.getPacketID() );
data.writeInt( type.ordinal() );
reportedItem.writeToPacket( data );
if( actualItem != null )
{
actualItem.writeToPacket( data );
}
this.configureWrite( data );
}
@Override
public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player )
{
TextComponentString msg = null;
if( this.type == InfoType.PARTIAL_ITEM_EXTRACTION )
{
AppEng.proxy.getPlayers().get( 0 ).sendStatusMessage( new TextComponentString( "System reported " + reportedItem.getStackSize() + " " + reportedItem.getItem().getItemStackDisplayName( reportedItem.getDefinition() ) + " available but could only extract" + actualItem.getStackSize() ), false );
}
else if( this.type == InfoType.NO_ITEMS_EXTRACTED )
{
AppEng.proxy.getPlayers().get( 0 ).sendStatusMessage( new TextComponentString( "System reported " + reportedItem.getStackSize() + " " + reportedItem.getItem().getItemStackDisplayName( reportedItem.getDefinition() ) + " available but could not extract anything" ), false );
}
}
public enum InfoType
{
PARTIAL_ITEM_EXTRACTION,
NO_ITEMS_EXTRACTED
}
}
@@ -30,7 +30,6 @@ import java.util.List;
import appeng.api.config.FuzzyMode;
import appeng.container.implementations.ContainerExpandedProcessingPatternTerm;
import appeng.container.implementations.ContainerPatternTerm;
import gregtech.common.items.MetaTool;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
@@ -41,6 +40,7 @@ import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraftforge.fml.common.Optional;
import net.minecraftforge.items.IItemHandler;
import appeng.api.AEApi;
@@ -175,7 +175,8 @@ public class PacketJEIRecipe extends AppEngPacket
{
ItemStack currentItem = craftMatrix.getStackInSlot( x );
if (x >= this.recipe.size()) {
if( x >= this.recipe.size() )
{
currentItem = ItemStack.EMPTY;
}
@@ -228,7 +229,7 @@ public class PacketJEIRecipe extends AppEngPacket
out = Platform.poweredExtraction( energy, storage, request, cct.getActionSource() );
if( out == null )
{
if( request.getItem().isDamageable() || ( Platform.isModLoaded( "gregtech" ) && request.getItem() instanceof MetaTool ) )
if( request.getItem().isDamageable() || Platform.isGTDamageableItem( request.getItem() ) )
{
Collection<IAEItemStack> outList = inv.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ).getStorageList().findFuzzy( request, FuzzyMode.IGNORE_ALL );
for( IAEItemStack is : outList )
@@ -261,7 +262,7 @@ public class PacketJEIRecipe extends AppEngPacket
if( out != null )
{
if (!cct.useRealItems())
if( !cct.useRealItems() )
{
out.setStackSize( recipe.get( x )[y].getCount() );
}
@@ -285,7 +286,7 @@ public class PacketJEIRecipe extends AppEngPacket
}
}
}
if (!cct.useRealItems())
if( !cct.useRealItems() )
{
if( currentItem.isEmpty() && recipe.size() > x && this.recipe.get( x ) != null )
{
@@ -301,24 +302,25 @@ public class PacketJEIRecipe extends AppEngPacket
if( this.output != null && ( ( con instanceof ContainerPatternTerm && !( (ContainerPatternTerm) con ).isCraftingMode() ) || con instanceof ContainerExpandedProcessingPatternTerm ) )
{
IItemHandler outputSlots = cct.getInventoryByName( "output" );
for( int i = 0; i < this.output.size(); ++i )
for( int i = 0; i < outputSlots.getSlots(); ++i )
{
if( this.output.get( i ) == null )
ItemHandlerUtil.setStackInSlot( outputSlots, i, ItemStack.EMPTY );
}
for( int i = 0; i < this.output.size() && i < outputSlots.getSlots(); ++i )
{
if( this.output.get( i ) == null || this.output.get( i ) == ItemStack.EMPTY )
{
continue;
}
ItemHandlerUtil.setStackInSlot( outputSlots, i, this.output.get( i ) );
}
}
}
}
/**
*
* @param slot
* @param is itemstack
* @param is itemstack
* @return is if it can be used, else EMPTY
*/
private ItemStack canUseInSlot( int slot, ItemStack is )
+59 -49
View File
@@ -19,15 +19,6 @@
package appeng.crafting;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Stopwatch;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import appeng.api.AEApi;
import appeng.api.config.Actionable;
import appeng.api.networking.IGrid;
@@ -36,7 +27,6 @@ import appeng.api.networking.IGridNode;
import appeng.api.networking.crafting.ICraftingCallback;
import appeng.api.networking.crafting.ICraftingGrid;
import appeng.api.networking.crafting.ICraftingJob;
import appeng.api.networking.crafting.ICraftingPatternDetails;
import appeng.api.networking.security.IActionHost;
import appeng.api.networking.security.IActionSource;
import appeng.api.networking.storage.IStorageGrid;
@@ -46,6 +36,14 @@ import appeng.api.storage.data.IItemList;
import appeng.api.util.DimensionalCoord;
import appeng.core.AELog;
import appeng.hooks.TickHandler;
import appeng.me.cache.GridStorageCache;
import com.google.common.base.Stopwatch;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
public class CraftingJob implements Runnable, ICraftingJob
@@ -57,47 +55,45 @@ public class CraftingJob implements Runnable, ICraftingJob
private final World world;
private final IItemList<IAEItemStack> crafting = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList();
private final IItemList<IAEItemStack> missing = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList();
private final IItemList<IAEItemStack> usedWhileBuilding = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList();
private final IItemList<IAEItemStack> neededForLoop = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList();
private final Object2ObjectOpenHashMap<CraftingTreeNode, IAEItemStack> reserved = new Object2ObjectOpenHashMap<>();
private final HashMap<String, TwoIntegers> opsAndMultiplier = new HashMap<>();
private final Object monitor = new Object();
private final Stopwatch tickSpreadingWatch = Stopwatch.createUnstarted();
private final Stopwatch craftingTreeWatch = Stopwatch.createUnstarted();
private CraftingTreeNode tree;
private final IAEItemStack output;
private final IActionSource actionSrc;
private final ICraftingCallback callback;
private CraftingTreeNode tree;
private boolean simulate = false;
private MECraftingInventory availableCheck;
private long bytes = 0;
private final IActionSource actionSrc;
private final ICraftingCallback callback;
private boolean running = false;
private boolean done = false;
private int time;
private int incTime;
private World wrapWorld( final World w )
{
return w;
}
public CraftingJob( final World w, final IGrid grid, final IActionSource actionSrc, final IAEItemStack what, final ICraftingCallback callback )
{
this.world = this.wrapWorld( w );
this.world = w;
this.output = what.copy();
this.actionSrc = actionSrc;
this.callback = callback;
final ICraftingGrid cc = grid.getCache( ICraftingGrid.class );
final IStorageGrid sg = grid.getCache( IStorageGrid.class );
this.original = new MECraftingInventory( sg.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ), actionSrc, false, false, false );
ICraftingGrid cc = grid.getCache( ICraftingGrid.class );
final GridStorageCache sg = grid.getCache( IStorageGrid.class );
this.original = sg.getExtractableList( actionSrc );
this.availableCheck = new MECraftingInventory( this.original, false, false, false );
this.setTree( this.getCraftingTree( cc, what ) );
this.availableCheck = null;
}
private CraftingTreeNode getCraftingTree( final ICraftingGrid cc, final IAEItemStack what )
{
return new CraftingTreeNode( cc, this, what, null, -1, 0 );
return new CraftingTreeNode( cc, this, what, what.getStackSize(), null, -1 );
}
void refund( final IAEItemStack o )
@@ -105,27 +101,17 @@ public class CraftingJob implements Runnable, ICraftingJob
this.availableCheck.injectItems( o, Actionable.MODULATE, this.actionSrc );
}
public IItemList<IAEItemStack> getUsedWhileBuilding()
{
return usedWhileBuilding;
}
public IAEItemStack getOriginal( IAEItemStack request )
{
return original.getItemList().findPrecise( request );
}
IAEItemStack checkUse( final IAEItemStack available )
{
return this.availableCheck.extractItems( available, Actionable.MODULATE, this.actionSrc );
}
public void writeToNBT( final NBTTagCompound out )
IAEItemStack checkAvailable( final IAEItemStack available )
{
return this.availableCheck.extractItems( available, Actionable.SIMULATE, this.actionSrc );
}
void addTask( IAEItemStack what, final long crafts, final ICraftingPatternDetails details, final int depth )
void addTask( IAEItemStack what, final long crafts )
{
if( crafts > 0 )
{
@@ -141,6 +127,22 @@ public class CraftingJob implements Runnable, ICraftingJob
this.missing.add( what );
}
public void reserve( CraftingTreeNode node, IAEItemStack stack )
{
this.checkUse( stack );
reserved.put( node, stack );
}
public IItemList<IAEItemStack> getNeededForLoop()
{
return neededForLoop;
}
public Object2ObjectOpenHashMap<CraftingTreeNode, IAEItemStack> getReserved()
{
return reserved;
}
@Override
public void run()
{
@@ -151,13 +153,15 @@ public class CraftingJob implements Runnable, ICraftingJob
TickHandler.INSTANCE.registerCraftingSimulation( this.world, this );
this.handlePausing();
craftingTreeWatch.start();
final MECraftingInventory craftingInventory = new MECraftingInventory( this.original, true, false, true );
craftingInventory.ignore( this.output );
this.availableCheck = new MECraftingInventory( this.original, false, false, false );
this.reserved.values().forEach( availableCheck::reserve );
this.reserved.values().forEach( craftingInventory::reserve );
craftingTreeWatch.start();
this.getTree().request( craftingInventory, this.output.getStackSize(), this.actionSrc );
craftingTreeWatch.stop();
this.getTree().dive( this );
for( final String s : this.opsAndMultiplier.keySet() )
@@ -166,8 +170,14 @@ public class CraftingJob implements Runnable, ICraftingJob
AELog.crafting( s + " * " + ti.times + " = " + ( ti.perOp * ti.times ) );
}
craftingTreeWatch.stop();
this.logCraftingJob( "real, success", craftingTreeWatch );
if( actionSrc.player().isPresent() )
{
this.logCraftingJob( "simulated, success", craftingTreeWatch );
}
else
{
this.logCraftingJob( "real, success", craftingTreeWatch );
}
}
catch( final CraftBranchFailure e )
{
@@ -177,14 +187,16 @@ public class CraftingJob implements Runnable, ICraftingJob
{
if( actionSrc.player().isPresent() )
{
craftingTreeWatch.reset().start();
final MECraftingInventory craftingInventory = new MECraftingInventory( this.original, true, false, true );
craftingInventory.ignore( this.output );
this.getTree().setSimulate();
this.availableCheck = new MECraftingInventory( this.original, false, false, false );
this.reserved.values().forEach( availableCheck::reserve );
this.reserved.values().forEach( craftingInventory::reserve );
this.getTree().setSimulate();
craftingTreeWatch.reset().start();
this.getTree().request( craftingInventory, this.output.getStackSize(), this.actionSrc );
craftingTreeWatch.stop();
this.getTree().dive( this );
for( final String s : this.opsAndMultiplier.keySet() )
@@ -193,12 +205,10 @@ public class CraftingJob implements Runnable, ICraftingJob
AELog.crafting( s + " * " + ti.times + " = " + ( ti.perOp * ti.times ) );
}
craftingTreeWatch.stop();
this.logCraftingJob( "simulate", craftingTreeWatch );
this.logCraftingJob( "simulated, failed", craftingTreeWatch );
}
else
{
craftingTreeWatch.stop();
this.logCraftingJob( "real, failed", craftingTreeWatch );
}
}
@@ -267,7 +277,7 @@ public class CraftingJob implements Runnable, ICraftingJob
}
}
}
if( Thread.interrupted() )
{
throw new InterruptedException();
@@ -19,15 +19,6 @@
package appeng.crafting;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.google.common.collect.Lists;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.world.World;
import appeng.api.AEApi;
import appeng.api.config.Actionable;
import appeng.api.config.FuzzyMode;
@@ -37,9 +28,22 @@ import appeng.api.networking.security.IActionSource;
import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList;
import appeng.core.sync.network.NetworkHandler;
import appeng.core.sync.packets.PacketInformPlayer;
import appeng.me.cluster.implementations.CraftingCPUCluster;
import appeng.util.Platform;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.Optional;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
@Optional.Interface( iface = "gregtech.api.items.IToolItem", modid = "gregtech" )
public class CraftingTreeNode
{
@@ -54,22 +58,20 @@ public class CraftingTreeNode
private final IAEItemStack what;
// what are the crafting patterns for this?
private final ArrayList<CraftingTreeProcess> nodes = new ArrayList<>();
private final boolean canEmit;
private CraftingTreeNode loopHead;
private int bytes = 0;
private boolean canEmit = false;
private long missing = 0;
private long howManyEmitted = 0;
private boolean exhausted = false;
private boolean sim;
public CraftingTreeNode( final ICraftingGrid cc, final CraftingJob job, final IAEItemStack wat, final CraftingTreeProcess par, final int slot, final int depth )
public CraftingTreeNode( final ICraftingGrid cc, final CraftingJob job, final IAEItemStack wat, long amount, final CraftingTreeProcess par, final int slot )
{
this.what = wat;
this.parent = par;
this.slot = slot;
this.world = job.getWorld();
this.job = job;
this.sim = false;
this.canEmit = cc.canEmitFor( this.what );
@@ -81,114 +83,136 @@ public class CraftingTreeNode
for( final ICraftingPatternDetails details : cc.getCraftingFor( this.what, this.parent == null ? null : this.parent.details, slot, this.world ) )// in
// order.
{
if( this.parent == null || this.parent.notRecursive( details ) )
int times = 1;
for( IAEItemStack o : details.getCondensedOutputs() )
{
this.nodes.add( new CraftingTreeProcess( cc, job, details, this, depth + 1 ) );
}
}
}
public CraftingTreeNode( final ICraftingGrid cc, final CraftingJob job, final IAEItemStack wat, final CraftingTreeProcess par, final int slot, final int depth, boolean available )
{
this.what = wat;
this.parent = par;
this.slot = slot;
this.world = job.getWorld();
this.job = job;
this.sim = false;
this.canEmit = cc.canEmitFor( this.what );
if( this.canEmit )
{
return; // if you can emit for something, you can't make it with patterns.
}
if( !available )
{
for( final ICraftingPatternDetails details : cc.getCraftingFor( this.what, this.parent == null ? null : this.parent.details, slot, this.world ) )// in
// order.
{
if( this.parent == null || this.parent.notRecursive( details ) )
if( what.equals( o ) )
{
this.nodes.add( new CraftingTreeProcess( cc, job, details, this, depth + 1 ) );
times = (int) ( amount / o.getStackSize() + ( amount % o.getStackSize() != 0 ? 1 : 0 ) );
}
}
if( this.parent == null )
{
this.nodes.add( new CraftingTreeProcess( cc, job, details, times, this ) );
continue;
}
if( details == parent.details )
{
continue;
}
CraftingTreeNode recursive = recursiveNode( this );
if( recursive == null )
{
this.nodes.add( new CraftingTreeProcess( cc, job, details, times, this ) );
}
else
{
reserveForNode();
}
}
}
boolean notRecursive( final ICraftingPatternDetails details )
void reserveForNode()
{
IAEItemStack[] o = details.getCondensedOutputs();
for( final IAEItemStack i : o )
if( this.equals( loopHead ) )
{
if( i.equals( this.what ) )
{
return false;
}
return;
}
o = details.getCondensedInputs();
for( final IAEItemStack i : o )
IAEItemStack available = job.checkAvailable( this.what );
if( available != null && available.getStackSize() >= this.what.getStackSize() )
{
if( i.equals( this.what ) )
{
return false;
}
this.job.reserve( this, this.what.copy() );
}
if( this.parent == null )
else
{
return true;
parent.reserveForNode();
}
return this.parent.notRecursive( details );
}
IAEItemStack request( final MECraftingInventory inv, long l, final IActionSource src ) throws CraftBranchFailure, InterruptedException
{
this.job.handlePausing();
if( this.canEmit )
{
final IAEItemStack wat = this.what.copy();
wat.setStackSize( l );
this.howManyEmitted = wat.getStackSize();
this.bytes += wat.getStackSize();
return wat;
}
final IItemList<IAEItemStack> inventoryList = inv.getItemList();
IAEItemStack reserved = job.getReserved().get( this );
final List<IAEItemStack> thingsUsed = new ArrayList<>();
this.what.setStackSize( l );
if( this.getSlot() >= 0 && this.parent != null && this.parent.details.isCraftable() )
{
final Collection<IAEItemStack> itemList;
final IItemList<IAEItemStack> inventoryList = inv.getItemList();
Collection<IAEItemStack> itemList = new HashSet<>();
if( this.parent.details.canSubstitute() )
if( this.what.getItem().isDamageable() || Platform.isGTDamageableItem( this.what.getItem() ) )
{
final List<IAEItemStack> substitutes = this.parent.details.getSubstituteInputs( this.slot );
itemList = new ArrayList<>( substitutes.size() );
itemList.addAll( inventoryList.findFuzzy( this.what, FuzzyMode.IGNORE_ALL ) );
for( IAEItemStack stack : substitutes )
if( this.parent.details.canSubstitute() )
{
itemList.addAll( inventoryList.findFuzzy( stack, FuzzyMode.IGNORE_ALL ) );
for( IAEItemStack is : inventoryList )
{
if( is.fuzzyComparison( this.what, FuzzyMode.IGNORE_ALL ) )
{
itemList.add( is );
}
}
}
}
else
{
itemList = Lists.newArrayList();
final IAEItemStack item = inventoryList.findPrecise( this.what );
if( item != null )
{
itemList.add( item );
}
if( this.parent.details.canSubstitute() )
{
for( IAEItemStack s : parent.details.getSubstituteInputs( this.slot ) )
{
if( s != null )
{
for( IAEItemStack ss : inventoryList.findFuzzy( s, FuzzyMode.IGNORE_ALL ) )
{
if( ss != null )
{
itemList.add( ss );
}
}
}
}
}
}
for( IAEItemStack fuzz : itemList )
{
if( this.parent.details.isValidItemForSlot( this.getSlot(), fuzz.copy().getCachedItemStack( 1 ), this.world ) )
if( this.parent.details.isValidItemForSlot( this.getSlot(), fuzz.getDefinition(), this.world ) )
{
fuzz = fuzz.copy();
fuzz.setStackSize( l );
final IAEItemStack available = inv.extractItems( fuzz, Actionable.MODULATE, src );
final IAEItemStack available;
if( reserved != null )
{
available = reserved;
}
else
{
available = inv.extractItems( fuzz, Actionable.MODULATE, src );
}
if( available != null )
{
@@ -201,6 +225,11 @@ public class CraftingTreeNode
thingsUsed.add( is.copy() );
this.used.add( is );
}
else if( reserved != null )
{
thingsUsed.add( reserved.copy() );
this.used.add( reserved );
}
}
this.bytes += available.getStackSize();
@@ -216,7 +245,20 @@ public class CraftingTreeNode
}
else
{
final IAEItemStack available = inv.extractItems( this.what, Actionable.MODULATE, src );
final IAEItemStack available;
if( parent == null && this.what.equals( job.getOutput() ) )
{
available = null;
}
else if( reserved != null )
{
available = reserved;
}
else
{
available = inv.extractItems( this.what, Actionable.MODULATE, src );
}
if( available != null )
{
@@ -229,6 +271,11 @@ public class CraftingTreeNode
thingsUsed.add( is.copy() );
this.used.add( is );
}
else if( reserved != null )
{
thingsUsed.add( reserved.copy() );
this.used.add( reserved );
}
}
this.bytes += available.getStackSize();
@@ -241,17 +288,6 @@ public class CraftingTreeNode
}
}
if( this.canEmit )
{
final IAEItemStack wat = this.what.copy();
wat.setStackSize( l );
this.howManyEmitted = wat.getStackSize();
this.bytes += wat.getStackSize();
return wat;
}
this.exhausted = true;
if( this.nodes.size() == 1 )
@@ -265,7 +301,6 @@ public class CraftingTreeNode
pro.request( inv, pro.getTimes( l, madeWhat.getStackSize() ), src );
madeWhat.setStackSize( l );
final IAEItemStack available = inv.extractItems( madeWhat, Actionable.MODULATE, src );
if( available != null )
@@ -293,7 +328,9 @@ public class CraftingTreeNode
while ( pro.possible && l > 0 )
{
final MECraftingInventory subInv = new MECraftingInventory( inv, true, true, true );
pro.request( subInv, 1, src );
final IAEItemStack madeWhat = pro.getAmountCrafted( this.what );
pro.request( subInv, pro.getTimes( l, madeWhat.getStackSize() ), src );
this.what.setStackSize( l );
final IAEItemStack available = subInv.extractItems( this.what, Actionable.MODULATE, src );
@@ -326,10 +363,10 @@ public class CraftingTreeNode
}
}
if( this.sim )
if( job.isSimulation() )
{
this.missing += l;
this.bytes += l;
this.missing += l;
final IAEItemStack rv = this.what.copy();
rv.setStackSize( l );
return rv;
@@ -345,6 +382,26 @@ public class CraftingTreeNode
throw new CraftBranchFailure( this.what, l );
}
CraftingTreeNode recursiveNode( CraftingTreeNode node )
{
if( this.parent == null )
{
return null;
}
if( node != this )
{
if( node.what.equals( this.what ) )
{
if( node.what.getStackSize() == this.what.getStackSize() )
{
loopHead = this;
return node;
}
}
}
return this.parent.notRecursive( node );
}
void dive( final CraftingJob job )
{
if( this.missing > 0 )
@@ -370,7 +427,6 @@ public class CraftingTreeNode
void setSimulate()
{
this.sim = true;
this.missing = 0;
this.bytes = 0;
this.used.resetStatus();
@@ -392,7 +448,21 @@ public class CraftingTreeNode
{
if( src.player().isPresent() )
{
src.player().get().sendStatusMessage( new TextComponentString( "System reported " + i.getStackSize() + " " + i.getDefinition().getItem().getItemStackDisplayName( i.getDefinition() ) + " available but could not extract anything" ), false );
try
{
if( ex == null )
{
NetworkHandler.instance().sendTo( new PacketInformPlayer( i ), (EntityPlayerMP) src.player().get() );
}
else
{
NetworkHandler.instance().sendTo( new PacketInformPlayer( ex, i ), (EntityPlayerMP) src.player().get() );
}
}
catch( IOException e )
{
e.printStackTrace();
}
}
throw new CraftBranchFailure( i, i.getStackSize() );
}
@@ -19,236 +19,202 @@
package appeng.crafting;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import it.unimi.dsi.fastutil.objects.Object2LongArrayMap;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraftforge.fml.common.FMLCommonHandler;
import appeng.api.AEApi;
import appeng.api.config.Actionable;
import appeng.api.config.FuzzyMode;
import appeng.api.networking.crafting.ICraftingGrid;
import appeng.api.networking.crafting.ICraftingPatternDetails;
import appeng.api.networking.security.IActionSource;
import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList;
import appeng.container.ContainerNull;
import appeng.me.cluster.implementations.CraftingCPUCluster;
import appeng.util.Platform;
import org.apache.commons.lang3.tuple.Pair;
import appeng.util.item.AEItemStack;
import com.google.common.collect.ImmutableCollection;
import it.unimi.dsi.fastutil.objects.Object2LongArrayMap;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
public class CraftingTreeProcess
{
private final CraftingTreeNode parent;
final ICraftingPatternDetails details;
private final CraftingTreeNode parent;
private final CraftingJob job;
private final Object2LongArrayMap<CraftingTreeNode> nodes = new Object2LongArrayMap<>();
private final int depth;
boolean possible = true;
private World world;
private long crafts = 0;
private boolean containerItems;
private boolean limitQty;
private boolean fullSimulation;
private long bytes = 0;
private boolean hasContainerItem = false;
public CraftingTreeProcess( final ICraftingGrid cc, final CraftingJob job, final ICraftingPatternDetails details, final CraftingTreeNode craftingTreeNode, final int depth )
public CraftingTreeProcess( final ICraftingGrid cc, final CraftingJob job, final ICraftingPatternDetails details, int times, final CraftingTreeNode craftingTreeNode )
{
this.parent = craftingTreeNode;
this.details = details;
this.job = job;
this.depth = depth;
final World world = job.getWorld();
World world = job.getWorld();
if( details.isCraftable() )
final IAEItemStack[] list = details.getInputs();
// this is minor different then below, this slot uses the pattern, but kinda fudges it.
for( IAEItemStack part : details.getCondensedInputs() )
{
final IAEItemStack[] list = details.getInputs();
for( final IAEItemStack part : details.getCondensedInputs() )
if( part == null )
{
boolean isAnInput = false;
for( final IAEItemStack a : details.getCondensedOutputs() )
continue;
}
for( int x = 0; x < list.length; x++ )
{
final IAEItemStack comparePart = list[x];
if( part.equals( comparePart ) )
{
if( a != null && a.equals( part ) )
boolean isPartContainer = false;
if( part.getItem().hasContainerItem( part.getDefinition() ) )
{
part = list[x];
isPartContainer = true;
this.hasContainerItem = true;
}
long wantedSize = isPartContainer ? part.getStackSize() : part.getStackSize() * times;
if( details.canSubstitute() && cc.getCraftingFor( part, details, x, world ).isEmpty() )
{
for( IAEItemStack subs : details.getSubstituteInputs( x ) )
{
if( subs.fuzzyComparison( part, FuzzyMode.IGNORE_ALL ) )
{
this.nodes.put( new CraftingTreeNode( cc, job, subs.copy(), wantedSize, this, x ), part.getStackSize() / times );
wantedSize = 0;
break;
}
}
//try to order the crafting of a substitute
ICraftingPatternDetails prioritizedPattern = null;
IAEItemStack prioritizedIAE = null;
for( IAEItemStack subs : details.getSubstituteInputs( x ) )
{
if( subs.equals( part ) )
{
continue;
}
ImmutableCollection<ICraftingPatternDetails> detailCollection = cc.getCraftingFor( subs, details, x, world );
for( ICraftingPatternDetails sp : detailCollection )
{
if( prioritizedPattern == null )
{
prioritizedPattern = sp;
prioritizedIAE = subs;
}
else
{
if( sp.getPriority() > prioritizedPattern.getPriority() )
{
prioritizedPattern = sp;
}
}
}
if( prioritizedIAE != null )
{
this.nodes.put( new CraftingTreeNode( cc, job, prioritizedIAE.copy(), wantedSize, this, x ), part.getStackSize() / times );
wantedSize = 0;
break;
}
}
}
if( wantedSize > 0 )
{
part = part.copy().setStackSize( wantedSize );
// use the first slot...
this.nodes.put( new CraftingTreeNode( cc, job, part.copy(), wantedSize, this, x ), part.getStackSize() / times );
wantedSize = 0;
}
if( !isPartContainer && wantedSize == 0 )
{
isAnInput = true;
break;
}
}
if( isAnInput )
{
this.limitQty = true;
}
if( part.getItem().hasContainerItem( part.getDefinition() ) )
{
this.limitQty = this.containerItems = true;
break;
}
}
if( this.containerItems )
{
for( int x = 0; x < list.length; x++ )
{
final IAEItemStack part = list[x];
if( part != null )
{
job.getUsedWhileBuilding().addStorage( part );
IAEItemStack used = job.getUsedWhileBuilding().findPrecise( part );
if( job.getOriginal( part ) != null && used.getStackSize() <= job.getOriginal( part ).getStackSize() )
{
this.nodes.put( new CraftingTreeNode( cc, job, part.copy(), this, x, depth + 1, true ), part.getStackSize() );
}
else
{
this.nodes.put( new CraftingTreeNode( cc, job, part.copy(), this, x, depth + 1 ), part.getStackSize() );
}
}
}
}
else
{
// this is minor different then below, this slot uses the pattern, but kinda fudges it.
for( final IAEItemStack part : details.getCondensedInputs() )
{
for( int x = 0; x < list.length; x++ )
{
final IAEItemStack comparePart = list[x];
if( part != null && part.equals( comparePart ) )
{
job.getUsedWhileBuilding().addStorage( part );
IAEItemStack used = job.getUsedWhileBuilding().findPrecise( part );
if( job.getOriginal( part ) != null && used.getStackSize() <= job.getOriginal( part ).getStackSize() )
{
this.nodes.put( new CraftingTreeNode( cc, job, part.copy(), this, x, depth + 1, true ), part.getStackSize() );
}
else
{
// use the first slot...
this.nodes.put( new CraftingTreeNode( cc, job, part.copy(), this, x, depth + 1 ), part.getStackSize() );
}
break;
}
}
}
}
}
else
{
for( final IAEItemStack part : details.getCondensedInputs() )
{
boolean isAnInput = false;
for( final IAEItemStack a : details.getCondensedOutputs() )
{
if( a != null && a.equals( part ) )
{
isAnInput = true;
break;
}
}
if( isAnInput )
{
this.limitQty = true;
}
}
for( final IAEItemStack part : details.getCondensedInputs() )
{
this.nodes.put( new CraftingTreeNode( cc, job, part.copy(), this, -1, depth + 1 ), part.getStackSize() );
}
}
}
boolean notRecursive( final ICraftingPatternDetails details )
CraftingTreeNode notRecursive( CraftingTreeNode node )
{
return this.parent == null || this.parent.notRecursive( details );
if( parent == null )
{
return null;
}
return this.parent.recursiveNode( node );
}
long getTimes( final long remaining, final long stackSize )
{
if( this.limitQty || this.fullSimulation )
if( hasContainerItem )
{
return 1;
}
return ( remaining / stackSize ) + ( remaining % stackSize != 0 ? 1 : 0 );
}
void request( final MECraftingInventory inv, final long i, final IActionSource src ) throws CraftBranchFailure, InterruptedException
void request( final MECraftingInventory inv, final long amountOfTimes, final IActionSource src ) throws CraftBranchFailure, InterruptedException
{
this.job.handlePausing();
if( this.fullSimulation )
List<IAEItemStack> containerItems = null;
// request and remove inputs...
for( final Entry<CraftingTreeNode, Long> entry : this.nodes.object2LongEntrySet() )
{
final InventoryCrafting ic = new InventoryCrafting( new ContainerNull(), 3, 3 );
final IAEItemStack stack = entry.getKey().request( inv, details.isCraftable() && hasContainerItem ? 1 : entry.getValue() * amountOfTimes, src );
for( final Entry<CraftingTreeNode, Long> entry : this.nodes.object2LongEntrySet() )
if( stack.equals( job.getOutput() ) )
{
final IAEItemStack item = entry.getKey().getStack( entry.getValue() );
final IAEItemStack stack = entry.getKey().request( inv, item.getStackSize(), src );
ic.setInventorySlotContents( entry.getKey().getSlot(), stack.createItemStack() );
job.getNeededForLoop().add( stack.copy() );
}
for( int x = 0; x < ic.getSizeInventory(); x++ )
if( details.isCraftable() && stack.getItem().hasContainerItem( stack.getDefinition() ) )
{
ItemStack is = ic.getStackInSlot( x );
is = Platform.getContainerItem( is );
final IAEItemStack o = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createStack( is );
final ItemStack is = Platform.getContainerItem( stack.createItemStack() );
final IAEItemStack o = AEItemStack.fromItemStack( is );
if( o != null )
{
this.bytes++;
inv.injectItems( o, Actionable.MODULATE, src );
}
}
}
else
{
// request and remove inputs...
for( final Entry<CraftingTreeNode, Long> entry : this.nodes.object2LongEntrySet() )
{
final IAEItemStack item = entry.getKey().getStack( entry.getValue() );
final IAEItemStack stack = entry.getKey().request( inv, item.getStackSize() * i, src );
if( this.containerItems )
{
final ItemStack is = Platform.getContainerItem( stack.createItemStack() );
final IAEItemStack o = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createStack( is );
if( o != null )
if( containerItems == null )
{
this.bytes++;
inv.injectItems( o, Actionable.MODULATE, src );
containerItems = new ArrayList<>();
}
this.bytes++;
o.setCachedItemStack( is );
containerItems.add( o );
}
if( containerItems != null )
{
for( IAEItemStack i : containerItems )
{
inv.injectItems( i, Actionable.MODULATE, src );
}
}
}
}
// assume its possible.
// add crafting results..
for( final IAEItemStack out : this.details.getCondensedOutputs() )
{
final IAEItemStack o = out.copy();
o.setStackSize( o.getStackSize() * i );
o.setStackSize( o.getStackSize() * amountOfTimes );
inv.injectItems( o, Actionable.MODULATE, src );
}
this.crafts += i;
this.crafts += amountOfTimes;
}
void dive( final CraftingJob job )
{
job.addTask( this.getAmountCrafted( this.parent.getStack( 1 ) ), this.crafts, this.details, this.depth );
job.addTask( this.getAmountCrafted( this.parent.getStack( 1 ) ), this.crafts );
for( final Entry<CraftingTreeNode, Long> entry : this.nodes.object2LongEntrySet() )
{
entry.getKey().dive( job );
@@ -318,4 +284,9 @@ public class CraftingTreeProcess
entry.getKey().getPlan( plan );
}
}
public void reserveForNode()
{
parent.reserveForNode();
}
}
@@ -28,10 +28,14 @@ import appeng.api.storage.IStorageChannel;
import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList;
import appeng.me.helpers.PlayerSource;
import appeng.core.sync.network.NetworkHandler;
import appeng.core.sync.packets.PacketInformPlayer;
import appeng.util.inv.ItemListIgnoreCrafting;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.util.text.TextComponentString;
import java.io.IOException;
public class MECraftingInventory implements IMEInventory<IAEItemStack>
{
@@ -310,20 +314,23 @@ public class MECraftingInventory implements IMEInventory<IAEItemStack>
{
if( src.player().isPresent() )
{
if( result == null )
try
{
src.player().get().sendStatusMessage( new TextComponentString( "System reported " + extra.getStackSize() + " " + extra.getDefinition().getItem().getItemStackDisplayName( extra.getDefinition() ) + " available but could not extract anything" ), false );
if( result == null )
{
NetworkHandler.instance().sendTo( new PacketInformPlayer( extra ), (EntityPlayerMP) src.player().get() );
}
else
{
NetworkHandler.instance().sendTo( new PacketInformPlayer( extra, result ), (EntityPlayerMP) src.player().get() );
}
}
else
catch( IOException e )
{
src.player().get().sendStatusMessage( new TextComponentString( "System reported " + extra.getStackSize() + " " + extra.getDefinition().getItem().getItemStackDisplayName( extra.getDefinition() ) + " available but could only extract " + result.getStackSize() ), false );
e.printStackTrace();
}
}
failed = true;
if( !src.player().isPresent() )
{
break;
}
}
}
}
@@ -354,11 +361,6 @@ public class MECraftingInventory implements IMEInventory<IAEItemStack>
return true;
}
private void addMissing( final IAEItemStack extra )
{
this.missingCache.add( extra );
}
void ignore( final IAEItemStack what )
{
final IAEItemStack list = this.localCache.findPrecise( what );
@@ -367,4 +369,18 @@ public class MECraftingInventory implements IMEInventory<IAEItemStack>
list.setStackSize( 0 );
}
}
void reserve( final IAEItemStack what )
{
final IAEItemStack list = this.localCache.findPrecise( what );
if( list != null )
{
list.decStackSize( what.getStackSize() );
}
}
private void addMissing( final IAEItemStack extra )
{
this.missingCache.add( extra );
}
}
@@ -414,7 +414,7 @@ public class ContainerFluidTerminal extends AEBaseContainer implements IConfigMa
}
}
if( notInserted == null )
if( notInserted == null || notInserted.getStackSize() == 0 )
{
if( !player.inventory.addItemStackToInventory( fh.getContainer() ) )
{
@@ -19,39 +19,6 @@
package appeng.helpers;
import java.util.*;
import javax.annotation.Nullable;
import appeng.util.inv.BlockingInventoryAdaptor;
import appeng.util.*;
import appeng.util.inv.*;
import com.google.common.collect.ImmutableSet;
import com.google.common.primitives.Ints;
import de.ellpeck.actuallyadditions.api.tile.IPhantomTile;
import gregtech.api.block.machines.BlockMachine;
import gregtech.api.metatileentity.MetaTileEntity;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Items;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.wrapper.RangedWrapper;
import appeng.api.AEApi;
import appeng.api.config.Actionable;
import appeng.api.config.Settings;
@@ -75,11 +42,7 @@ import appeng.api.networking.ticking.IGridTickable;
import appeng.api.networking.ticking.TickRateModulation;
import appeng.api.networking.ticking.TickingRequest;
import appeng.api.parts.IPart;
import appeng.api.storage.IMEInventory;
import appeng.api.storage.IMEMonitor;
import appeng.api.storage.IStorageChannel;
import appeng.api.storage.IStorageMonitorable;
import appeng.api.storage.IStorageMonitorableAccessor;
import appeng.api.storage.*;
import appeng.api.storage.channels.IFluidStorageChannel;
import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEFluidStack;
@@ -101,7 +64,39 @@ import appeng.parts.automation.StackUpgradeInventory;
import appeng.parts.automation.UpgradeInventory;
import appeng.tile.inventory.AppEngInternalAEInventory;
import appeng.tile.inventory.AppEngInternalInventory;
import appeng.util.ConfigManager;
import appeng.util.IConfigManagerHost;
import appeng.util.InventoryAdaptor;
import appeng.util.Platform;
import appeng.util.inv.*;
import appeng.util.item.AEItemStack;
import com.google.common.collect.ImmutableSet;
import com.google.common.primitives.Ints;
import de.ellpeck.actuallyadditions.api.tile.IPhantomTile;
import gregtech.api.block.machines.BlockMachine;
import gregtech.api.metatileentity.MetaTileEntity;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Items;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.wrapper.RangedWrapper;
import javax.annotation.Nullable;
import java.util.*;
import static gregtech.api.block.machines.BlockMachine.getMetaTileEntity;
@@ -113,9 +108,7 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
public static final int NUMBER_OF_PATTERN_SLOTS = 36;
private static final Collection<Block> BAD_BLOCKS = new HashSet<>( 100 );
private final IAEItemStack[] requireWork = {
null, null, null, null, null, null, null, null, null
};
private final IAEItemStack[] requireWork = {null, null, null, null, null, null, null, null, null};
private final MultiCraftingTracker craftingTracker;
private final AENetworkProxy gridProxy;
private final IInterfaceHost iHost;
@@ -128,13 +121,13 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
private final MEMonitorPassThrough<IAEItemStack> items = new MEMonitorPassThrough<>( new NullInventory<IAEItemStack>(), AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) );
private final MEMonitorPassThrough<IAEFluidStack> fluids = new MEMonitorPassThrough<>( new NullInventory<IAEFluidStack>(), AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) );
private final UpgradeInventory upgrades;
private final Accessor accessor = new Accessor();
private boolean hasConfig = false;
private int priority;
private List<ICraftingPatternDetails> craftingList = null;
private List<ItemStack> waitingToSend = null;
private IMEInventory<IAEItemStack> destination;
private int isWorking = -1;
private final Accessor accessor = new Accessor();
private EnumSet<EnumFacing> visitedFaces = EnumSet.noneOf( EnumFacing.class );
private EnumMap<EnumFacing, List<ItemStack>> waitingToSendFacing = new EnumMap<>( EnumFacing.class );
private boolean resetConfigCache = true;
@@ -160,6 +153,11 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
this.interfaceRequestSource = new InterfaceRequestSource( this.iHost );
}
private static boolean invIsCustomBlocking( BlockingInventoryAdaptor inv )
{
return ( inv.containsBlockingItems() );
}
@Override
public void saveChanges()
{
@@ -281,6 +279,7 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
final NBTTagCompound waitingListSided = data.getCompoundTag( "sidedWaitList" );
for( EnumFacing s : EnumFacing.values() )
{
if( waitingListSided.hasKey( s.name() ) )
{
NBTTagList w = waitingListSided.getTagList( s.name(), 10 );
@@ -294,6 +293,7 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
}
}
}
}
this.craftingTracker.readFromNBT( data );
@@ -464,14 +464,7 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
}
try
{
if( removed )
{
this.gridProxy.getGrid().postEvent( new MENetworkCraftingPatternChange( this, this.gridProxy.getNode() ) );
}
else if( newPattern )
{
this.provideCrafting( (ICraftingProviderHelper) this.gridProxy.getCrafting() );
}
this.gridProxy.getGrid().postEvent( new MENetworkCraftingPatternChange( this, this.gridProxy.getNode() ) );
}
catch( GridAccessException e )
{
@@ -916,10 +909,6 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
changed = true;
throw new GridAccessException();
}
else
{
itemStack.setCachedItemStack( inputStack );
}
IAEItemStack storedStack = this.gridProxy.getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ).getStorageList().findPrecise( itemStack );
if( storedStack != null )
@@ -937,8 +926,13 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
}
else if( storedStack.isCraftable() )
{
itemStack.setCachedItemStack( inputStack );
changed = this.handleCrafting( x, adaptor, itemStack ) || changed;
}
if( acquired == null )
{
itemStack.setCachedItemStack( inputStack );
}
}
}
// else wtf?
@@ -1111,11 +1105,6 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
return ( inv.containsItems() );
}
private static boolean invIsCustomBlocking( BlockingInventoryAdaptor inv )
{
return ( inv.containsBlockingItems() );
}
@Override
public boolean pushPattern( final ICraftingPatternDetails patternDetails, final InventoryCrafting table )
{
@@ -1165,7 +1154,7 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
}
}
final InventoryAdaptor ad = InventoryAdaptor.getAdaptor( te, s.getOpposite() );
InventoryAdaptor ad = InventoryAdaptor.getAdaptor( te, s.getOpposite() );
if( ad != null )
{
if( this.isBlocking() )
@@ -1177,7 +1166,7 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
if( phantomTE.hasBoundPosition() )
{
TileEntity phantom = w.getTileEntity( phantomTE.getBoundPosition() );
if( NonBlockingItems.INSTANCE.getMap().containsKey( phantom.getBlockType().getRegistryName().getResourceDomain() ) )
if( NonBlockingItems.INSTANCE.getMap().containsKey( w.getBlockState( phantomTE.getBoundPosition() ).getBlock().getRegistryName().getResourceDomain() ) )
{
if( isCustomInvBlocking( phantom, s ) )
{
@@ -1187,7 +1176,7 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
}
}
}
else if( NonBlockingItems.INSTANCE.getMap().containsKey( te.getBlockType().getRegistryName().getResourceDomain() ) )
else if( NonBlockingItems.INSTANCE.getMap().containsKey( w.getBlockState( tile.getPos().offset( s ) ).getBlock().getRegistryName().getResourceDomain() ) )
{
if( isCustomInvBlocking( te, s ) )
{
@@ -1195,7 +1184,6 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
continue;
}
}
else if( invIsBlocked( ad ) )
{
visitedFaces.remove( s );
@@ -1255,7 +1243,7 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
if( phantomTE.hasBoundPosition() )
{
TileEntity phantom = w.getTileEntity( phantomTE.getBoundPosition() );
if( NonBlockingItems.INSTANCE.getMap().containsKey( phantom.getBlockType().getRegistryName().getResourceDomain() ) )
if( NonBlockingItems.INSTANCE.getMap().containsKey( w.getBlockState( phantomTE.getBoundPosition() ).getBlock().getRegistryName().getResourceDomain() ) )
{
if( !isCustomInvBlocking( phantom, s ) )
{
@@ -1265,8 +1253,7 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
}
}
}
else if( NonBlockingItems.INSTANCE.getMap().containsKey( te.getBlockType().getRegistryName().getResourceDomain() ) )
else if( NonBlockingItems.INSTANCE.getMap().containsKey( w.getBlockState( tile.getPos().offset( s ) ).getBlock().getRegistryName().getResourceDomain() ) )
{
if( !isCustomInvBlocking( te, s ) )
{
@@ -1274,11 +1261,13 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
break;
}
}
else if( !invIsBlocked( ad ) )
else
{
allAreBusy = false;
break;
if( !invIsBlocked( ad ) )
{
allAreBusy = false;
break;
}
}
}
}
@@ -1604,6 +1593,7 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
}
private class InterfaceRequestContext implements Comparable<Integer>
{
@@ -1614,6 +1604,7 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
}
}
private class InterfaceInventory extends MEMonitorIInventory
{
@@ -1651,6 +1642,7 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
}
}
private class Accessor implements IStorageMonitorableAccessor
{
@@ -2,6 +2,7 @@ package appeng.helpers;
import appeng.core.AEConfig;
import appeng.core.AELog;
import appeng.util.Platform;
import gregtech.api.items.metaitem.MetaItem;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
@@ -50,16 +51,19 @@ public class NonBlockingItems
continue;
}
if( ModItemMeta[0].equals( "gregtech" ) )
if( ModItemMeta[0].equals( "gregtech" ) && Platform.isModLoaded( "gregtech" ) )
{
boolean found = false;
for( MetaItem<?> metaItem : MetaItem.getMetaItems() )
{
MetaItem<?>.MetaValueItem metaItem2 = metaItem.getItem( ModItemMeta[1] );
if( metaItem.getItem( ModItemMeta[1] ) != null )
{
found = true;
ItemStack itemStack = metaItem2.getStackForm();
NON_BLOCKING_MAP.get( modid ).putIfAbsent( itemStack.getItem(), new IntOpenHashSet() );
NON_BLOCKING_MAP.get( modid ).computeIfPresent( itemStack.getItem(), ( item, intSet ) -> {
NON_BLOCKING_MAP.get( modid ).computeIfPresent( itemStack.getItem(), ( item, intSet ) ->
{
intSet.add( itemStack.getItemDamage() );
return intSet;
} );
@@ -70,28 +74,30 @@ public class NonBlockingItems
if( !itemStack.isEmpty() )
{
NON_BLOCKING_MAP.get( modid ).putIfAbsent( itemStack.getItem(), new IntOpenHashSet() );
NON_BLOCKING_MAP.get( modid ).computeIfPresent( itemStack.getItem(), ( item, intSet ) -> {
NON_BLOCKING_MAP.get( modid ).computeIfPresent( itemStack.getItem(), ( item, intSet ) ->
{
intSet.add( itemStack.getItemDamage() );
return intSet;
} );
}
else
{
AELog.error( "Item not found on nonBlocking config: " + s );
}
}
break;
}
if( !found )
{
AELog.error( "Item not found on nonBlocking config: " + s );
}
}
else if( ModItemMeta[0].equals( "ore" ) )
{
OreDictionary.getOres( ModItemMeta[1] ).forEach( itemStack -> {
NON_BLOCKING_MAP.get( modid ).putIfAbsent( itemStack.getItem(), new IntOpenHashSet() );
NON_BLOCKING_MAP.get( modid ).computeIfPresent( itemStack.getItem(), ( item, intSet ) -> {
intSet.add( itemStack.getItemDamage() );
return intSet;
} );
} );
OreDictionary.getOres( ModItemMeta[1] ).forEach( itemStack ->
{
NON_BLOCKING_MAP.get( modid ).putIfAbsent( itemStack.getItem(), new IntOpenHashSet() );
NON_BLOCKING_MAP.get( modid ).computeIfPresent( itemStack.getItem(), ( item, intSet ) ->
{
intSet.add( itemStack.getItemDamage() );
return intSet;
} );
} );
}
else
{
@@ -99,7 +105,8 @@ public class NonBlockingItems
if( !itemStack.isEmpty() )
{
NON_BLOCKING_MAP.get( modid ).putIfAbsent( itemStack.getItem(), new IntOpenHashSet() );
NON_BLOCKING_MAP.get( modid ).computeIfPresent( itemStack.getItem(), ( item, intSet ) -> {
NON_BLOCKING_MAP.get( modid ).computeIfPresent( itemStack.getItem(), ( item, intSet ) ->
{
intSet.add( itemStack.getItemDamage() );
return intSet;
} );
@@ -119,4 +126,8 @@ public class NonBlockingItems
{
return NON_BLOCKING_MAP;
}
public void init()
{
}
}
+54 -32
View File
@@ -40,6 +40,7 @@ import appeng.container.ContainerNull;
import appeng.util.Platform;
import appeng.util.item.AEItemStack;
import net.minecraftforge.common.crafting.IShapedRecipe;
import net.minecraftforge.fml.common.Optional;
public class PatternHelper implements ICraftingPatternDetails, Comparable<PatternHelper>
@@ -247,7 +248,7 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable<Patter
final TestStatus result = this.getStatus( slotIndex, i );
switch( result )
switch ( result )
{
case ACCEPT:
return true;
@@ -266,9 +267,11 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable<Patter
this.testFrame.setInventorySlotContents( slotIndex, i );
// If we cannot substitute, the items must match exactly
if (!canSubstitute && slotIndex < inputs.length) {
if (!inputs[slotIndex].isSameType(i)) {
this.markItemAs(slotIndex, i, TestStatus.DECLINE);
if( ( !( i.getItem().isDamageable() || Platform.isGTDamageableItem( i.getItem() ) ) && !canSubstitute ) && slotIndex < inputs.length )
{
if( !inputs[slotIndex].isSameType( i ) )
{
this.markItemAs( slotIndex, i, TestStatus.DECLINE );
return false;
}
}
@@ -326,23 +329,26 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable<Patter
}
@Override
public List<IAEItemStack> getSubstituteInputs(int slot) {
if (this.inputs[slot] == null) {
public List<IAEItemStack> getSubstituteInputs( int slot )
{
if( this.inputs[slot] == null )
{
return Collections.emptyList();
}
return this.substituteInputs.computeIfAbsent(slot, value -> {
ItemStack[] matchingStacks = getRecipeIngredient(slot).getMatchingStacks();
List<IAEItemStack> itemList = new ArrayList<>(matchingStacks.length + 1);
for (ItemStack matchingStack : matchingStacks) {
itemList.add(AEItemStack.fromItemStack(matchingStack));
return this.substituteInputs.computeIfAbsent( slot, value -> {
ItemStack[] matchingStacks = getRecipeIngredient( slot ).getMatchingStacks();
List<IAEItemStack> itemList = new ArrayList<>( matchingStacks.length + 1 );
for( ItemStack matchingStack : matchingStacks )
{
itemList.add( AEItemStack.fromItemStack( matchingStack ) );
}
// Ensure that the specific item put in by the user is at the beginning,
// so that it takes precedence over substitutions
itemList.add(0, this.inputs[slot]);
itemList.add( 0, this.inputs[slot] );
return itemList;
});
} );
}
/**
@@ -352,31 +358,40 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable<Patter
* ingredient list will be condensed to the actual recipe's grid size. In addition, in our 3x3 grid, the user can
* shift the actual recipe input to the right and down.
*/
private Ingredient getRecipeIngredient(int slot) {
private Ingredient getRecipeIngredient( int slot )
{
if (standardRecipe instanceof IShapedRecipe ) {
if( standardRecipe instanceof IShapedRecipe )
{
IShapedRecipe shapedRecipe = (IShapedRecipe) standardRecipe;
return getShapedRecipeIngredient(slot, shapedRecipe.getRecipeWidth());
} else {
return getShapelessRecipeIngredient(slot);
return getShapedRecipeIngredient( slot, shapedRecipe.getRecipeWidth() );
}
else
{
return getShapelessRecipeIngredient( slot );
}
}
private Ingredient getShapedRecipeIngredient(int slot, int recipeWidth) {
private Ingredient getShapedRecipeIngredient( int slot, int recipeWidth )
{
// Compute the offset of the user's input vs. crafting grid origin
// Which is >0 if they have empty rows above or to the left of their input
int topOffset = 0;
if (inputs[0] == null && inputs[1] == null && inputs[2] == null) {
if( inputs[0] == null && inputs[1] == null && inputs[2] == null )
{
topOffset++; // First row is fully empty
if (inputs[3] == null && inputs[4] == null && inputs[5] == null) {
if( inputs[3] == null && inputs[4] == null && inputs[5] == null )
{
topOffset++; // Second row is fully empty
}
}
int leftOffset = 0;
if (inputs[0] == null && inputs[3] == null && inputs[6] == null) {
if( inputs[0] == null && inputs[3] == null && inputs[6] == null )
{
leftOffset++; // First column is fully empty
if (inputs[1] == null && inputs[4] == null && inputs[7] == null) {
if( inputs[1] == null && inputs[4] == null && inputs[7] == null )
{
leftOffset++; // Second column is fully empty
}
}
@@ -390,32 +405,37 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable<Patter
NonNullList<Ingredient> ingredients = standardRecipe.getIngredients();
if (ingredientIndex < 0 || ingredientIndex > ingredients.size()) {
if( ingredientIndex < 0 || ingredientIndex > ingredients.size() )
{
return Ingredient.EMPTY;
}
return ingredients.get(ingredientIndex);
return ingredients.get( ingredientIndex );
}
private Ingredient getShapelessRecipeIngredient(int slot) {
private Ingredient getShapelessRecipeIngredient( int slot )
{
// We map the list of *filled* sparse inputs to the shapeless (ergo unordered)
// ingredients. While these do not actually correspond to each other,
// since both lists have the same length, the mapping is at least stable.
int ingredientIndex = 0;
for (int i = 0; i < slot; i++) {
if (inputs[i] != null) {
for( int i = 0; i < slot; i++ )
{
if( inputs[i] != null )
{
ingredientIndex++;
}
}
NonNullList<Ingredient> ingredients = standardRecipe.getIngredients();
if (ingredientIndex < ingredients.size()) {
return ingredients.get(ingredientIndex);
if( ingredientIndex < ingredients.size() )
{
return ingredients.get( ingredientIndex );
}
return Ingredient.EMPTY;
}
@Override
public ItemStack getOutput( final InventoryCrafting craftingInv, final World w )
{
@@ -517,7 +537,9 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable<Patter
private enum TestStatus
{
ACCEPT, DECLINE, TEST
ACCEPT,
DECLINE,
TEST
}
private static final class TestLookup
-21
View File
@@ -411,27 +411,6 @@ public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper
{
details.add( medium );
}
if( !updatePatterns )
{
List<IAEItemStack> newCraftables = new ArrayList<>();
ObjectSet<ICraftingPatternDetails> b = new ObjectRBTreeSet<>( COMPARATOR );
ImmutableList<ICraftingPatternDetails> a = this.craftableItems.get( api.getCondensedOutputs()[0] );
if( a != null )
{
b.addAll( this.craftableItems.get( api.getOutputs()[0] ) );
}
b.add( api );
for( IAEItemStack stack : api.getCondensedOutputs() )
{
IAEItemStack i = stack.copy().reset().setCraftable( true );
this.craftableItems.put( i, ImmutableList.copyOf( b ) );
newCraftables.add( i );
}
this.storageGrid.postCraftablesChanges( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ), newCraftables, new BaseActionSource() );
}
}
@Override
+34 -8
View File
@@ -19,13 +19,12 @@
package appeng.me.cache;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import appeng.api.storage.channels.IItemStorageChannel;
import appeng.crafting.MECraftingInventory;
import appeng.helpers.IInterfaceHost;
import appeng.helpers.IPriorityHost;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.SetMultimap;
@@ -55,6 +54,8 @@ import appeng.me.helpers.GenericInterestManager;
import appeng.me.helpers.MachineSource;
import appeng.me.storage.ItemWatcher;
import appeng.me.storage.NetworkInventoryHandler;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
public class GridStorageCache implements IStorageGrid
@@ -68,6 +69,8 @@ public class GridStorageCache implements IStorageGrid
private final HashMap<IGridNode, IStackWatcher> watchers = new HashMap<>();
private final Map<IStorageChannel<? extends IAEStack>, NetworkInventoryHandler<?>> storageNetworks;
private final Map<IStorageChannel<? extends IAEStack>, NetworkMonitor<?>> storageMonitors;
private MECraftingInventory localCache = null;
private final Int2ObjectMap<MECraftingInventory> extractableItemPriorityMap = new Int2ObjectOpenHashMap<>();
private int localDepth;
public GridStorageCache( final IGrid g )
@@ -82,6 +85,8 @@ public class GridStorageCache implements IStorageGrid
@Override
public void onUpdateTick()
{
this.localCache = null;
this.extractableItemPriorityMap.clear();
this.storageMonitors.forEach( ( channel, monitor ) -> monitor.onTick() );
}
@@ -169,6 +174,28 @@ public class GridStorageCache implements IStorageGrid
return (IMEMonitor<T>) this.storageMonitors.get( channel );
}
public MECraftingInventory getExtractableList( IActionSource src )
{
if( src instanceof MachineSource )
{
if( src.machine().isPresent() )
{
IActionHost machine = src.machine().get();
if( machine instanceof IInterfaceHost )
{
extractableItemPriorityMap.putIfAbsent( ( (IPriorityHost) machine ).getPriority(), new MECraftingInventory( getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ), src, false, false, false ) );
return extractableItemPriorityMap.get( ( (IPriorityHost) machine ).getPriority() );
}
}
}
if( localCache == null )
{
localCache = new MECraftingInventory( getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ), src, false, false, false );
}
return localCache;
}
private CellChangeTracker addCellProvider( final ICellProvider cc, final CellChangeTracker tracker )
{
if( this.inactiveCellProviders.contains( cc ) )
@@ -198,8 +225,7 @@ public class GridStorageCache implements IStorageGrid
final IActionSource actionSrc = cc instanceof IActionHost ? new MachineSource( (IActionHost) cc ) : new BaseActionSource();
this.storageMonitors.forEach( ( channel, monitor ) ->
{
this.storageMonitors.forEach( ( channel, monitor ) -> {
for( final IMEInventoryHandler<IAEItemStack> h : cc.getCellArray( channel ) )
{
tracker.postChanges( channel, -1, h, actionSrc );
@@ -19,22 +19,6 @@
package appeng.me.cluster.implementations;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import appeng.api.config.Upgrades;
import appeng.helpers.DualityInterface;
import appeng.helpers.PatternHelper;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.world.World;
import appeng.api.AEApi;
import appeng.api.config.Actionable;
import appeng.api.config.FuzzyMode;
@@ -43,14 +27,7 @@ import appeng.api.implementations.ICraftingPatternItem;
import appeng.api.networking.IGrid;
import appeng.api.networking.IGridHost;
import appeng.api.networking.IGridNode;
import appeng.api.networking.crafting.CraftingItemList;
import appeng.api.networking.crafting.ICraftingCPU;
import appeng.api.networking.crafting.ICraftingGrid;
import appeng.api.networking.crafting.ICraftingJob;
import appeng.api.networking.crafting.ICraftingLink;
import appeng.api.networking.crafting.ICraftingMedium;
import appeng.api.networking.crafting.ICraftingPatternDetails;
import appeng.api.networking.crafting.ICraftingRequester;
import appeng.api.networking.crafting.*;
import appeng.api.networking.energy.IEnergyGrid;
import appeng.api.networking.events.MENetworkCraftingCpuChange;
import appeng.api.networking.security.IActionSource;
@@ -63,11 +40,8 @@ import appeng.api.storage.data.IItemList;
import appeng.api.util.WorldCoord;
import appeng.container.ContainerNull;
import appeng.core.AELog;
import appeng.crafting.CraftBranchFailure;
import appeng.crafting.CraftingJob;
import appeng.crafting.CraftingLink;
import appeng.crafting.CraftingWatcher;
import appeng.crafting.MECraftingInventory;
import appeng.crafting.*;
import appeng.helpers.PatternHelper;
import appeng.me.cache.CraftingGridCache;
import appeng.me.cluster.IAECluster;
import appeng.me.helpers.MachineSource;
@@ -75,6 +49,17 @@ import appeng.tile.crafting.TileCraftingMonitorTile;
import appeng.tile.crafting.TileCraftingTile;
import appeng.util.Platform;
import appeng.util.item.AEItemStack;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.world.World;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;
public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
@@ -102,6 +87,7 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
private IAEItemStack finalOutput;
private boolean waiting = false;
private IItemList<IAEItemStack> waitingFor = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList();
private IItemList<IAEItemStack> neededForLoop = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList();
private long availableStorage = 0;
private MachineSource machineSrc = null;
private int accelerator = 0;
@@ -224,13 +210,10 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
public boolean canAccept( final IAEItemStack input )
{
if( input instanceof IAEItemStack )
if( input != null )
{
final IAEItemStack is = this.waitingFor.findPrecise( input );
if( is != null && is.getStackSize() > 0 )
{
return true;
}
return is != null && is.getStackSize() > 0;
}
return false;
}
@@ -239,7 +222,8 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
{
// also stop accepting items when the job is complete, i.e. to prevent re-insertion when pushing out
// items during storeItems
if (input == null || isComplete) {
if( input == null || isComplete )
{
return input;
}
@@ -303,9 +287,28 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
if( this.finalOutput.equals( what ) )
{
IAEItemStack isLoop = neededForLoop.findPrecise( finalOutput );
IAEItemStack leftover = what;
this.finalOutput.decStackSize( what.getStackSize() );
if( isLoop != null && isLoop.getStackSize() > 0 )
{
if( isLoop.getStackSize() >= what.getStackSize() )
{
leftover = this.inventory.injectItems( what.copy(), type, src );
isLoop.decStackSize( what.getStackSize() );
}
else
{
leftover = this.inventory.injectItems( what.copy().setStackSize( what.getStackSize() - isLoop.getStackSize() ), type, src );
isLoop.decStackSize( what.getStackSize() - isLoop.getStackSize() );
}
if( leftover == null )
{
return null;
}
}
this.finalOutput.decStackSize( leftover.getStackSize() );
if( this.myLastLink != null )
{
@@ -335,9 +338,28 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
if( this.finalOutput.equals( insert ) )
{
IAEItemStack isLoop = neededForLoop.findPrecise( finalOutput );
IAEItemStack leftover = input;
this.finalOutput.decStackSize( insert.getStackSize() );
if( isLoop != null && isLoop.getStackSize() > 0 )
{
if( isLoop.getStackSize() >= insert.getStackSize() )
{
leftover = this.inventory.injectItems( insert.copy(), type, src );
isLoop.decStackSize( insert.getStackSize() );
}
else
{
leftover = this.inventory.injectItems( insert.copy().setStackSize( insert.getStackSize() - isLoop.getStackSize() ), type, src );
isLoop.decStackSize( insert.getStackSize() - isLoop.getStackSize() );
}
if( leftover == null )
{
return null;
}
}
this.finalOutput.decStackSize( leftover.getStackSize() );
if( this.myLastLink != null )
{
@@ -375,7 +397,7 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
{
final ImmutableList<IAEItemStack> single = ImmutableList.of( diff.copy() );
while( i.hasNext() )
while ( i.hasNext() )
{
final Entry<IMEMonitorHandlerReceiver<IAEItemStack>, Object> o = i.next();
final IMEMonitorHandlerReceiver<IAEItemStack> receiver = o.getKey();
@@ -495,15 +517,14 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
return null;
}
private boolean canCraft(final ICraftingPatternDetails details, final IAEItemStack[] condensedInputs)
private boolean canCraft( final ICraftingPatternDetails details, final IAEItemStack[] condensedInputs )
{
if( !details.isCraftable() )
{
// Processing patterns are relatively easy
for ( IAEItemStack input : condensedInputs )
for( IAEItemStack input : condensedInputs )
{
final IAEItemStack ais = this.inventory.extractItems( input.copy(), Actionable.SIMULATE,
this.machineSrc );
final IAEItemStack ais = this.inventory.extractItems( input.copy(), Actionable.SIMULATE, this.machineSrc );
if( ais == null || ais.getStackSize() < input.getStackSize() )
{
@@ -516,7 +537,7 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
// When substitutions are allowed, we have to keep track of which items we've reserved
IAEItemStack[] inputs = details.getInputs();
Map<IAEItemStack, Integer> consumedCount = new HashMap<>();
for ( int i = 0; i < inputs.length; i++ )
for( int i = 0; i < inputs.length; i++ )
{
List<IAEItemStack> substitutes = details.getSubstituteInputs( i );
if( substitutes.isEmpty() )
@@ -525,9 +546,9 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
}
boolean found = false;
for ( IAEItemStack substitute : substitutes )
for( IAEItemStack substitute : substitutes )
{
for ( IAEItemStack fuzz : this.inventory.getItemList().findFuzzy( substitute, FuzzyMode.IGNORE_ALL ) )
for( IAEItemStack fuzz : this.inventory.getItemList().findFuzzy( substitute, FuzzyMode.IGNORE_ALL ) )
{
int alreadyConsumed = consumedCount.getOrDefault( fuzz, 0 );
if( fuzz.getStackSize() - alreadyConsumed <= 0 )
@@ -537,8 +558,7 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
fuzz = fuzz.copy();
fuzz.setStackSize( 1 ); // We're iterating over non condensed inputs which means there's 1 of each needed
final IAEItemStack ais = this.inventory.extractItems( fuzz, Actionable.SIMULATE,
this.machineSrc );
final IAEItemStack ais = this.inventory.extractItems( fuzz, Actionable.SIMULATE, this.machineSrc );
if( ais != null && ais.getStackSize() > 0 )
{
@@ -565,11 +585,11 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
{
// When no substitutions can occur, we can simply check that all items are accounted since
// each type of item should only occur once
for ( IAEItemStack g : condensedInputs )
for( IAEItemStack g : condensedInputs )
{
boolean found = false;
for ( IAEItemStack fuzz : this.inventory.getItemList().findFuzzy( g, FuzzyMode.IGNORE_ALL ) )
for( IAEItemStack fuzz : this.inventory.getItemList().findFuzzy( g, FuzzyMode.IGNORE_ALL ) )
{
fuzz = fuzz.copy();
fuzz.setStackSize( g.getStackSize() );
@@ -675,8 +695,7 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
{
this.somethingChanged = false;
this.executeCrafting( eg, cc );
}
while( this.somethingChanged && this.remainingOperations > 0 );
} while ( this.somethingChanged && this.remainingOperations > 0 );
}
this.usedOps[2] = this.usedOps[1];
this.usedOps[1] = this.usedOps[0];
@@ -692,7 +711,7 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
{
final Iterator<Entry<ICraftingPatternDetails, TaskProgress>> i = this.tasks.entrySet().iterator();
while( i.hasNext() )
while ( i.hasNext() )
{
final Entry<ICraftingPatternDetails, TaskProgress> e = i.next();
@@ -708,12 +727,12 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
{
InventoryCrafting ic = null;
if (!visitedMediums.containsKey( details ) || visitedMediums.get( details ).isEmpty())
if( !visitedMediums.containsKey( details ) || visitedMediums.get( details ).isEmpty() )
{
visitedMediums.put( details, new ArrayDeque<>( cc.getMediums( details ).stream().filter( Objects::nonNull ).collect( Collectors.toList()) ) );
visitedMediums.put( details, new ArrayDeque<>( cc.getMediums( details ).stream().filter( Objects::nonNull ).collect( Collectors.toList() ) ) );
}
while (!visitedMediums.get( details ).isEmpty())
while ( !visitedMediums.get( details ).isEmpty() )
{
ICraftingMedium m = visitedMediums.get( details ).poll();
@@ -773,52 +792,58 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
{
itemList.addAll( this.inventory.getItemList().findFuzzy( stack, FuzzyMode.IGNORE_ALL ) );
}
} else {
itemList = new ArrayList<>(1);
}
else
{
itemList = new ArrayList<>( 1 );
final IAEItemStack item = this.inventory.getItemList()
.findPrecise(input[x]);
final IAEItemStack item = this.inventory.getItemList().findPrecise( input[x] );
if (item != null) {
itemList.add(item);
if( item != null )
{
itemList.add( item );
}
}
for (IAEItemStack fuzz : itemList) {
for( IAEItemStack fuzz : itemList )
{
fuzz = fuzz.copy();
fuzz.setStackSize(input[x].getStackSize());
fuzz.setStackSize( input[x].getStackSize() );
if (details.isValidItemForSlot(x, fuzz.createItemStack(),
this.getWorld())) {
final IAEItemStack ais = this.inventory.extractItems(fuzz,
Actionable.MODULATE, this.machineSrc);
final ItemStack is = ais == null ? ItemStack.EMPTY
: ais.createItemStack();
if( details.isValidItemForSlot( x, fuzz.createItemStack(), this.getWorld() ) )
{
final IAEItemStack ais = this.inventory.extractItems( fuzz, Actionable.MODULATE, this.machineSrc );
final ItemStack is = ais == null ? ItemStack.EMPTY : ais.createItemStack();
if (!is.isEmpty()) {
this.postChange(AEItemStack.fromItemStack(is), this.machineSrc);
ic.setInventorySlotContents(x, is);
if( !is.isEmpty() )
{
this.postChange( AEItemStack.fromItemStack( is ), this.machineSrc );
ic.setInventorySlotContents( x, is );
found = true;
break;
}
}
}
} else {
final IAEItemStack ais = this.inventory.extractItems(input[x].copy(),
Actionable.MODULATE, this.machineSrc);
}
else
{
final IAEItemStack ais = this.inventory.extractItems( input[x].copy(), Actionable.MODULATE, this.machineSrc );
final ItemStack is = ais == null ? ItemStack.EMPTY : ais.createItemStack();
if (!is.isEmpty()) {
this.postChange(input[x], this.machineSrc);
ic.setInventorySlotContents(x, is);
if (is.getCount() == input[x].getStackSize()) {
if( !is.isEmpty() )
{
this.postChange( input[x], this.machineSrc );
ic.setInventorySlotContents( x, is );
if( is.getCount() == input[x].getStackSize() )
{
found = true;
continue;
}
}
}
if (!found) {
if( !found )
{
break;
}
}
@@ -902,7 +927,7 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
private void storeItems()
{
Preconditions.checkState(isComplete, "CPU should be complete to prevent re-insertion when dumping items");
Preconditions.checkState( isComplete, "CPU should be complete to prevent re-insertion when dumping items" );
final IGrid g = this.getGrid();
if( g == null )
@@ -962,10 +987,12 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
try
{
this.waitingFor.resetStatus();
this.neededForLoop.resetStatus();
( (CraftingJob) job ).getTree().setJob( ci, this, src );
if( ci.commit( src ) )
{
this.finalOutput = job.getOutput();
this.neededForLoop = ( (CraftingJob) job ).getNeededForLoop();
this.waiting = false;
this.isComplete = false;
this.markDirty();
@@ -1016,8 +1043,7 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
public boolean isBusy()
{
this.tasks.entrySet().removeIf(
taskProgressEntry -> taskProgressEntry.getValue().value <= 0 );
this.tasks.entrySet().removeIf( taskProgressEntry -> taskProgressEntry.getValue().value <= 0 );
if( !this.waitingFor.isEmpty() || !this.tasks.isEmpty() )
{
@@ -1075,8 +1101,7 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
final int hash = System.identityHashCode( this );
final int hmm = this.finalOutput == null ? 0 : this.finalOutput.hashCode();
return Long.toString( now, Character.MAX_RADIX ) + '-' + Integer.toString( hash, Character.MAX_RADIX ) + '-' + Integer.toString( hmm,
Character.MAX_RADIX );
return Long.toString( now, Character.MAX_RADIX ) + '-' + Integer.toString( hash, Character.MAX_RADIX ) + '-' + Integer.toString( hmm, Character.MAX_RADIX );
}
private NBTTagCompound generateLinkData( final String craftingID, final boolean standalone, final boolean req )
@@ -1103,7 +1128,7 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
public void getListOfItem( final IItemList<IAEItemStack> list, final CraftingItemList whichList )
{
switch( whichList )
switch ( whichList )
{
case ACTIVE:
for( final IAEItemStack ais : this.waitingFor )
@@ -1174,7 +1199,7 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
{
IAEItemStack is;
switch( storage2 )
switch ( storage2 )
{
case STORAGE:
is = this.inventory.getItemList().findPrecise( what );
@@ -19,7 +19,6 @@
package appeng.parts.misc;
import javax.annotation.Nullable;
import appeng.api.AEApi;
import appeng.api.config.AccessRestriction;
import appeng.api.config.Actionable;
@@ -147,6 +146,7 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
}
ItemStack extracted;
int stackSizeCurrentSlot = stackInInventorySlot.getCount();
int remainingCurrentSlot = Math.min( remainingSize, stackSizeCurrentSlot );
@@ -155,9 +155,17 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
do
{
extracted = this.itemHandler.extractItem( i, remainingCurrentSlot, simulate );
if( !extracted.isEmpty() )
{
// In order to guard against broken IItemHandler implementations, we'll try to guess if the returned
// stack (especially in simulate mode) is the same that was returned by getStackInSlot. This is
// obviously not a precise science, but it would catch the previous Forge bug:
// https://github.com/MinecraftForge/MinecraftForge/pull/6580
if( extracted == stackInInventorySlot )
{
extracted = extracted.copy();
}
if( extracted.getCount() > remainingCurrentSlot )
{
// Something broke. It should never return more than we requested...
@@ -166,12 +174,17 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
extracted.setCount( remainingCurrentSlot );
}
// We're just gonna use the first stack we get our hands on as the template for the rest.
// In case some stupid itemhandler (aka forge) returns an internal state we have to do a second
// expensive copy again.
// Heuristic for simulation: looping in case of simulations is pointless, since the state of the
// underlying inventory does not change after a simulated extraction. To still support inventories
// that report stacks that are larger than maxStackSize, we use this heuristic
if( simulate && extracted.getCount() == extracted.getMaxStackSize() && remainingCurrentSlot > extracted.getMaxStackSize() )
{
extracted.setCount( remainingCurrentSlot );
}
if( gathered.isEmpty() )
{
gathered = extracted.copy();
gathered = extracted;
}
else
{
@@ -179,11 +192,9 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
}
remainingCurrentSlot -= extracted.getCount();
}
} while ( !extracted.isEmpty() && remainingCurrentSlot > 0 );
} while ( !simulate && !extracted.isEmpty() && remainingCurrentSlot > 0 );
remainingSize -= stackSizeCurrentSlot - remainingCurrentSlot;
// Done?
if( remainingSize <= 0 )
{
break;
@@ -128,7 +128,7 @@ public class TileChest extends AENetworkPowerTile implements IMEChest, ITerminal
public TileChest()
{
this.setInternalMaxPower( PowerMultiplier.CONFIG.multiply( 40 ) );
this.setInternalMaxPower( PowerMultiplier.CONFIG.multiply( 128 ) );
this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL );
this.config.registerSetting( Settings.SORT_BY, SortOrder.NAME );
this.config.registerSetting( Settings.VIEW_MODE, ViewItems.ALL );
@@ -541,7 +541,7 @@ public class TileChest extends AENetworkPowerTile implements IMEChest, ITerminal
if( this.cellHandler != null && this.cellHandler.getChannel() == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) )
{
final IAEItemStack returns = Platform.poweredInsert( this, this.cellHandler,
AEItemStack.fromItemStack( this.inputInventory.getStackInSlot( 0 ) ), this.mySrc );
AEItemStack.fromItemStack( this.inputInventory.getStackInSlot( 0 ) ), this.mySrc );
if( returns == null )
{
@@ -698,7 +698,8 @@ public class TileChest extends AENetworkPowerTile implements IMEChest, ITerminal
{
TileChest.this.getProxy().getStorage().postAlterationOfStoredItems( this.chan, change, TileChest.this.mySrc );
}
} catch ( final GridAccessException e )
}
catch( final GridAccessException e )
{
// :(
}
@@ -738,11 +739,11 @@ public class TileChest extends AENetworkPowerTile implements IMEChest, ITerminal
return input;
}
T injected = super.injectItems( input, mode, src );
if (mode == Actionable.MODULATE && ( injected == null || injected.getStackSize() != input.getStackSize() ))
if( mode == Actionable.MODULATE && ( injected == null || injected.getStackSize() != input.getStackSize() ) )
{
if( TileChest.this.getProxy().isActive() && this.getInternalHandler().getCellInv() != null )
if( TileChest.this.isPowered() && this.getInternalHandler().getCellInv() != null )
{
TileChest.this.cellHandler.postChangesToListeners(Collections.singletonList( input.copy().setStackSize( input.getStackSize() - ( injected == null ? 0 : injected.getStackSize() ) ) ), TileChest.this.mySrc );
TileChest.this.cellHandler.postChangesToListeners( Collections.singletonList( input.copy().setStackSize( input.getStackSize() - ( injected == null ? 0 : injected.getStackSize() ) ) ), TileChest.this.mySrc );
}
}
return injected;
@@ -792,9 +793,9 @@ public class TileChest extends AENetworkPowerTile implements IMEChest, ITerminal
T extracted = super.extractItems( request, mode, src );
if( mode == Actionable.MODULATE && extracted != null )
{
if( TileChest.this.getProxy().isActive() && this.getInternalHandler().getCellInv() != null )
if( TileChest.this.isPowered() && this.getInternalHandler().getCellInv() != null )
{
TileChest.this.cellHandler.postChangesToListeners(Collections.singletonList( request.copy().setStackSize( -extracted.getStackSize() ) ), TileChest.this.mySrc );
TileChest.this.cellHandler.postChangesToListeners( Collections.singletonList( request.copy().setStackSize( -extracted.getStackSize() ) ), TileChest.this.mySrc );
}
}
return extracted;
@@ -848,7 +849,7 @@ public class TileChest extends AENetworkPowerTile implements IMEChest, ITerminal
private class FluidHandler implements IFluidHandler
{
private final IFluidTankProperties[] TANK_PROPS = new IFluidTankProperties[] { new FluidTankProperties( null, Fluid.BUCKET_VOLUME ) };
private final IFluidTankProperties[] TANK_PROPS = new IFluidTankProperties[]{new FluidTankProperties( null, Fluid.BUCKET_VOLUME )};
@Override
public int fill( final FluidStack resource, final boolean doFill )
@@ -858,7 +859,7 @@ public class TileChest extends AENetworkPowerTile implements IMEChest, ITerminal
.getChannel() == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) )
{
final IAEFluidStack results = Platform.poweredInsert( TileChest.this, TileChest.this.cellHandler, AEFluidStack.fromFluidStack( resource ),
TileChest.this.mySrc, doFill ? Actionable.MODULATE : Actionable.SIMULATE );
TileChest.this.mySrc, doFill ? Actionable.MODULATE : Actionable.SIMULATE );
if( results == null )
{
+60 -51
View File
@@ -36,6 +36,9 @@ import com.google.common.base.Preconditions;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import gregtech.api.items.IToolItem;
import ic2.api.item.IC2Items;
import ic2.api.item.ICustomDamageItem;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
@@ -73,6 +76,7 @@ import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.Optional;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.minecraftforge.oredict.OreDictionary;
@@ -134,6 +138,8 @@ import appeng.util.prioritylist.IPartitionList;
* @version rv2
* @since rv0
*/
@Optional.Interface( iface = "gregtech.api.items.IToolItem", modid = "gregtech" )
@Optional.Interface( iface = "ic2.api.item.ICustomDamageItem", modid = "IC2" )
public class Platform
{
@@ -176,9 +182,8 @@ public class Platform
/**
* This displays the value for encoded longs ( double *100 )
*
* @param n to be formatted long value
* @param n to be formatted long value
* @param isRate if true it adds a /t to the formatted string
*
* @return formatted long value
*/
public static String formatPowerLong( final long n, final boolean isRate )
@@ -188,12 +193,14 @@ public class Platform
final PowerUnits displayUnits = AEConfig.instance().selectedPowerUnit();
p = PowerUnits.AE.convertTo( displayUnits, p );
final String[] preFixes = { "k", "M", "G", "T", "P", "T", "P", "E", "Z", "Y" };
final String[] preFixes = {
"k", "M", "G", "T", "P", "T", "P", "E", "Z", "Y"
};
String unitName = displayUnits.name();
String level = "";
int offset = 0;
while( p > 1000 && offset < preFixes.length )
while ( p > 1000 && offset < preFixes.length )
{
p /= 1000;
level = preFixes[offset];
@@ -210,7 +217,7 @@ public class Platform
final int west_y = forward.zOffset * up.xOffset - forward.xOffset * up.zOffset;
final int west_z = forward.xOffset * up.yOffset - forward.yOffset * up.xOffset;
switch( west_x + west_y * 2 + west_z * 3 )
switch ( west_x + west_y * 2 + west_z * 3 )
{
case 1:
return AEPartLocation.EAST;
@@ -237,7 +244,7 @@ public class Platform
final int west_y = forward.getFrontOffsetZ() * up.getFrontOffsetX() - forward.getFrontOffsetX() * up.getFrontOffsetZ();
final int west_z = forward.getFrontOffsetX() * up.getFrontOffsetY() - forward.getFrontOffsetY() * up.getFrontOffsetX();
switch( west_x + west_y * 2 + west_z * 3 )
switch ( west_x + west_y * 2 + west_z * 3 )
{
case 1:
return EnumFacing.EAST;
@@ -271,8 +278,7 @@ public class Platform
{
ce = nextEnum( ce );
}
}
while( !validOptions.contains( ce ) || isNotValidSetting( ce ) );
} while ( !validOptions.contains( ce ) || isNotValidSetting( ce ) );
return ce;
}
@@ -446,7 +452,7 @@ public class Platform
{
if( upAndDown )
{
switch( dir )
switch ( dir )
{
case NORTH:
return AEPartLocation.SOUTH;
@@ -466,7 +472,7 @@ public class Platform
}
else
{
switch( dir )
switch ( dir )
{
case UP:
return AEPartLocation.DOWN;
@@ -519,8 +525,7 @@ public class Platform
final double offset_x = ( getRandomInt() % 32 - 16 ) / 82;
final double offset_y = ( getRandomInt() % 32 - 16 ) / 82;
final double offset_z = ( getRandomInt() % 32 - 16 ) / 82;
final EntityItem ei = new EntityItem( w, 0.5 + offset_x + pos.getX(), 0.5 + offset_y + pos.getY(), 0.2 + offset_z + pos.getZ(), i
.copy() );
final EntityItem ei = new EntityItem( w, 0.5 + offset_x + pos.getX(), 0.5 + offset_y + pos.getY(), 0.2 + offset_z + pos.getZ(), i.copy() );
w.spawnEntity( ei );
}
}
@@ -592,8 +597,7 @@ public class Platform
try
{
ITooltipFlag.TooltipFlags tooltipFlag = Minecraft
.getMinecraft().gameSettings.advancedItemTooltips ? ITooltipFlag.TooltipFlags.ADVANCED : ITooltipFlag.TooltipFlags.NORMAL;
ITooltipFlag.TooltipFlags tooltipFlag = Minecraft.getMinecraft().gameSettings.advancedItemTooltips ? ITooltipFlag.TooltipFlags.ADVANCED : ITooltipFlag.TooltipFlags.NORMAL;
return itemStack.getTooltip( Minecraft.getMinecraft().player, tooltipFlag );
}
catch( final Exception errB )
@@ -764,7 +768,7 @@ public class Platform
public static int MC2MEColor( final int color )
{
switch( color )
switch ( color )
{
case 4: // "blue"
return 0;
@@ -842,10 +846,10 @@ public class Platform
return forward;
}
switch( forward )
switch ( forward )
{
case DOWN:
switch( axis )
switch ( axis )
{
case DOWN:
return forward;
@@ -864,7 +868,7 @@ public class Platform
}
break;
case UP:
switch( axis )
switch ( axis )
{
case NORTH:
return AEPartLocation.WEST;
@@ -879,7 +883,7 @@ public class Platform
}
break;
case NORTH:
switch( axis )
switch ( axis )
{
case UP:
return AEPartLocation.WEST;
@@ -894,7 +898,7 @@ public class Platform
}
break;
case SOUTH:
switch( axis )
switch ( axis )
{
case UP:
return AEPartLocation.EAST;
@@ -909,7 +913,7 @@ public class Platform
}
break;
case EAST:
switch( axis )
switch ( axis )
{
case UP:
return AEPartLocation.NORTH;
@@ -923,7 +927,7 @@ public class Platform
break;
}
case WEST:
switch( axis )
switch ( axis )
{
case UP:
return AEPartLocation.SOUTH;
@@ -944,10 +948,10 @@ public class Platform
public static EnumFacing rotateAround( final EnumFacing forward, final EnumFacing axis )
{
switch( forward )
switch ( forward )
{
case DOWN:
switch( axis )
switch ( axis )
{
case DOWN:
return forward;
@@ -966,7 +970,7 @@ public class Platform
}
break;
case UP:
switch( axis )
switch ( axis )
{
case NORTH:
return EnumFacing.WEST;
@@ -981,7 +985,7 @@ public class Platform
}
break;
case NORTH:
switch( axis )
switch ( axis )
{
case UP:
return EnumFacing.WEST;
@@ -996,7 +1000,7 @@ public class Platform
}
break;
case SOUTH:
switch( axis )
switch ( axis )
{
case UP:
return EnumFacing.EAST;
@@ -1011,7 +1015,7 @@ public class Platform
}
break;
case EAST:
switch( axis )
switch ( axis )
{
case UP:
return EnumFacing.NORTH;
@@ -1025,7 +1029,7 @@ public class Platform
break;
}
case WEST:
switch( axis )
switch ( axis )
{
case UP:
return EnumFacing.SOUTH;
@@ -1101,9 +1105,7 @@ public class Platform
final Vec3d vec31 = vec3.addVector( f7 * d3, f6 * d3, f8 * d3 );
final AxisAlignedBB bb = new AxisAlignedBB( Math.min( vec3.x, vec31.x ), Math.min( vec3.y, vec31.y ), Math.min( vec3.z,
vec31.z ), Math.max( vec3.x, vec31.x ), Math.max( vec3.y, vec31.y ), Math.max( vec3.z, vec31.z ) ).grow(
16, 16, 16 );
final AxisAlignedBB bb = new AxisAlignedBB( Math.min( vec3.x, vec31.x ), Math.min( vec3.y, vec31.y ), Math.min( vec3.z, vec31.z ), Math.max( vec3.x, vec31.x ), Math.max( vec3.y, vec31.y ), Math.max( vec3.z, vec31.z ) ).grow( 16, 16, 16 );
Entity entity = null;
double closest = 9999999.0D;
@@ -1249,15 +1251,15 @@ public class Platform
final T leftover = input.copy();
final T split = input.copy();
leftover.decStackSize(itemToAdd);
split.setStackSize(itemToAdd);
leftover.add(cell.injectItems(split, Actionable.MODULATE, src));
leftover.decStackSize( itemToAdd );
split.setStackSize( itemToAdd );
leftover.add( cell.injectItems( split, Actionable.MODULATE, src ) );
src.player().ifPresent( player ->
{
final long diff = original - leftover.getStackSize();
Stats.ItemsInserted.addToPlayer( player, (int) diff );
} );
{
final long diff = original - leftover.getStackSize();
Stats.ItemsInserted.addToPlayer( player, (int) diff );
} );
return leftover;
}
@@ -1265,10 +1267,10 @@ public class Platform
final T ret = cell.injectItems( input, Actionable.MODULATE, src );
src.player().ifPresent( player ->
{
final long diff = ret == null ? input.getStackSize() : input.getStackSize() - ret.getStackSize();
Stats.ItemsInserted.addToPlayer( player, (int) diff );
} );
{
final long diff = ret == null ? input.getStackSize() : input.getStackSize() - ret.getStackSize();
Stats.ItemsInserted.addToPlayer( player, (int) diff );
} );
return ret;
}
@@ -1282,7 +1284,7 @@ public class Platform
return input;
}
@SuppressWarnings( { "rawtypes", "unchecked" } )
@SuppressWarnings( {"rawtypes", "unchecked"} )
public static void postChanges( final IStorageGrid gs, final ItemStack removed, final ItemStack added, final IActionSource src )
{
for( final IStorageChannel<?> chan : AEApi.instance().storage().storageChannels() )
@@ -1361,8 +1363,7 @@ public class Platform
final String locationA = a.getGridBlock().isWorldAccessible() ? a.getGridBlock().getLocation().toString() : "notInWorld";
final String locationB = b.getGridBlock().isWorldAccessible() ? b.getGridBlock().getLocation().toString() : "notInWorld";
AELog.info( "Audit: Node A [isSecure=%b, key=%d, playerID=%d, location={%s}] vs Node B[isSecure=%b, key=%d, playerID=%d, location={%s}]",
a_isSecure, a.getLastSecurityKey(), a.getPlayerID(), locationA, b_isSecure, b.getLastSecurityKey(), b.getPlayerID(), locationB );
AELog.info( "Audit: Node A [isSecure=%b, key=%d, playerID=%d, location={%s}] vs Node B[isSecure=%b, key=%d, playerID=%d, location={%s}]", a_isSecure, a.getLastSecurityKey(), a.getPlayerID(), locationA, b_isSecure, b.getLastSecurityKey(), b.getPlayerID(), locationB );
}
// can't do that son...
@@ -1423,7 +1424,7 @@ public class Platform
float yaw = 0.0f;
// player.yOffset = 1.8f;
switch( side )
switch ( side )
{
case DOWN:
pitch = 90.0f;
@@ -1513,16 +1514,14 @@ public class Platform
}
}
final boolean checkFuzzy = ae_req.getOre().isPresent() || providedTemplate.getItemDamage() == OreDictionary.WILDCARD_VALUE || providedTemplate
.hasTagCompound() || providedTemplate.isItemStackDamageable();
final boolean checkFuzzy = ae_req.getOre().isPresent() || providedTemplate.getItemDamage() == OreDictionary.WILDCARD_VALUE || providedTemplate.hasTagCompound() || providedTemplate.isItemStackDamageable();
if( items != null && checkFuzzy )
{
for( final IAEItemStack x : items )
{
final ItemStack sh = x.getDefinition();
if( ( Platform.itemComparisons().isEqualItemType( providedTemplate, sh ) || ae_req.sameOre( x ) ) && !ItemStack.areItemsEqual( sh,
output ) )
if( ( Platform.itemComparisons().isEqualItemType( providedTemplate, sh ) || ae_req.sameOre( x ) ) && !ItemStack.areItemsEqual( sh, output ) )
{ // Platform.isSameItemType( sh, providedTemplate )
final ItemStack cp = sh.copy();
cp.setCount( 1 );
@@ -1681,4 +1680,14 @@ public class Platform
return isPurified;
}
public static boolean isGTDamageableItem( Item item )
{
return ( isModLoaded( "gregtech" ) && item instanceof IToolItem );
}
public static boolean isIC2DamageableItem( Item item )
{
return ( isModLoaded( "IC2" ) && item instanceof ICustomDamageItem );
}
}
@@ -1,20 +1,12 @@
package appeng.util.inv;
import appeng.api.config.FuzzyMode;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList;
import appeng.helpers.NonBlockingItems;
import appeng.util.Platform;
import appeng.util.item.AEItemStack;
import gregtech.common.items.MetaTool;
import it.unimi.dsi.fastutil.ints.IntSet;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.items.IItemHandler;
import java.util.Collection;
import java.util.Iterator;
+50 -24
View File
@@ -18,7 +18,6 @@
package appeng.util.item;
import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@@ -27,6 +26,8 @@ import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.common.primitives.Ints;
import gregtech.api.items.IToolItem;
import ic2.api.item.ICustomDamageItem;
import io.netty.buffer.ByteBuf;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
@@ -44,7 +45,7 @@ import appeng.core.Api;
import appeng.util.Platform;
public final class AEItemStack extends AEStack<IAEItemStack> implements IAEItemStack
public class AEItemStack extends AEStack<IAEItemStack> implements IAEItemStack
{
private static final String NBT_STACKSIZE = "Cnt";
private static final String NBT_REQUESTABLE = "Req";
@@ -280,26 +281,17 @@ public final class AEItemStack extends AEStack<IAEItemStack> implements IAEItemS
@Override
public ItemStack getCachedItemStack( long stackSize )
{
ItemStack currentCached = null;
if( this.cachedItemStack != null )
{
currentCached = this.cachedItemStack;
if( Platform.itemComparisons().isSameItem( this.getDefinition(), this.cachedItemStack ) )
{
ItemStack currentCached = this.cachedItemStack;
this.cachedItemStack = null;
currentCached.setCount( Ints.saturatedCast( stackSize ) );
return currentCached;
}
}
ItemStack itemStack;
if( currentCached != null )
{
// Cache is suitable, just update the count
itemStack = currentCached;
currentCached.setCount( Ints.saturatedCast( stackSize ) );
}
else
{
// We need a new stack :-(
itemStack = this.createItemStack();
}
return itemStack;
return ItemHandlerHelper.copyStackWithSize( this.getDefinition(), Ints.saturatedCast( stackSize ) );
}
@Override
@@ -370,20 +362,53 @@ public final class AEItemStack extends AEStack<IAEItemStack> implements IAEItemS
private boolean fuzzyItemStackComparison( ItemStack a, ItemStack b, FuzzyMode mode )
{
if( a.getItem() == b.getItem() && a.getItem().isDamageable() )
if( a.getItem() == b.getItem() && ( a.getItem().isDamageable() || Platform.isGTDamageableItem( a.getItem() ) ) )
{
if( mode == FuzzyMode.IGNORE_ALL )
{
return true;
if( a.getItem().isDamageable() )
{
return true;
}
else if( Platform.isGTDamageableItem( a.getItem() ) )
{
return a.getItemDamage() == b.getItemDamage();
}
}
else if( mode == FuzzyMode.PERCENT_99 )
{
return a.getItemDamage() > 1 == b.getItemDamage() > 1;
if( Platform.isIC2DamageableItem( a.getItem() ) )
{
return ( (ICustomDamageItem) a.getItem() ).getCustomDamage( a ) > 1 == ( (ICustomDamageItem) b.getItem() ).getCustomDamage( b ) > 1;
}
else if( a.getItem().isDamageable() )
{
return a.getItemDamage() > 1 == b.getItemDamage() > 1;
}
else if( Platform.isGTDamageableItem( a.getItem() ) )
{
return ( (IToolItem) a.getItem() ).getItemDamage( a ) > 1 == ( (IToolItem) b.getItem() ).getItemDamage( b ) > 1;
}
}
else
{
final float percentDamageOfA = (float) a.getItemDamage() / a.getMaxDamage();
final float percentDamageOfB = (float) b.getItemDamage() / b.getMaxDamage();
float percentDamageOfA = 0;
float percentDamageOfB = 0;
if( Platform.isIC2DamageableItem( a.getItem() ) )
{
percentDamageOfA = (float) ( (ICustomDamageItem) a.getItem() ).getCustomDamage( a ) / ( (ICustomDamageItem) a.getItem() ).getMaxCustomDamage( a );
percentDamageOfB = (float) ( (ICustomDamageItem) b.getItem() ).getCustomDamage( b ) / ( (ICustomDamageItem) b.getItem() ).getMaxCustomDamage( b );
}
else if( a.getItem().isDamageable() )
{
percentDamageOfA = (float) a.getItemDamage() / a.getMaxDamage();
percentDamageOfB = (float) b.getItemDamage() / b.getMaxDamage();
}
else if( Platform.isGTDamageableItem( a.getItem() ) )
{
percentDamageOfA = (float) ( (IToolItem) a.getItem() ).getItemDamage( a ) / ( (IToolItem) a.getItem() ).getMaxItemDamage( a );
percentDamageOfB = (float) ( (IToolItem) b.getItem() ).getItemDamage( b ) / ( (IToolItem) b.getItem() ).getMaxItemDamage( b );
}
return percentDamageOfA > mode.breakPoint == percentDamageOfB > mode.breakPoint;
}
@@ -391,4 +416,5 @@ public final class AEItemStack extends AEStack<IAEItemStack> implements IAEItemS
return false;
}
}
@@ -25,7 +25,8 @@ import java.util.Map;
import appeng.util.Platform;
import com.google.common.base.Preconditions;
import gregtech.common.items.MetaTool;
import gregtech.api.items.IToolItem;
import ic2.api.item.ICustomDamageItem;
import net.minecraft.item.ItemStack;
import it.unimi.dsi.fastutil.objects.Object2ObjectAVLTreeMap;
@@ -34,159 +35,210 @@ import it.unimi.dsi.fastutil.objects.Object2ObjectSortedMap;
import appeng.api.config.FuzzyMode;
import appeng.api.storage.data.IAEItemStack;
/**
* This variant list is optimized for damageable items, and supports selecting durability ranges with
* {@link #findFuzzy(IAEItemStack, FuzzyMode)}.
*/
class FuzzyItemVariantList extends ItemVariantList {
class FuzzyItemVariantList extends ItemVariantList
{
static final SharedStackComparator COMPARATOR = new SharedStackComparator();
static final SharedStackComparator COMPARATOR = new SharedStackComparator();
// NOTE: We only use Object as they key here so we can pass our special DamageBounds to the subMap method.
// We NEVER put any keys in this map that are not AESharedItemStacks.
private final Object2ObjectSortedMap<Object, IAEItemStack> records = new Object2ObjectAVLTreeMap<>(COMPARATOR);
// NOTE: We only use Object as they key here so we can pass our special DamageBounds to the subMap method.
// We NEVER put any keys in this map that are not AESharedItemStacks.
private final Object2ObjectSortedMap<Object, IAEItemStack> records = new Object2ObjectAVLTreeMap<>( COMPARATOR );
@Override
public Collection<IAEItemStack> findFuzzy(final IAEItemStack filter, final FuzzyMode fuzzy) {
ItemStack itemStack = filter.getDefinition();
@Override
public Collection<IAEItemStack> findFuzzy( final IAEItemStack filter, final FuzzyMode fuzzy )
{
ItemStack itemStack = filter.getDefinition();
ItemDamageBound lowerBound = makeLowerBound(itemStack, fuzzy);
ItemDamageBound upperBound = makeUpperBound(itemStack, fuzzy);
Preconditions.checkState(lowerBound.itemDamage > upperBound.itemDamage);
ItemDamageBound lowerBound = makeLowerBound( itemStack, fuzzy );
ItemDamageBound upperBound = makeUpperBound( itemStack, fuzzy );
Preconditions.checkState( lowerBound.itemDamage > upperBound.itemDamage );
return this.records.subMap(lowerBound, upperBound).values();
}
return this.records.subMap( lowerBound, upperBound ).values();
}
@SuppressWarnings("unchecked")
@Override
Map<AESharedItemStack, IAEItemStack> getRecords() {
// We ensure on our end that we NEVER use anything but AESharedItemStack as the key in this map
return (Map<AESharedItemStack, IAEItemStack>) (Object) this.records;
}
@SuppressWarnings( "unchecked" )
@Override
Map<AESharedItemStack, IAEItemStack> getRecords()
{
// We ensure on our end that we NEVER use anything but AESharedItemStack as the key in this map
return (Map<AESharedItemStack, IAEItemStack>) (Object) this.records;
}
static class ItemDamageBound {
final int itemDamage;
static class ItemDamageBound
{
final int itemDamage;
public ItemDamageBound(int itemDamage) {
this.itemDamage = itemDamage;
}
}
public ItemDamageBound( int itemDamage )
{
this.itemDamage = itemDamage;
}
}
/**
* This comparator creates a strict and total ordering over all {@link AESharedItemStack} of the same item. To
* support selecting ranges of durability, it is defined for type {@link Object} and also accepts
* {@link ItemDamageBound} as an argument to compare against.
*/
static class SharedStackComparator implements Comparator<Object> {
@Override
public int compare(Object a, Object b) {
// Either argument can either be a damage bound or a shared item stack
// Since we never put damage bounds into the map as keys, only one
// of the two arguments can possibly be a bound
ItemDamageBound boundA = null;
AESharedItemStack stackA = null;
int itemDamageA;
if (a instanceof ItemDamageBound) {
boundA = (ItemDamageBound) a;
itemDamageA = boundA.itemDamage;
} else {
stackA = (AESharedItemStack) a;
itemDamageA = stackA.getItemDamage();
}
ItemDamageBound boundB = null;
AESharedItemStack stackB = null;
int itemDamageB;
if (b instanceof ItemDamageBound) {
boundB = (ItemDamageBound) b;
itemDamageB = boundB.itemDamage;
} else {
stackB = (AESharedItemStack) b;
itemDamageB = stackB.getItemDamage();
}
/**
* This comparator creates a strict and total ordering over all {@link AESharedItemStack} of the same item. To
* support selecting ranges of durability, it is defined for type {@link Object} and also accepts
* {@link ItemDamageBound} as an argument to compare against.
*/
static class SharedStackComparator implements Comparator<Object>
{
@Override
public int compare( Object a, Object b )
{
// Either argument can either be a damage bound or a shared item stack
// Since we never put damage bounds into the map as keys, only one
// of the two arguments can possibly be a bound
ItemDamageBound boundA = null;
AESharedItemStack stackA = null;
int itemDamageA;
if( a instanceof ItemDamageBound )
{
boundA = (ItemDamageBound) a;
itemDamageA = boundA.itemDamage;
}
else
{
stackA = (AESharedItemStack) a;
itemDamageA = stackA.getItemDamage();
}
ItemDamageBound boundB = null;
AESharedItemStack stackB = null;
int itemDamageB;
if( b instanceof ItemDamageBound )
{
boundB = (ItemDamageBound) b;
itemDamageB = boundB.itemDamage;
}
else
{
stackB = (AESharedItemStack) b;
itemDamageB = stackB.getItemDamage();
}
// When either argument is a damage bound, we just compare the damage values because it is used
// only to get a certain damage range out of the map.
if (boundA != null || boundB != null) {
return Integer.compare(itemDamageB, itemDamageA);
}
// When either argument is a damage bound, we just compare the damage values because it is used
// only to get a certain damage range out of the map.
if( boundA != null || boundB != null )
{
return Integer.compare( itemDamageB, itemDamageA );
}
ItemStack itemStackA = stackA.getDefinition();
ItemStack itemStackB = stackB.getDefinition();
Preconditions.checkState(itemStackA.getCount() == 1, "ItemStack#getCount() has to be 1");
Preconditions.checkArgument(itemStackB.getCount() == 1, "ItemStack#getCount() has to be 1");
ItemStack itemStackA = stackA.getDefinition();
ItemStack itemStackB = stackB.getDefinition();
Preconditions.checkState( itemStackA.getCount() == 1, "ItemStack#getCount() has to be 1" );
Preconditions.checkArgument( itemStackB.getCount() == 1, "ItemStack#getCount() has to be 1" );
if (itemStackA == itemStackB) {
return 0;
}
if( itemStackA == itemStackB )
{
return 0;
}
// Damaged items are sorted before undamaged items
final int damageValue = Integer.compare(itemDamageB, itemDamageA);
if (damageValue != 0) {
return damageValue;
}
// Damaged items are sorted before undamaged items
final int damageValue = Integer.compare( itemDamageB, itemDamageA );
if( damageValue != 0 )
{
return damageValue;
}
// As a final tie breaker, order by the object identity of the item stack
// While this will order seemingly at random, we only need the order of
// damage values to be predictable, while still having to satisfy the
// complete order requirements of the sorted map
return Long.compare(System.identityHashCode(itemStackA), System.identityHashCode(itemStackB));
}
}
// As a final tie breaker, order by the object identity of the item stack
// While this will order seemingly at random, we only need the order of
// damage values to be predictable, while still having to satisfy the
// complete order requirements of the sorted map
return Long.compare( System.identityHashCode( itemStackA ), System.identityHashCode( itemStackB ) );
}
}
/**
* Minecraft reverses the damage values. So anything with a damage of 0 is undamaged and increases the more damaged
* the item is.
* <p>
* Further the used subMap follows [MAX_DAMAGE, MIN_DAMAGE), so to include undamaged items, we have to start with a
* lower damage value than 0, while it is fine to use {@link ItemStack#getMaxDamage()} for the upper bound.
*/
private static final int MIN_DAMAGE_VALUE = -1;
/**
* Minecraft reverses the damage values. So anything with a damage of 0 is undamaged and increases the more damaged
* the item is.
* <p>
* Further the used subMap follows [MAX_DAMAGE, MIN_DAMAGE), so to include undamaged items, we have to start with a
* lower damage value than 0, while it is fine to use {@link ItemStack#getMaxDamage()} for the upper bound.
*/
private static final int MIN_DAMAGE_VALUE = -1;
/*
* Keep in mind that the stack order is from most damaged to least damaged, so this lower bound will actually be a
* higher number than the upper bound.
*/
static ItemDamageBound makeLowerBound(final ItemStack stack, final FuzzyMode fuzzy)
{
Preconditions.checkState( stack.getItem().isDamageable() , "Item#isDamageable() has to be true" );
/*
* Keep in mind that the stack order is from most damaged to least damaged, so this lower bound will actually be a
* higher number than the upper bound.
*/
static ItemDamageBound makeLowerBound( final ItemStack stack, final FuzzyMode fuzzy )
{
Preconditions.checkState( stack.getItem().isDamageable() || ( Platform.isGTDamageableItem( stack.getItem() ) ), "Item#isDamageable() has to be true" );
int damage;
if( fuzzy == FuzzyMode.IGNORE_ALL )
{
if( stack.getMaxDamage() == 0 )
{
damage = stack.getItemDamage();
}
else
{
damage = stack.getMaxDamage();
}
}
else
{
final int breakpoint = fuzzy.calculateBreakPoint( stack.getMaxDamage() );
damage = stack.getItemDamage() <= breakpoint ? breakpoint : stack.getMaxDamage();
}
int damage;
int maxDamage;
if( Platform.isIC2DamageableItem( stack.getItem() ) )
{
maxDamage = ( (ICustomDamageItem) stack.getItem() ).getMaxCustomDamage( stack );
damage = ( (ICustomDamageItem) stack.getItem() ).getCustomDamage( stack );
}
else if( Platform.isGTDamageableItem( stack.getItem() ) )
{
maxDamage = ( (IToolItem) stack.getItem() ).getMaxItemDamage( stack );
damage = ( (IToolItem) stack.getItem() ).getItemDamage( stack );
}
else
{
maxDamage = stack.getMaxDamage();
damage = stack.getItemDamage();
}
return new ItemDamageBound( damage );
}
if( fuzzy == FuzzyMode.IGNORE_ALL )
{
if( maxDamage != 0 )
{
damage = maxDamage;
}
}
else
{
final int breakpoint = fuzzy.calculateBreakPoint( maxDamage );
damage = damage <= breakpoint ? breakpoint : maxDamage;
}
/*
* Keep in mind that the stack order is from most damaged to least damaged, so this upper bound will actually be a
* lower number than the lower bound. It also is exclusive.
*/
static ItemDamageBound makeUpperBound(final ItemStack stack, final FuzzyMode fuzzy) {
Preconditions.checkState(stack.getItem().isDamageable() , "Item#isDamageable() has to be true");
return new ItemDamageBound( damage );
}
int damage;
if (fuzzy == FuzzyMode.IGNORE_ALL) {
damage = MIN_DAMAGE_VALUE;
} else {
final int breakpoint = fuzzy.calculateBreakPoint(stack.getMaxDamage());
damage = stack.getItemDamage() <= breakpoint ? MIN_DAMAGE_VALUE : breakpoint;
}
/*
* Keep in mind that the stack order is from most damaged to least damaged, so this upper bound will actually be a
* lower number than the lower bound. It also is exclusive.
*/
static ItemDamageBound makeUpperBound( final ItemStack stack, final FuzzyMode fuzzy )
{
Preconditions.checkState( stack.getItem().isDamageable() || ( Platform.isGTDamageableItem( stack.getItem() ) ), "Item#isDamageable() has to be true" );
return new ItemDamageBound(damage);
}
int damage;
if( fuzzy == FuzzyMode.IGNORE_ALL )
{
damage = MIN_DAMAGE_VALUE;
}
else
{
int maxDamage;
if( Platform.isIC2DamageableItem( stack.getItem() ) )
{
maxDamage = ( (ICustomDamageItem) stack.getItem() ).getMaxCustomDamage( stack );
damage = ( (ICustomDamageItem) stack.getItem() ).getCustomDamage( stack );
}
else if( Platform.isGTDamageableItem( stack.getItem() ) )
{
maxDamage = ( (IToolItem) stack.getItem() ).getMaxItemDamage( stack );
damage = ( (IToolItem) stack.getItem() ).getItemDamage( stack );
}
else
{
maxDamage = stack.getMaxDamage();
damage = stack.getItemDamage();
}
final int breakpoint = fuzzy.calculateBreakPoint( maxDamage );
damage = damage <= breakpoint ? MIN_DAMAGE_VALUE : breakpoint;
}
return new ItemDamageBound( damage );
}
}
+177 -141
View File
@@ -26,7 +26,6 @@ import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicInteger;
import appeng.util.Platform;
import gregtech.common.items.MetaTool;
import net.minecraft.item.Item;
import it.unimi.dsi.fastutil.objects.Reference2ObjectMap;
@@ -36,180 +35,217 @@ import appeng.api.config.FuzzyMode;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList;
public final class ItemList implements IItemList<IAEItemStack> {
private final Reference2ObjectMap<Item, ItemVariantList> records = new Reference2ObjectOpenHashMap<>();
/**
* We increment this version field everytime an attempt to mutate this item list (or potentially one of its
* sub-lists) is made. Iterators will copy the version when they are created and compare it against the current
* version whenever they advance to trigger a {@link ConcurrentModificationException}.
*/
private final AtomicInteger version = new AtomicInteger(0);
public final class ItemList implements IItemList<IAEItemStack>
{
@Override
public IAEItemStack findPrecise(final IAEItemStack itemStack) {
if (itemStack == null) {
return null;
}
private final Reference2ObjectMap<Item, ItemVariantList> records = new Reference2ObjectOpenHashMap<>();
/**
* We increment this version field everytime an attempt to mutate this item list (or potentially one of its
* sub-lists) is made. Iterators will copy the version when they are created and compare it against the current
* version whenever they advance to trigger a {@link ConcurrentModificationException}.
*/
private final AtomicInteger version = new AtomicInteger( 0 );
ItemVariantList record = this.records.get(itemStack.getItem());
return record != null ? record.findPrecise(itemStack) : null;
}
@Override
public IAEItemStack findPrecise( final IAEItemStack itemStack )
{
if( itemStack == null )
{
return null;
}
@Override
public Collection<IAEItemStack> findFuzzy(final IAEItemStack filter, final FuzzyMode fuzzy) {
if (filter == null) {
return Collections.emptyList();
}
ItemVariantList record = this.records.get( itemStack.getItem() );
return record != null ? record.findPrecise( itemStack ) : null;
}
ItemVariantList record = this.records.get(filter.getItem());
return record != null ? record.findFuzzy(filter, fuzzy) : Collections.emptyList();
}
@Override
public Collection<IAEItemStack> findFuzzy( final IAEItemStack filter, final FuzzyMode fuzzy )
{
if( filter == null )
{
return Collections.emptyList();
}
@Override
public boolean isEmpty() {
return !this.iterator().hasNext();
}
ItemVariantList record = this.records.get( filter.getItem() );
return record != null ? record.findFuzzy( filter, fuzzy ) : Collections.emptyList();
}
@Override
public void add(final IAEItemStack itemStack) {
version.incrementAndGet();
@Override
public boolean isEmpty()
{
return !this.iterator().hasNext();
}
if (itemStack == null) {
return;
}
@Override
public void add( final IAEItemStack itemStack )
{
version.incrementAndGet();
this.getOrCreateRecord(itemStack.getItem()).add(itemStack);
}
if( itemStack == null )
{
return;
}
@Override
public void addStorage(final IAEItemStack itemStack) {
version.incrementAndGet();
this.getOrCreateRecord( itemStack.getItem() ).add( itemStack );
}
if (itemStack == null) {
return;
}
@Override
public void addStorage( final IAEItemStack itemStack )
{
version.incrementAndGet();
this.getOrCreateRecord(itemStack.getItem()).addStorage(itemStack);
}
if( itemStack == null )
{
return;
}
@Override
public void addCrafting(final IAEItemStack itemStack) {
version.incrementAndGet();
this.getOrCreateRecord( itemStack.getItem() ).addStorage( itemStack );
}
if (itemStack == null) {
return;
}
@Override
public void addCrafting( final IAEItemStack itemStack )
{
version.incrementAndGet();
this.getOrCreateRecord(itemStack.getItem()).addCrafting(itemStack);
}
if( itemStack == null )
{
return;
}
@Override
public void addRequestable(final IAEItemStack itemStack) {
version.incrementAndGet();
this.getOrCreateRecord( itemStack.getItem() ).addCrafting( itemStack );
}
if (itemStack == null) {
return;
}
@Override
public void addRequestable( final IAEItemStack itemStack )
{
version.incrementAndGet();
this.getOrCreateRecord(itemStack.getItem()).addRequestable(itemStack);
}
if( itemStack == null )
{
return;
}
@Override
public IAEItemStack getFirstItem() {
for (final IAEItemStack stackType : this) {
return stackType;
}
this.getOrCreateRecord( itemStack.getItem() ).addRequestable( itemStack );
}
return null;
}
@Override
public IAEItemStack getFirstItem()
{
for( final IAEItemStack stackType : this )
{
return stackType;
}
@Override
public int size() {
int size = 0;
for (ItemVariantList entry : records.values()) {
size += entry.size();
}
return null;
}
return size;
}
@Override
public int size()
{
int size = 0;
for( ItemVariantList entry : records.values() )
{
size += entry.size();
}
@Override
public Iterator<IAEItemStack> iterator() {
return new ChainedIterator(this.records.values().iterator(), version);
}
return size;
}
@Override
public void resetStatus() {
for (final IAEItemStack i : this) {
i.reset();
}
}
@Override
public Iterator<IAEItemStack> iterator()
{
return new ChainedIterator( this.records.values().iterator(), version );
}
private ItemVariantList getOrCreateRecord(Item item) {
return this.records.computeIfAbsent(item, this::makeRecordMap);
}
@Override
public void resetStatus()
{
for( final IAEItemStack i : this )
{
i.reset();
}
}
private ItemVariantList makeRecordMap(Item item) {
if (item.isDamageable() ) {
return new FuzzyItemVariantList();
} else {
return new NormalItemVariantList();
}
}
private ItemVariantList getOrCreateRecord( Item item )
{
return this.records.computeIfAbsent( item, this::makeRecordMap );
}
/**
* Iterates over multiple item lists as if they were one list.
*/
private static class ChainedIterator implements Iterator<IAEItemStack> {
private ItemVariantList makeRecordMap( Item item )
{
if( item.isDamageable() || Platform.isGTDamageableItem( item ) )
{
return new FuzzyItemVariantList();
}
else
{
return new NormalItemVariantList();
}
}
private final AtomicInteger parentVersion;
private final int version;
private final Iterator<ItemVariantList> parent;
private Iterator<IAEItemStack> next;
/**
* Iterates over multiple item lists as if they were one list.
*/
private static class ChainedIterator implements Iterator<IAEItemStack>
{
public ChainedIterator(Iterator<ItemVariantList> iterator, AtomicInteger parentVersion) {
this.parent = iterator;
this.parentVersion = parentVersion;
this.version = parentVersion.get();
this.ensureItems();
}
private final AtomicInteger parentVersion;
private final int version;
private final Iterator<ItemVariantList> parent;
private Iterator<IAEItemStack> next;
@Override
public boolean hasNext() {
return next != null && next.hasNext();
}
public ChainedIterator( Iterator<ItemVariantList> iterator, AtomicInteger parentVersion )
{
this.parent = iterator;
this.parentVersion = parentVersion;
this.version = parentVersion.get();
this.ensureItems();
}
@Override
public IAEItemStack next() {
if (this.next == null) {
throw new NoSuchElementException();
}
if (this.version != this.parentVersion.get()) {
throw new ConcurrentModificationException();
}
@Override
public boolean hasNext()
{
return next != null && next.hasNext();
}
IAEItemStack result = this.next.next();
this.ensureItems();
return result;
}
@Override
public IAEItemStack next()
{
if( this.next == null )
{
throw new NoSuchElementException();
}
if( this.version != this.parentVersion.get() )
{
throw new ConcurrentModificationException();
}
private void ensureItems() {
if (hasNext()) {
return; // Still items left in the current one
}
IAEItemStack result = this.next.next();
this.ensureItems();
return result;
}
// Find the next iterator willing to return some items...
while (this.parent.hasNext()) {
this.next = this.parent.next().iterator();
private void ensureItems()
{
if( hasNext() )
{
return; // Still items left in the current one
}
if (this.next.hasNext()) {
return; // Found one!
}
}
// Find the next iterator willing to return some items...
while ( this.parent.hasNext() )
{
this.next = this.parent.next().iterator();
// No more items
this.next = null;
}
}
if( this.next.hasNext() )
{
return; // Found one!
}
}
// No more items
this.next = null;
}
}
}