Compare commits

...

12 Commits

Author SHA1 Message Date
Salomão d48c24a2e1 avoid relaying changes if theres no one listening to the passthrough 2021-07-05 19:56:41 -03:00
Salomão b6eef99312 Merge branch '111' into AE2-Omnifactory 2021-07-05 16:51:14 -03:00
Salomão decb869011 reworked propagation of item/fluid changes on the network 2021-07-05 16:49:52 -03:00
Salomão 5877fd2def Merge branch 'fluid-terminal-multiple-containers' into AE2-Omnifactory 2021-07-04 10:30:16 -03:00
Salomão df08ce0513 Fluid terminal is now able to fill/empty stacked tanks 2021-07-04 10:28:36 -03:00
Salomão f9c274fb48 Reduce power flickering by increasing energy polling rate
in testing 84 dense cells could sustain MAX Integer on a FE p2p pair
2021-06-27 23:17:26 -03:00
Salomão 3582582e3f fix off-by-one voiding patterns when removing expansion cards 2021-06-26 10:25:47 -03:00
Salomão 6de48f8541 fixes #34
getAllIngredients() can contain nulls
2021-06-26 07:31:16 -03:00
Salomão 5a2c2d06d3 make pattern expansion recipe shapeless 2021-06-24 22:34:21 -03:00
Salomão 98d3cafdfd Merge branch 'oredictfixes' into AE2-Omnifactory 2021-06-23 10:19:02 -03:00
Salomão 904de49543 wip
fix substitution crafting, for real this time
wip 2


wip. still has NBT issues


fix semantic changes


fix interface with free slots on interface terminal


Auto stash before cherry pick of "fix interface with free slots on interface terminal"
2021-06-23 10:16:59 -03:00
Salomão b0772bf94c backport 223163aa0a
fixes #32
2021-06-21 22:48:25 -03:00
32 changed files with 886 additions and 731 deletions
+1 -1
View File
@@ -3,7 +3,7 @@ aechannel=stable
aebuild=7
aegroup=appeng
aebasename=appliedenergistics2
trousers=omni-fixes-v43
trousers=omni-fixes-v44
#########################################################
# Versions #
@@ -31,6 +31,9 @@ import net.minecraft.world.World;
import appeng.api.implementations.ICraftingPatternItem;
import appeng.api.storage.data.IAEItemStack;
import java.util.Collections;
import java.util.List;
/**
* do not implement provided by {@link ICraftingPatternItem}
@@ -84,6 +87,11 @@ public interface ICraftingPatternDetails
*/
boolean canSubstitute();
default List<IAEItemStack> getSubstituteInputs( int slot )
{
return Collections.emptyList();
}
/**
* Allow using this INSTANCE of the pattern details to preform the crafting action with performance enhancements.
*
@@ -44,11 +44,8 @@ public interface IStackWatcherHost
/**
* Called when a watched item changes amounts.
*
* @param o changed item list
* @param fullStack old stack
* @param diffStack new stack
* @param src action source
* @param chan storage channel
*/
void onStackChange( IItemList<?> o, IAEStack<?> fullStack, IAEStack<?> diffStack, IActionSource src, IStorageChannel<?> chan );
void onStackChange( IAEStack<?> diffStack, IStorageChannel<?> chan );
}
@@ -52,4 +52,9 @@ public interface IMEMonitorHandlerReceiver<T extends IAEStack<T>>
* called when the list updates its contents, this is mostly for handling power events.
*/
void onListUpdate();
default boolean hasListeners()
{
return true;
}
}
@@ -418,8 +418,12 @@ public class GuiInterfaceTerminal extends AEBaseGui
// Search if the current inventory holds a pattern containing the search term.
if( !found )
{
int slot = 0;
for( final ItemStack itemStack : entry.getInventory() )
{
if (slot > 8 + numUpgradesMap.get(entry) * 9) {
break;
}
if( !searchFieldInputs.isEmpty() && !searchFieldOutputs.isEmpty() ) {
if (this.itemStackMatchesSearchTerm(itemStack, searchFieldInputs, 0) || this.itemStackMatchesSearchTerm(itemStack, searchFieldOutputs, 1)) {
found = true;
@@ -441,6 +445,7 @@ public class GuiInterfaceTerminal extends AEBaseGui
// If only Interfaces with empty slots should be shown, check that here
if(itemStack.isEmpty())
interfaceHasFreeSlots = true;
slot++;
}
}
// if found, filter skipped or machine name matching the search term, add it
@@ -130,7 +130,12 @@ public class CraftingTreeNode
if( this.parent.details.canSubstitute() )
{
itemList = inventoryList.findFuzzy( this.what, FuzzyMode.IGNORE_ALL );
final List<IAEItemStack> substitutes = this.parent.details.getSubstituteInputs(this.slot);
itemList = new ArrayList<>(substitutes.size());
for (IAEItemStack stack : substitutes) {
itemList.addAll(inventoryList.findFuzzy(stack, FuzzyMode.IGNORE_ALL));
}
}
else
{
@@ -305,7 +305,7 @@ public class CraftingTreeProcess
void getPlan( final IItemList<IAEItemStack> plan )
{
for( IAEItemStack i : this.details.getOutputs() )
for( IAEItemStack i : this.details.getCondensedOutputs() )
{
i = i.copy();
i.setCountRequestable( i.getStackSize() * this.crafts );
@@ -24,6 +24,9 @@ import java.nio.BufferOverflowException;
import javax.annotation.Nonnull;
import appeng.container.slot.AppEngSlot;
import appeng.container.slot.SlotPlayerHotBar;
import appeng.container.slot.SlotPlayerInv;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.InventoryPlayer;
@@ -70,6 +73,7 @@ import appeng.me.helpers.ChannelPowerSrc;
import appeng.util.ConfigManager;
import appeng.util.IConfigManagerHost;
import appeng.util.Platform;
import net.minecraftforge.items.IItemHandler;
/**
@@ -342,6 +346,89 @@ public class ContainerFluidTerminal extends AEBaseContainer implements IConfigMa
}
}
@Override
public ItemStack transferStackInSlot( final EntityPlayer p, final int idx )
{
if( Platform.isClient() )
{
return ItemStack.EMPTY;
}
EntityPlayerMP player = (EntityPlayerMP) p;
if( this.inventorySlots.get( idx ) instanceof SlotPlayerInv || this.inventorySlots.get( idx ) instanceof SlotPlayerHotBar )
{
final AppEngSlot clickSlot = (AppEngSlot) this.inventorySlots.get( idx ); // require AE SLots!
ItemStack itemStack = clickSlot.getStack();
ItemStack copy = itemStack.copy();
copy.setCount( 1 );
IFluidHandlerItem fh = FluidUtil.getFluidHandler( copy );
if( fh == null )
{
// only fluid handlers items
return ItemStack.EMPTY;
}
int heldAmount = itemStack.getCount();
for( int i = 0; i < heldAmount; i++ )
{
copy = itemStack.copy();
copy.setCount( 1 );
fh = FluidUtil.getFluidHandler( copy );
final FluidStack extract = fh.drain( Integer.MAX_VALUE, false );
if( extract == null || extract.amount < 1 )
{
return ItemStack.EMPTY;
}
// Check if we can push into the system
final IAEFluidStack notStorable = Platform.poweredInsert( this.getPowerSource(), this.monitor, AEFluidStack.fromFluidStack( extract ), this.getActionSource(), Actionable.SIMULATE );
if( notStorable != null && notStorable.getStackSize() > 0 )
{
final int toStore = (int) ( extract.amount - notStorable.getStackSize() );
final FluidStack storable = fh.drain( toStore, false );
if( storable == null || storable.amount == 0 )
{
return ItemStack.EMPTY;
}
else
{
extract.amount = storable.amount;
}
}
// Actually drain
final FluidStack drained = fh.drain( extract, true );
extract.amount = drained.amount;
final IAEFluidStack notInserted = Platform.poweredInsert( this.getPowerSource(), this.monitor, AEFluidStack.fromFluidStack( extract ), this.getActionSource() );
if( notInserted != null && notInserted.getStackSize() > 0 )
{
IAEFluidStack spill = this.monitor.injectItems( notInserted, Actionable.MODULATE, this.getActionSource() );
if( spill != null && spill.getStackSize() > 0 )
{
fh.fill( spill.getFluidStack(), true );
}
}
if( notInserted == null )
{
if( !player.inventory.addItemStackToInventory( fh.getContainer() ) )
{
player.dropItem( fh.getContainer(), false );
}
clickSlot.decrStackSize( 1 );
}
}
this.detectAndSendChanges();
return ItemStack.EMPTY;
}
return super.transferStackInSlot( p, idx );
}
@Override
public void doAction( EntityPlayerMP player, InventoryAction action, int slot, long id )
{
@@ -352,13 +439,9 @@ public class ContainerFluidTerminal extends AEBaseContainer implements IConfigMa
}
final ItemStack held = player.inventory.getItemStack();
if( held.getCount() != 1 )
{
// only support stacksize 1 for now
return;
}
final IFluidHandlerItem fh = FluidUtil.getFluidHandler( held );
ItemStack heldCopy = held.copy();
heldCopy.setCount( 1 );
IFluidHandlerItem fh = FluidUtil.getFluidHandler( heldCopy );
if( fh == null )
{
// only fluid handlers items
@@ -372,88 +455,122 @@ public class ContainerFluidTerminal extends AEBaseContainer implements IConfigMa
// Check how much we can store in the item
stack.setStackSize( Integer.MAX_VALUE );
int amountAllowed = fh.fill( stack.getFluidStack(), false );
stack.setStackSize( amountAllowed );
// Check if we can pull out of the system
final IAEFluidStack canPull = Platform.poweredExtraction( this.getPowerSource(), this.monitor, stack, this.getActionSource(), Actionable.SIMULATE );
if( canPull == null || canPull.getStackSize() < 1 )
int heldAmount = held.getCount();
for( int i = 0; i < heldAmount; i++ )
{
return;
}
ItemStack copiedFluidContainer = held.copy();
copiedFluidContainer.setCount( 1 );
fh = FluidUtil.getFluidHandler( copiedFluidContainer );
// How much could fit into the container
final int canFill = fh.fill( canPull.getFluidStack(), false );
if( canFill == 0 )
{
return;
}
// Now actually pull out of the system
stack.setStackSize( canFill );
final IAEFluidStack pulled = Platform.poweredExtraction( this.getPowerSource(), this.monitor, stack, this.getActionSource() );
if( pulled == null || pulled.getStackSize() < 1 )
{
// Something went wrong
AELog.error( "Unable to pull fluid out of the ME system even though the simulation said yes " );
return;
}
// Actually fill
final int used = fh.fill( pulled.getFluidStack(), true );
if( used != canFill )
{
AELog.error( "Fluid item [%s] reported a different possible amount than it actually accepted.", held.getDisplayName() );
}
player.inventory.setItemStack( fh.getContainer() );
this.updateHeld( player );
}
else if( action == InventoryAction.EMPTY_ITEM )
{
// See how much we can drain from the item
final FluidStack extract = fh.drain( Integer.MAX_VALUE, false );
if( extract == null || extract.amount < 1 )
{
return;
}
// Check if we can push into the system
final IAEFluidStack notStorable = Platform.poweredInsert( this.getPowerSource(), this.monitor, AEFluidStack.fromFluidStack( extract ),
this.getActionSource(), Actionable.SIMULATE );
if( notStorable != null && notStorable.getStackSize() > 0 )
{
final int toStore = (int) ( extract.amount - notStorable.getStackSize() );
final FluidStack storable = fh.drain( toStore, false );
if( storable == null || storable.amount == 0 )
// Check if we can pull out of the system
final IAEFluidStack canPull = Platform.poweredExtraction( this.getPowerSource(), this.monitor, stack.setStackSize( amountAllowed ), this.getActionSource(), Actionable.SIMULATE );
if( canPull == null || canPull.getStackSize() < 1 )
{
return;
}
// How much could fit into the container
final int canFill = fh.fill( canPull.getFluidStack(), false );
if( canFill == 0 )
{
return;
}
// Now actually pull out of the system
final IAEFluidStack pulled = Platform.poweredExtraction( this.getPowerSource(), this.monitor, stack.setStackSize( canFill ), this.getActionSource() );
if( pulled == null || pulled.getStackSize() < 1 )
{
// Something went wrong
AELog.error( "Unable to pull fluid out of the ME system even though the simulation said yes " );
return;
}
// Actually fill
final int used = fh.fill( pulled.getFluidStack(), true );
if( used != canFill )
{
AELog.error( "Fluid item [%s] reported a different possible amount than it actually accepted.", held.getDisplayName() );
}
if( held.getCount() == 1 )
{
player.inventory.setItemStack( fh.getContainer() );
}
else
{
extract.amount = storable.amount;
player.inventory.getItemStack().shrink( 1 );
if( !player.inventory.addItemStackToInventory( fh.getContainer() ) )
{
player.dropItem( fh.getContainer(), false );
}
}
}
this.updateHeld( player );
// Actually drain
final FluidStack drained = fh.drain( extract, true );
extract.amount = drained.amount;
final IAEFluidStack notInserted = Platform.poweredInsert( this.getPowerSource(), this.monitor, AEFluidStack.fromFluidStack( extract ),
this.getActionSource() );
if( notInserted != null && notInserted.getStackSize() > 0 )
}
else if( action == InventoryAction.EMPTY_ITEM )
{
int heldAmount = held.getCount();
for( int i = 0; i < heldAmount; i++ )
{
IAEFluidStack spill = this.monitor.injectItems( notInserted, Actionable.MODULATE, this.getActionSource() );
if( spill != null && spill.getStackSize() > 0 )
ItemStack copiedFluidContainer = held.copy();
copiedFluidContainer.setCount( 1 );
fh = FluidUtil.getFluidHandler( copiedFluidContainer );
// See how much we can drain from the item
final FluidStack extract = fh.drain( Integer.MAX_VALUE, false );
if( extract == null || extract.amount < 1 )
{
fh.fill( spill.getFluidStack(), true );
return;
}
// Check if we can push into the system
final IAEFluidStack notStorable = Platform.poweredInsert( this.getPowerSource(), this.monitor, AEFluidStack.fromFluidStack( extract ), this.getActionSource(), Actionable.SIMULATE );
if( notStorable != null && notStorable.getStackSize() > 0 )
{
final int toStore = (int) ( extract.amount - notStorable.getStackSize() );
final FluidStack storable = fh.drain( toStore, false );
if( storable == null || storable.amount == 0 )
{
return;
}
else
{
extract.amount = storable.amount;
}
}
// Actually drain
final FluidStack drained = fh.drain( extract, true );
extract.amount = drained.amount;
final IAEFluidStack notInserted = Platform.poweredInsert( this.getPowerSource(), this.monitor, AEFluidStack.fromFluidStack( extract ), this.getActionSource() );
if( notInserted != null && notInserted.getStackSize() > 0 )
{
IAEFluidStack spill = this.monitor.injectItems( notInserted, Actionable.MODULATE, this.getActionSource() );
if( spill != null && spill.getStackSize() > 0 )
{
fh.fill( spill.getFluidStack(), true );
}
}
if( held.getCount() == 1 )
{
player.inventory.setItemStack( fh.getContainer() );
}
else
{
player.inventory.getItemStack().shrink( 1 );
if( !player.inventory.addItemStackToInventory( fh.getContainer() ) )
{
player.dropItem( fh.getContainer(), false );
}
}
}
player.inventory.setItemStack( fh.getContainer() );
this.updateHeld( player );
}
}
@@ -20,7 +20,6 @@ package appeng.fluids.parts;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@@ -45,7 +44,6 @@ import appeng.api.storage.channels.IFluidStorageChannel;
import appeng.api.storage.data.IAEFluidStack;
import appeng.api.storage.data.IItemList;
import appeng.fluids.util.AEFluidStack;
import appeng.me.GridAccessException;
import appeng.me.helpers.IGridProxyable;
import appeng.me.storage.ITickingMonitor;
@@ -94,14 +92,9 @@ public class FluidHandlerAdapter implements IMEInventory<IAEFluidStack>, IBaseMo
if( type == Actionable.MODULATE )
{
try
{
this.proxyable.getProxy().getTick().alertDevice( this.proxyable.getProxy().getNode() );
}
catch( GridAccessException ignore )
{
// meh
}
this.cache
.currentlyCached
.add( input.copy().setStackSize( wasFillled ));
}
fluidStack.amount = remaining;
@@ -123,18 +116,16 @@ public class FluidHandlerAdapter implements IMEInventory<IAEFluidStack>, IBaseMo
return null;
}
IAEFluidStack gatheredAEFluidstack = AEFluidStack.fromFluidStack( gathered );
if( mode == Actionable.MODULATE )
{
try
IAEFluidStack e = this.cache.currentlyCached.findPrecise( gatheredAEFluidstack );
if (e != null)
{
this.proxyable.getProxy().getTick().alertDevice( this.proxyable.getProxy().getNode() );
}
catch( GridAccessException ignore )
{
// meh
e.decStackSize( gathered.amount );
}
}
return AEFluidStack.fromFluidStack( gathered );
return gatheredAEFluidstack;
}
@Override
@@ -202,9 +193,10 @@ public class FluidHandlerAdapter implements IMEInventory<IAEFluidStack>, IBaseMo
private static class InventoryCache
{
private IAEFluidStack[] cachedAeStacks = new IAEFluidStack[0];
private final IFluidHandler fluidHandler;
private final StorageFilter mode;
IItemList<IAEFluidStack> currentlyCached = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ).createList();
public InventoryCache( IFluidHandler fluidHandler, StorageFilter mode )
{
@@ -216,19 +208,12 @@ public class FluidHandlerAdapter implements IMEInventory<IAEFluidStack>, IBaseMo
{
final List<IAEFluidStack> changes = new ArrayList<>();
final IFluidTankProperties[] tankProperties = this.fluidHandler.getTankProperties();
final int slots = tankProperties.length;
// Make room for new slots
if( slots > this.cachedAeStacks.length )
{
this.cachedAeStacks = Arrays.copyOf( this.cachedAeStacks, slots );
}
IItemList<IAEFluidStack> currentlyOnStorage = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ).createList();
for( int slot = 0; slot < slots; slot++ )
for( IFluidTankProperties tankProperty : tankProperties )
{
// Save the old stuff
final IAEFluidStack oldAEFS = this.cachedAeStacks[slot];
FluidStack newFS = tankProperties[slot].getContents();
FluidStack newFS = tankProperty.getContents();
if( this.mode == StorageFilter.EXTRACTABLE_ONLY && newFS != null )
{
if( this.fluidHandler.drain( 1, false ) == null )
@@ -236,82 +221,40 @@ public class FluidHandlerAdapter implements IMEInventory<IAEFluidStack>, IBaseMo
newFS = null;
}
}
this.handlePossibleSlotChanges( slot, oldAEFS, newFS, changes );
}
// Handle cases where the number of slots actually is lower now than before
if( slots < this.cachedAeStacks.length )
{
for( int slot = slots; slot < this.cachedAeStacks.length; slot++ )
if( newFS != null )
{
final IAEFluidStack aeStack = this.cachedAeStacks[slot];
if( aeStack != null )
{
final IAEFluidStack a = aeStack.copy();
a.setStackSize( -a.getStackSize() );
changes.add( a );
}
currentlyOnStorage.add( AEFluidStack.fromFluidStack( newFS ) );
}
this.cachedAeStacks = Arrays.copyOf( this.cachedAeStacks, slots );
}
for ( final IAEFluidStack is : currentlyCached )
{
is.setStackSize( -is.getStackSize() );
}
for ( final IAEFluidStack is : currentlyOnStorage )
{
currentlyCached.add( is );
}
for ( final IAEFluidStack is : currentlyCached )
{
if( is.getStackSize() != 0 )
{
changes.add( is );
}
}
currentlyCached = currentlyOnStorage;
return changes;
}
public IItemList<IAEFluidStack> getAvailableItems( IItemList<IAEFluidStack> out )
{
Arrays.stream( this.cachedAeStacks ).forEach( out::add );
currentlyCached.iterator().forEachRemaining( out::add );
return out;
}
private void handlePossibleSlotChanges( int slot, IAEFluidStack oldAeFS, FluidStack newFS, List<IAEFluidStack> changes )
{
if( oldAeFS != null && oldAeFS.getFluidStack().isFluidEqual( newFS ) )
{
this.handleStackSizeChanged( slot, oldAeFS, newFS, changes );
}
else
{
this.handleFluidChanged( slot, oldAeFS, newFS, changes );
}
}
private void handleStackSizeChanged( int slot, IAEFluidStack oldAeFS, FluidStack newFS, List<IAEFluidStack> changes )
{
// Still the same fluid, but amount might have changed
final long diff = newFS.amount - oldAeFS.getStackSize();
if( diff != 0 )
{
final IAEFluidStack stack = oldAeFS.copy();
stack.setStackSize( newFS.amount );
this.cachedAeStacks[slot] = stack;
final IAEFluidStack a = stack.copy();
a.setStackSize( diff );
changes.add( a );
}
}
private void handleFluidChanged( int slot, IAEFluidStack oldAeFS, FluidStack newFS, List<IAEFluidStack> changes )
{
// Completely different fluid
this.cachedAeStacks[slot] = AEFluidStack.fromFluidStack( newFS );
// If we had a stack previously in this slot, notify the network about its disappearance
if( oldAeFS != null )
{
oldAeFS.setStackSize( -oldAeFS.getStackSize() );
changes.add( oldAeFS );
}
// Notify the network about the new stack. Note that this is null if newFS was null
if( this.cachedAeStacks[slot] != null )
{
changes.add( this.cachedAeStacks[slot] );
}
}
}
}
@@ -4,7 +4,9 @@ package appeng.fluids.parts;
import java.util.Random;
import appeng.api.networking.events.MENetworkChannelChanged;
import appeng.fluids.helper.IConfigurableFluidInventory;
import appeng.me.cache.NetworkMonitor;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
@@ -34,7 +36,6 @@ import appeng.api.storage.IStorageChannel;
import appeng.api.storage.channels.IFluidStorageChannel;
import appeng.api.storage.data.IAEFluidStack;
import appeng.api.storage.data.IAEStack;
import appeng.api.storage.data.IItemList;
import appeng.api.util.AECableType;
import appeng.api.util.AEPartLocation;
import appeng.api.util.IConfigManager;
@@ -112,11 +113,11 @@ public class PartFluidLevelEmitter extends PartUpgradeable implements IStackWatc
}
@Override
public void onStackChange( IItemList<?> o, IAEStack<?> fullStack, IAEStack<?> diffStack, IActionSource src, IStorageChannel<?> chan )
public void onStackChange( IAEStack<?> diffStack, IStorageChannel<?> chan )
{
if( chan == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) && fullStack.equals( this.config.getFluidInSlot( 0 ) ) )
if( chan == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) && diffStack.equals( this.config.getFluidInSlot( 0 ) ) )
{
this.lastReportedValue = fullStack.getStackSize();
this.lastReportedValue += diffStack.getStackSize();
this.updateState();
}
}
@@ -128,14 +129,22 @@ public class PartFluidLevelEmitter extends PartUpgradeable implements IStackWatc
}
@MENetworkEventSubscribe
public void channelChanged( final MENetworkChannelsChanged c )
public void powerStatusChange( final MENetworkPowerStatusChange powerEvent )
{
if (this.getProxy().isActive())
{
onListUpdate();
}
this.updateState();
}
@MENetworkEventSubscribe
public void powerChanged( final MENetworkPowerStatusChange c )
public void channelChanged( final MENetworkChannelsChanged c )
{
if (this.getProxy().isActive())
{
onListUpdate();
}
this.updateState();
}
@@ -247,10 +256,9 @@ public class PartFluidLevelEmitter extends PartUpgradeable implements IStackWatc
if( myStack == null )
{
this.lastReportedValue = 0;
for( final IAEFluidStack st : monitor.getStorageList() )
if( monitor instanceof NetworkMonitor )
{
this.lastReportedValue += st.getStackSize();
this.lastReportedValue = ( (NetworkMonitor<IAEFluidStack>) monitor ).getGridCurrentCount();
}
}
else
@@ -264,20 +264,17 @@ public class PartFluidStorageBus extends PartSharedStorageBus implements IMEMoni
@Override
public void postChange( final IBaseMonitor<IAEFluidStack> monitor, final Iterable<IAEFluidStack> change, final IActionSource source )
{
if( source == this.source || source.machine().map( machine -> machine == this ).orElse( false ) )
try
{
try
if( this.getProxy().isActive() )
{
if( this.getProxy().isActive() )
{
this.getProxy().getStorage().postAlterationOfStoredItems( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ), change, this.source );
}
}
catch( final GridAccessException e )
{
// :(
this.getProxy().getStorage().postAlterationOfStoredItems( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ), change, this.source );
}
}
catch( final GridAccessException e )
{
// :(
}
}
public MEInventoryHandler<IAEFluidStack> getInternalHandler()
@@ -415,7 +412,7 @@ public class PartFluidStorageBus extends PartSharedStorageBus implements IMEMoni
{
if( channel == this.getStorageChannel() )
{
final IMEInventoryHandler<IAEFluidStack> out = this.getProxy().isActive() ? this.getInternalHandler() : null;
final IMEInventoryHandler<IAEFluidStack> out = this.getInternalHandler();
if( out != null )
{
return Collections.singletonList( out );
@@ -608,14 +608,14 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
List<ItemStack> dropList = new ArrayList<>();
for( int invSlot = 0; invSlot < patterns.getSlots(); invSlot++ )
{
if( invSlot >= 9 + ( this.getInstalledUpgrades( Upgrades.PATTERN_EXPANSION ) ) * 9 )
if( invSlot > 8 + this.getInstalledUpgrades( Upgrades.PATTERN_EXPANSION ) * 9 )
{
ItemStack is = patterns.getStackInSlot( invSlot );
if( is.isEmpty() ) continue;
dropList.add( patterns.extractItem( invSlot, Integer.MAX_VALUE, false ) );
}
}
if( dropList.size() > 1 )
if( dropList.size() > 0 )
{
World world = this.getLocation().getWorld();
BlockPos blockPos = this.getLocation().getPos();
+114 -46
View File
@@ -19,21 +19,18 @@
package appeng.helpers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringJoiner;
import java.util.*;
import java.util.stream.Collectors;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.NonNullList;
import net.minecraft.world.World;
import appeng.api.AEApi;
@@ -46,11 +43,17 @@ import appeng.core.AELog;
import appeng.core.features.AEFeature;
import appeng.util.Platform;
import appeng.util.item.AEItemStack;
import net.minecraftforge.common.crafting.IShapedRecipe;
public class PatternHelper implements ICraftingPatternDetails, Comparable<PatternHelper>
{
private static final int CRAFTING_GRID_DIMENSION = 3;
private static final int ALL_INPUT_LIMIT = CRAFTING_GRID_DIMENSION * CRAFTING_GRID_DIMENSION;
private static final int CRAFTING_OUTPUT_LIMIT = 1;
private static final int PROCESSING_OUTPUT_LIMIT = 3;
private final ItemStack patternItem;
private final InventoryCrafting crafting = new InventoryCrafting( new ContainerNull(), 3, 3 );
private final InventoryCrafting testFrame = new InventoryCrafting( new ContainerNull(), 3, 3 );
@@ -60,6 +63,7 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable<Patter
private final IAEItemStack[] condensedOutputs;
private final IAEItemStack[] inputs;
private final IAEItemStack[] outputs;
private final Map<Integer, List<IAEItemStack>> substituteInputs;
private final boolean isCrafting;
private final boolean canSubstitute;
private final Set<TestLookup> failCache = new HashSet<>();
@@ -143,9 +147,11 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable<Patter
}
}
}
final int outputLength = this.isCrafting ? CRAFTING_OUTPUT_LIMIT : PROCESSING_OUTPUT_LIMIT;
this.outputs = out.toArray( new IAEItemStack[out.size()] );
this.inputs = in.toArray( new IAEItemStack[in.size()] );
this.inputs = in.toArray(new IAEItemStack[ALL_INPUT_LIMIT]);
this.outputs = out.toArray(new IAEItemStack[outputLength]);
this.substituteInputs = new HashMap<>(ALL_INPUT_LIMIT);
final Map<IAEItemStack, IAEItemStack> tmpOutputs = new HashMap<>();
@@ -257,6 +263,14 @@ 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);
return false;
}
}
if( this.standardRecipe.matches( this.testFrame, w ) )
{
final ItemStack testOutput = this.standardRecipe.getCraftingResult( this.testFrame );
@@ -268,25 +282,6 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable<Patter
return true;
}
}
else if( AEConfig.instance().isFeatureEnabled( AEFeature.CRAFTING_MANAGER_FALLBACK ) )
{
final ItemStack testOutput = CraftingManager.findMatchingResult( this.testFrame, w );
if( Platform.itemComparisons().isSameItem( this.correctOutput, testOutput ) )
{
this.testFrame.setInventorySlotContents( slotIndex, this.crafting.getStackInSlot( slotIndex ) );
this.markItemAs( slotIndex, i, TestStatus.ACCEPT );
if( AELog.isCraftingDebugLogEnabled() )
{
this.warnAboutCraftingManager( true );
}
return true;
}
this.warnAboutCraftingManager( false );
}
this.markItemAs( slotIndex, i, TestStatus.DECLINE );
return false;
@@ -328,6 +323,97 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable<Patter
return this.canSubstitute;
}
@Override
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));
}
// 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]);
return itemList;
});
}
/**
* Gets the {@link Ingredient} from the actual used recipe for a given slot-index into {@link #getInputs()}.
* <p/>
* Conversion is needed for two reasons: our sparse ingredients are always organized in a 3x3 grid, while Vanilla's
* 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) {
if (standardRecipe instanceof IShapedRecipe ) {
IShapedRecipe shapedRecipe = (IShapedRecipe) standardRecipe;
return getShapedRecipeIngredient(slot, shapedRecipe.getRecipeWidth());
} else {
return getShapelessRecipeIngredient(slot);
}
}
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) {
topOffset++; // First row is fully empty
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) {
leftOffset++; // First column is fully empty
if (inputs[1] == null && inputs[4] == null && inputs[7] == null) {
leftOffset++; // Second column is fully empty
}
}
// Compute the x,y of the slot, as-if the recipe was anchored to 0,0
int slotX = slot % CRAFTING_GRID_DIMENSION - leftOffset;
int slotY = slot / CRAFTING_GRID_DIMENSION - topOffset;
// Compute the index into the recipe's ingredient list now
int ingredientIndex = slotY * recipeWidth + slotX;
NonNullList<Ingredient> ingredients = standardRecipe.getIngredients();
if (ingredientIndex < 0 || ingredientIndex > ingredients.size()) {
return Ingredient.EMPTY;
}
return ingredients.get(ingredientIndex);
}
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) {
ingredientIndex++;
}
}
NonNullList<Ingredient> ingredients = standardRecipe.getIngredients();
if (ingredientIndex < ingredients.size()) {
return ingredients.get(ingredientIndex);
}
return Ingredient.EMPTY;
}
@Override
public ItemStack getOutput( final InventoryCrafting craftingInv, final World w )
{
@@ -406,24 +492,6 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable<Patter
return this.pattern.hashCode();
}
private void warnAboutCraftingManager( boolean foundAlternative )
{
final String foundAlternativeRecipe = foundAlternative ? "Found alternative recipe." : "NOT FOUND, please report.";
final StringJoiner joinActualInputs = new StringJoiner( ", " );
for( int j = 0; j < this.testFrame.getSizeInventory(); j++ )
{
final ItemStack stack = this.testFrame.getStackInSlot( j );
if( !stack.isEmpty() )
{
joinActualInputs.add( stack.toString() );
}
}
AELog.warn( "Using CraftingManager fallback: Recipe <%s> for output <%s> rejected inputs [%s]. %s",
this.standardRecipe.getRegistryName(), this.standardRecipe.getRecipeOutput(), joinActualInputs, foundAlternativeRecipe );
}
@Override
public boolean equals( final Object obj )
{
@@ -147,8 +147,12 @@ class RecipeTransferHandler<T extends Container> implements IRecipeTransferHandl
}
// prefer pure crystals.
for( ItemStack stack : ingredient.getAllIngredients() )
for ( ItemStack stack : ingredient.getAllIngredients() )
{
if( stack == null )
{
continue;
}
if( Platform.isRecipePrioritized( stack ) )
{
list.add( 0, stack );
@@ -159,7 +163,7 @@ class RecipeTransferHandler<T extends Container> implements IRecipeTransferHandl
}
}
for( final ItemStack is : list )
for ( final ItemStack is : list )
{
final NBTTagCompound tag = new NBTTagCompound();
is.writeToNBT( tag );
@@ -225,7 +225,7 @@ public class ItemEncodedPattern extends AEBaseItem implements ICraftingPatternIt
final ICraftingPatternDetails details = this.getPatternForItem( item, w );
out = details != null ? details.getOutputs()[0].createItemStack() : ItemStack.EMPTY;
out = details != null ? details.getCondensedOutputs()[0].createItemStack() : ItemStack.EMPTY;
SIMPLE_CACHE.put( item, out );
return out;
+1 -1
View File
@@ -296,7 +296,7 @@ public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper
// new craftables!
for( final ICraftingPatternDetails details : this.craftingMethods.keySet() )
{
for( IAEItemStack out : details.getOutputs() )
for( IAEItemStack out : details.getCondensedOutputs() )
{
out = out.copy();
out.reset();
+20 -38
View File
@@ -202,23 +202,6 @@ public class EnergyGridCache implements IEnergyGrid
@Override
public void onUpdateTick()
{
if (!providerToRemove.isEmpty() && !ongoingExtractOperation) {
this.providers.removeIf( p -> providerToRemove.contains( p ) );
providerToRemove.clear();
}
if (!requesterToRemove.isEmpty() && !ongoingInjectOperation) {
this.requesters.removeIf( r -> providerToRemove.contains( r ) );
requesterToRemove.clear();
}
if (!providersToAdd.isEmpty() && !ongoingExtractOperation) {
this.providers.addAll(providersToAdd);
providersToAdd.clear();
}
if( !requesterToAdd.isEmpty() && !ongoingInjectOperation){
this.requesters.addAll(requesterToAdd);
requesterToAdd.clear();
}
if( !this.interests.isEmpty() )
{
final double oldPower = this.lastStoredPower;
@@ -248,7 +231,7 @@ public class EnergyGridCache implements IEnergyGrid
if( this.drainPerTick > 0.0001 )
{
final double drained = this.extractAEPower( this.getIdlePowerUsage(), Actionable.MODULATE, PowerMultiplier.CONFIG );
currentlyHasPower = drained >= this.drainPerTick - 0.001;
currentlyHasPower = drained >= this.drainPerTick - 0.001 && this.getStoredPower() > 0;
}
else
{
@@ -352,6 +335,9 @@ public class EnergyGridCache implements IEnergyGrid
{
double extractedPower = 0;
this.providers.addAll( providersToAdd );
providersToAdd.clear();
final Iterator<IAEPowerStorage> it = this.providers.iterator();
ongoingExtractOperation = true;
@@ -361,12 +347,6 @@ public class EnergyGridCache implements IEnergyGrid
{
final IAEPowerStorage node = it.next();
if ( providerToRemove.contains( node )) {
it.remove();
providerToRemove.remove( node );
continue;
}
final double req = amt - extractedPower;
final double newPower = node.extractAEPower( req, mode, PowerMultiplier.ONE );
extractedPower += newPower;
@@ -376,7 +356,10 @@ public class EnergyGridCache implements IEnergyGrid
it.remove();
}
}
} finally {
} finally
{
providers.removeIf( p -> providerToRemove.contains( p ) );
this.providerToRemove.clear();
ongoingExtractOperation = false;
}
@@ -401,6 +384,9 @@ public class EnergyGridCache implements IEnergyGrid
{
final double originalAmount = amt;
this.requesters.addAll( requesterToAdd );
requesterToAdd.clear();
final Iterator<IAEPowerStorage> it = this.requesters.iterator();
ongoingInjectOperation = true;
@@ -410,12 +396,6 @@ public class EnergyGridCache implements IEnergyGrid
{
final IAEPowerStorage node = it.next();
if ( requesterToRemove.contains( node )) {
it.remove();
requesterToRemove.remove( node );
continue;
}
amt = node.injectAEPower( amt, mode );
if( amt > 0 && mode == Actionable.MODULATE )
@@ -425,6 +405,8 @@ public class EnergyGridCache implements IEnergyGrid
}
} finally
{
requesters.removeIf( r -> requesterToRemove.contains( r ) );
this.requesterToRemove.clear();
ongoingInjectOperation = false;
}
@@ -505,11 +487,7 @@ public class EnergyGridCache implements IEnergyGrid
@Override
public double getStoredPower()
{
if( this.availableTicksSinceUpdate > 2 )
{
this.refreshPower();
}
this.refreshPower();
return Math.max( 0.0, this.globalAvailablePower );
}
@@ -810,8 +788,12 @@ public class EnergyGridCache implements IEnergyGrid
if( this.stored < 0.01 )
{
EnergyGridCache.this.ticksSinceHasPowerChange = 0;
EnergyGridCache.this.publicPowerState( false, EnergyGridCache.this.myGrid );
refreshPower();
if (globalAvailablePower < MAX_BUFFER_STORAGE - 0.001)
{
EnergyGridCache.this.ticksSinceHasPowerChange = 0;
EnergyGridCache.this.publicPowerState( false, EnergyGridCache.this.myGrid );
}
}
}
}
+63 -16
View File
@@ -19,17 +19,21 @@
package appeng.me.cache;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import appeng.api.AEApi;
import appeng.api.storage.channels.IFluidStorageChannel;
import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEFluidStack;
import appeng.api.storage.data.IAEItemStack;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Queues;
@@ -66,6 +70,8 @@ public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
private boolean hasChanged = false;
@Nonnegative
private int localDepthSemaphore = 0;
private long gridItemCount;
private long gridFluidCount;
public NetworkMonitor( final GridStorageCache cache, final IStorageChannel<T> chan )
{
@@ -137,6 +143,32 @@ public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
return this.getHandler().getSlot();
}
public long getGridCurrentCount()
{
if( myChannel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) )
{
return gridItemCount;
}
else if( myChannel == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) )
{
return gridFluidCount;
}
return 0;
}
public long incGridCurrentCount(long count)
{
if( myChannel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) )
{
return gridItemCount += count;
}
else if( myChannel == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) )
{
return gridFluidCount += count;
}
return 0;
}
@Nonnull
@Override
public IItemList<T> getStorageList()
@@ -230,7 +262,7 @@ public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
{
final Entry<IMEMonitorHandlerReceiver<T>, Object> o = i.next();
final IMEMonitorHandlerReceiver<T> receiver = o.getKey();
if( receiver.isValid( o.getValue() ) )
if( receiver.isValid( o.getValue() ) && receiver.hasListeners() )
{
receiver.postChange( this, diff, src );
}
@@ -258,9 +290,7 @@ public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
this.sendEvent = true;
this.notifyListenersOfChange( changes, src );
for( final T changedItem : changes )
for ( final T changedItem : changes )
{
T difference = changedItem;
@@ -270,25 +300,20 @@ public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
difference.setStackSize( -changedItem.getStackSize() );
}
incGridCurrentCount( difference.getStackSize() );
this.cachedList.add( difference );
if( this.myGridCache.getInterestManager().containsKey( changedItem ) )
{
final Collection<ItemWatcher> list = this.myGridCache.getInterestManager().get( changedItem );
if( !list.isEmpty() )
{
IAEStack<T> fullStack = this.getStorageList().findPrecise( changedItem );
if( fullStack == null )
{
fullStack = changedItem.copy();
fullStack.setStackSize( 0 );
}
this.myGridCache.getInterestManager().enableTransactions();
for( final ItemWatcher iw : list )
{
iw.getHost().onStackChange( this.getStorageList(), fullStack, difference, src, this.getChannel() );
iw.getHost().onStackChange( difference, this.getChannel() );
}
this.myGridCache.getInterestManager().disableTransactions();
@@ -296,6 +321,8 @@ public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
}
}
this.notifyListenersOfChange( changes, src );
final NetworkMonitor<?> last = GLOBAL_DEPTH.pop();
this.localDepthSemaphore--;
@@ -308,9 +335,28 @@ public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
void forceUpdate()
{
this.hasChanged = true;
//when the grid comes back online, reset the count to 0 so
//it reflects the correct amount after the changes are accounted for
if( myChannel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) )
{
gridItemCount = 0;
for( IAEItemStack iaeItemStack : (Iterable<IAEItemStack>) getStorageList() )
{
gridItemCount += iaeItemStack.getStackSize();
}
}
else if( myChannel == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) )
{
gridFluidCount = 0;
for( IAEFluidStack iaeFluidStack : (Iterable<IAEFluidStack>) getStorageList() )
{
gridFluidCount += iaeFluidStack.getStackSize();
}
}
final Iterator<Entry<IMEMonitorHandlerReceiver<T>, Object>> i = this.getListeners();
while( i.hasNext() )
while ( i.hasNext() )
{
final Entry<IMEMonitorHandlerReceiver<T>, Object> o = i.next();
final IMEMonitorHandlerReceiver<T> receiver = o.getKey();
@@ -333,5 +379,6 @@ public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
this.sendEvent = false;
this.myGridCache.getGrid().postEvent( new MENetworkStorageEvent( this, this.myChannel ) );
}
}
}
-1
View File
@@ -138,7 +138,6 @@ public class TickManagerCache implements ITickManager
tt.addEntityCrashInfo( crashreportcategory );
throw new ReportedException( crashreport );
}
PartLevelEmitter.wipeCache();
}
private void addToQueue( final TickTracker tt )
@@ -494,22 +494,87 @@ 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)
{
for( IAEItemStack g : condensedInputs )
if( !details.isCraftable() )
{
// Processing patterns are relatively easy
for ( IAEItemStack input : condensedInputs )
{
final IAEItemStack ais = this.inventory.extractItems( input.copy(), Actionable.SIMULATE,
this.machineSrc );
if( details.isCraftable() )
if( ais == null || ais.getStackSize() < input.getStackSize() )
{
return false;
}
}
}
else if( details.canSubstitute() )
{
// 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++ )
{
List<IAEItemStack> substitutes = details.getSubstituteInputs( i );
if( substitutes.isEmpty() )
{
continue;
}
boolean found = false;
for ( IAEItemStack substitute : substitutes )
{
for ( IAEItemStack fuzz : this.inventory.getItemList().findFuzzy( substitute, FuzzyMode.IGNORE_ALL ) )
{
int alreadyConsumed = consumedCount.getOrDefault( fuzz, 0 );
if( fuzz.getStackSize() - alreadyConsumed <= 0 )
{
continue; // Already fully consumed by a previous slot of this recipe
}
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 );
if( ais != null && ais.getStackSize() > 0 )
{
// Mark 1 of the stack as consumed
consumedCount.merge( fuzz, 1, Integer::sum );
found = true;
break;
}
}
if( found )
{
break;
}
}
if( !found )
{
return false;
}
}
}
else
{
// 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 )
{
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() );
final IAEItemStack ais = this.inventory.extractItems( fuzz, Actionable.SIMULATE, this.machineSrc );
if (ais != null && ais.getStackSize() == g.getStackSize())
if( ais != null && ais.getStackSize() >= g.getStackSize() )
{
found = true;
break;
@@ -526,15 +591,7 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
return false;
}
}
else
{
final IAEItemStack ais = this.inventory.extractItems( g.copy(), Actionable.SIMULATE, this.machineSrc );
if (ais == null || ais.getStackSize() < g.getStackSize())
{
return false;
}
}
}
return true;
@@ -689,71 +746,67 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
ic = new InventoryCrafting( new ContainerNull(), 3, 3 );
boolean found = false;
for( int x = 0; x < input.length; x++ )
{
if( input[x] != null )
{
for (int x = 0; x < input.length; x++) {
if (input[x] != null) {
found = false;
if( details.isCraftable() )
{
if (details.isCraftable()) {
final Collection<IAEItemStack> itemList;
if( details.canSubstitute() )
{
itemList = this.inventory.getItemList().findFuzzy( input[x], FuzzyMode.IGNORE_ALL );
}
else
{
itemList = new ArrayList<>( 1 );
if (details.canSubstitute()) {
final List<IAEItemStack> substitutes = details.getSubstituteInputs(x);
itemList = new ArrayList<>(substitutes.size());
final IAEItemStack item = this.inventory.getItemList().findPrecise( input[x] );
for (IAEItemStack stack : substitutes) {
itemList.addAll(this.inventory.getItemList().findFuzzy(stack,
FuzzyMode.IGNORE_ALL));
}
} else {
itemList = new ArrayList<>(1);
if( item != null )
{
itemList.add( item );
final IAEItemStack item = this.inventory.getItemList()
.findPrecise(input[x]);
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;
}
}
@@ -23,9 +23,10 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.google.common.collect.Multimap;
import appeng.api.config.FuzzyMode;
import appeng.api.storage.data.IAEStack;
import appeng.util.item.AEItemStack;
import com.google.common.collect.Multimap;
public class GenericInterestManager<T>
@@ -101,12 +102,30 @@ public class GenericInterestManager<T>
public boolean containsKey( final IAEStack stack )
{
if( stack.isItem() && ( ( AEItemStack ) stack ).getItem().isDamageable() )
{
return this.container.keySet().stream().filter( s -> s.isItem() )
.anyMatch( s -> s.fuzzyComparison( stack, FuzzyMode.IGNORE_ALL ) );
}
return this.container.containsKey( stack );
}
public Collection<T> get( final IAEStack stack )
{
return this.container.get( stack );
Collection<T> watchers = new ArrayList<>();
if( stack.isItem() && ( ( AEItemStack ) stack ).getItem().isDamageable() )
{
this.container.keySet().stream().filter( s -> s.isItem() )
.filter( k -> k.fuzzyComparison( stack, FuzzyMode.IGNORE_ALL ) )
.forEach( key ->
watchers.addAll( this.container.get( key ) )
);
}
else
{
return this.container.get( stack );
}
return watchers;
}
private class SavedTransactions
@@ -90,6 +90,13 @@ public class MEMonitorPassThrough<T extends IAEStack<T>> extends MEPassThrough<T
@Override
public void addListener( final IMEMonitorHandlerReceiver<T> l, final Object verificationToken )
{
if( this.listeners.size() == 0 )
{
if( this.monitor != null )
{
this.monitor.addListener( this, this.monitor );
}
}
this.listeners.put( l, verificationToken );
}
@@ -117,6 +124,12 @@ public class MEMonitorPassThrough<T extends IAEStack<T>> extends MEPassThrough<T
return verificationToken == this.monitor;
}
@Override
public boolean hasListeners()
{
return this.listeners.size() > 0;
}
@Override
public void postChange( final IBaseMonitor<T> monitor, final Iterable<T> change, final IActionSource source )
{
@@ -19,11 +19,17 @@
package appeng.parts.automation;
import java.util.Collections;
import java.util.Optional;
import java.util.Random;
import appeng.api.networking.events.*;
import appeng.me.Grid;
import appeng.me.GridNode;
import appeng.me.cache.NetworkMonitor;
import appeng.util.item.AEItemStack;
import appeng.util.item.OreHelper;
import appeng.util.item.OreReference;
import it.unimi.dsi.fastutil.objects.Object2LongMap;
import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
@@ -56,10 +62,6 @@ import appeng.api.networking.crafting.ICraftingWatcherHost;
import appeng.api.networking.energy.IEnergyGrid;
import appeng.api.networking.energy.IEnergyWatcher;
import appeng.api.networking.energy.IEnergyWatcherHost;
import appeng.api.networking.events.MENetworkChannelsChanged;
import appeng.api.networking.events.MENetworkCraftingPatternChange;
import appeng.api.networking.events.MENetworkEventSubscribe;
import appeng.api.networking.events.MENetworkPowerStatusChange;
import appeng.api.networking.security.IActionSource;
import appeng.api.networking.storage.IBaseMonitor;
import appeng.api.networking.storage.IStackWatcher;
@@ -72,7 +74,6 @@ import appeng.api.storage.IStorageChannel;
import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IAEStack;
import appeng.api.storage.data.IItemList;
import appeng.api.util.AECableType;
import appeng.api.util.AEPartLocation;
import appeng.api.util.IConfigManager;
@@ -123,9 +124,6 @@ public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherH
private double centerX;
private double centerY;
private double centerZ;
static Object2LongMap<Grid> gridItemCount = new Object2LongOpenHashMap<>();
static Object2ObjectOpenHashMap<Grid, Object2LongMap<AEItemStack>> fuzzyAEItemStackCount = new Object2ObjectOpenHashMap<>();
static Object2ObjectOpenHashMap<Grid, Object2LongMap<AEItemStack>> preciseAEItemStackCount = new Object2ObjectOpenHashMap<>();
@Reflected
public PartLevelEmitter( final ItemStack is )
@@ -156,12 +154,6 @@ public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherH
}
}
@MENetworkEventSubscribe
public void powerChanged( final MENetworkPowerStatusChange c )
{
this.updateState();
}
private void updateState()
{
final boolean isOn = this.isLevelEmitterOn();
@@ -206,9 +198,23 @@ public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherH
return flipState ? this.reportingValue >= this.lastReportedValue + 1 : this.reportingValue < this.lastReportedValue + 1;
}
@MENetworkEventSubscribe
public void powerStatusChange( final MENetworkPowerStatusChange powerEvent )
{
if (this.getProxy().isActive())
{
onListUpdate();
}
this.updateState();
}
@MENetworkEventSubscribe
public void channelChanged( final MENetworkChannelsChanged c )
{
if (this.getProxy().isActive())
{
onListUpdate();
}
this.updateState();
}
@@ -296,24 +302,37 @@ public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherH
try
{
if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 || myStack == null )
if( myStack == null )
{
this.getProxy()
.getStorage()
.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) )
.addListener( this,
this.getProxy().getGrid() );
this.getProxy().getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ).addListener( this, this.getProxy().getGrid() );
}
else
{
this.getProxy().getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ).removeListener( this );
if( this.myWatcher != null )
{
this.myWatcher.add( myStack );
if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 )
{
Optional<OreReference> ores = OreHelper.INSTANCE.getOre( myStack.getDefinition() );
if( ores.isPresent() )
{
for( IAEItemStack iaeItemStack : ores.get().getAEEquivalents() )
{
this.myWatcher.add( iaeItemStack );
}
}
else
{
this.myWatcher.add( myStack );
}
}
else
{
this.myWatcher.add( myStack );
}
}
}
this.updateReportingValue( this.getProxy().getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) );
}
catch( final GridAccessException e )
@@ -323,90 +342,29 @@ public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherH
}
private void updateReportingValue( final IMEMonitor<IAEItemStack> monitor )
{
updateReportingValue( monitor,null );
}
private void updateReportingValue( final IMEMonitor<IAEItemStack> monitor, Iterable<IAEItemStack> change )
{
final IAEItemStack myStack = this.config.getAEStackInSlot( 0 );
GridNode node = (GridNode) (this.getGridNode());
if( node != null )
if( myStack == null )
{
final Grid g = node.getInternalGrid();
if( myStack == null )
if( monitor instanceof NetworkMonitor )
{
if( change != null )
{
if( gridItemCount.containsKey( g ) )
{
change.forEach( iaeItemStack -> lastReportedValue += iaeItemStack.getStackSize() );
}
}
gridItemCount.computeIfAbsent( g, ( aLong ) -> {
this.lastReportedValue = 0;
monitor.getStorageList().forEach( iaeItemStack -> lastReportedValue += iaeItemStack.getStackSize() );
return ( lastReportedValue );
} );
this.lastReportedValue = gridItemCount.get( g );
this.lastReportedValue = ( (NetworkMonitor<IAEItemStack>) monitor ).getGridCurrentCount();
}
}
else if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 )
{
final FuzzyMode fzMode = (FuzzyMode) this.getConfigManager().getSetting( Settings.FUZZY_MODE );
if( change != null )
{
if( fuzzyAEItemStackCount.containsKey( g ) )
{
change.forEach( iaeItemStack -> {
if( iaeItemStack.sameOre( myStack ) ) lastReportedValue += iaeItemStack.getStackSize();
} );
}
}
else if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 )
{
final FuzzyMode fzMode = (FuzzyMode) this.getConfigManager().getSetting( Settings.FUZZY_MODE );
fuzzyAEItemStackCount.computeIfAbsent( g, ( grid -> new Object2LongOpenHashMap<>() ) );
fuzzyAEItemStackCount.get( g ).computeIfAbsent( (AEItemStack) myStack, ( aLong -> {
this.lastReportedValue = 0;
monitor.getStorageList().findFuzzy( myStack, fzMode ).forEach( iaeItemStack -> lastReportedValue += iaeItemStack.getStackSize() );
return ( lastReportedValue );
} ) );
this.lastReportedValue = fuzzyAEItemStackCount.get( g ).get( myStack );
if( this.lastReportedValue == 0 )
{
fuzzyAEItemStackCount.get( g ).remove( myStack );
fuzzyAEItemStackCount.trim();
}
}
else
{
if( change != null )
{
if( preciseAEItemStackCount.containsKey( g ) )
{
change.forEach( iaeItemStack -> {
if( iaeItemStack.isSameType( myStack ) ) lastReportedValue += iaeItemStack.getStackSize();
} );
}
}
preciseAEItemStackCount.computeIfAbsent( g, ( grid -> new Object2LongOpenHashMap<>() ) );
preciseAEItemStackCount.get( g ).computeIfAbsent( (AEItemStack) myStack, ( aLong -> {
this.lastReportedValue = 0;
IAEItemStack precise = monitor.getStorageList().findPrecise( myStack );
if( precise != null ) lastReportedValue = precise.getStackSize();
return ( lastReportedValue );
} ) );
this.lastReportedValue = preciseAEItemStackCount.get( g ).get( myStack );
if( this.lastReportedValue == 0 )
{
preciseAEItemStackCount.get( g ).remove( myStack );
preciseAEItemStackCount.trim();
}
}
this.lastReportedValue = 0;
monitor.getStorageList().findFuzzy( myStack, fzMode ).forEach( iaeItemStack -> lastReportedValue += iaeItemStack.getStackSize() );
}
else
{
this.lastReportedValue = 0;
IAEItemStack precise = monitor.getStorageList().findPrecise( myStack );
if( precise != null ) lastReportedValue = precise.getStackSize();
}
this.updateState();
}
@@ -419,12 +377,23 @@ public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherH
}
@Override
public void onStackChange( final IItemList o, final IAEStack fullStack, final IAEStack diffStack, final IActionSource src, final IStorageChannel chan )
public void onStackChange( final IAEStack diffStack, final IStorageChannel chan )
{
if( chan == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) && fullStack.equals( this.config.getAEStackInSlot( 0 ) ) && this
.getInstalledUpgrades( Upgrades.FUZZY ) == 0 )
if( chan == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) )
{
this.lastReportedValue = fullStack.getStackSize();
IAEItemStack myStack = this.config.getAEStackInSlot( 0 );
if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 )
{
final FuzzyMode fzMode = (FuzzyMode) this.getConfigManager().getSetting( Settings.FUZZY_MODE );
if( Platform.itemComparisons().isFuzzyEqualItem( myStack.getDefinition(), ( (IAEItemStack) diffStack ).getDefinition(), fzMode ) )
{
this.lastReportedValue += diffStack.getStackSize();
}
}
else if( diffStack.equals( myStack ) )
{
this.lastReportedValue += diffStack.getStackSize();
}
this.updateState();
}
}
@@ -459,7 +428,7 @@ public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherH
@Override
public void postChange( final IBaseMonitor<IAEItemStack> monitor, final Iterable<IAEItemStack> change, final IActionSource actionSource )
{
this.updateReportingValue( (IMEMonitor<IAEItemStack>) monitor, change );
this.updateReportingValue( (IMEMonitor<IAEItemStack>) monitor );
}
@Override
@@ -636,9 +605,4 @@ public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherH
}
}
public static void wipeCache(){
fuzzyAEItemStackCount.clear();
preciseAEItemStackCount.clear();
gridItemCount.clear();
}
}
@@ -33,7 +33,6 @@ import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList;
import appeng.core.AELog;
import appeng.me.GridAccessException;
import appeng.me.helpers.IGridProxyable;
import appeng.me.storage.ITickingMonitor;
import appeng.util.inv.ItemHandlerIterator;
@@ -44,7 +43,6 @@ import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import net.minecraft.item.ItemStack;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.ItemHandlerHelper;
import java.util.*;
@@ -83,6 +81,8 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
stackCache = null;
ItemStack orgInput;
int slotCount = this.itemHandler.getSlots();
if( currentCached != null && iox.isSameType( currentCached ) )
{
// Cache is suitable, just update the count
@@ -94,10 +94,16 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
// We need a new stack :-(
orgInput = iox.createItemStack();
}
ItemStack remaining = ItemHandlerHelper.insertItem( this.itemHandler, orgInput, type == Actionable.SIMULATE );
ItemStack remaining = orgInput;
for ( int i = 0; i < slotCount && !remaining.isEmpty(); i++ )
{
remaining = this.itemHandler.insertItem( i, remaining, type == Actionable.SIMULATE );
}
// Store the stack in the cache for next time.
if (!remaining.isEmpty() && remaining != orgInput)
if( !remaining.isEmpty() && remaining != orgInput )
{
stackCache = remaining;
}
@@ -111,15 +117,9 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
if( type == Actionable.MODULATE )
{
try
{
this.proxyable.getProxy().getTick().alertDevice( this.proxyable.getProxy().getNode() );
}
catch( GridAccessException ex )
{
// meh
}
this.cache
.currentlyCached
.add( AEItemStack.fromItemStack( orgInput ).setStackSize( orgInput.getCount() - remaining.getCount() ) );
}
return AEItemStack.fromItemStack( remaining );
@@ -128,18 +128,17 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
@Override
public IAEItemStack extractItems( IAEItemStack request, Actionable mode, IActionSource src )
{
int remainingSize = Ints.saturatedCast(request.getStackSize());
int remainingSize = Ints.saturatedCast( request.getStackSize() );
// Use this to gather the requested items
ItemStack gathered = ItemStack.EMPTY;
final boolean simulate = ( mode == Actionable.SIMULATE );
for( int i = 0; i < this.itemHandler.getSlots(); i++ )
for ( int i = 0; i < this.itemHandler.getSlots(); i++ )
{
ItemStack stackInInventorySlot = this.itemHandler.getStackInSlot( i );
if (!request.isSameType(stackInInventorySlot))
if( !request.isSameType( stackInInventorySlot ) )
{
continue;
}
@@ -191,19 +190,17 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
if( !gathered.isEmpty() )
{
IAEItemStack gatheredAEItemStack = AEItemStack.fromItemStack( gathered );
if( mode == Actionable.MODULATE )
{
try
IAEItemStack e = this.cache.currentlyCached.findPrecise( gatheredAEItemStack );
if (e != null)
{
this.proxyable.getProxy().getTick().alertDevice( this.proxyable.getProxy().getNode() );
}
catch( GridAccessException ex )
{
// meh
e.decStackSize( gathered.getCount() );
}
}
return AEItemStack.fromItemStack( gathered );
return gatheredAEItemStack;
}
return null;
@@ -274,9 +271,10 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
private static class InventoryCache implements Iterable<ItemSlot>
{
private IAEItemStack[] cachedAeStacks = new IAEItemStack[0];
private final IItemHandler itemHandler;
private final StorageFilter mode;
IItemList<IAEItemStack> currentlyCached = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList();
public InventoryCache( IItemHandler itemHandler, StorageFilter mode )
{
@@ -286,7 +284,7 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
public IItemList<IAEItemStack> getAvailableItems( IItemList<IAEItemStack> out )
{
Arrays.stream( this.cachedAeStacks ).forEach( out::add );
currentlyCached.iterator().forEachRemaining( out::add );
return out;
}
@@ -298,93 +296,41 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
public List<IAEItemStack> update()
{
final List<IAEItemStack> changes = new ArrayList<>();
final int slots = this.itemHandler.getSlots();
// Make room for new slots
if( slots > this.cachedAeStacks.length )
{
this.cachedAeStacks = Arrays.copyOf( this.cachedAeStacks, slots );
}
IItemList<IAEItemStack> currentlyOnStorage = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList();
for( final ItemSlot is : this )
for ( final ItemSlot is : this )
{
// Save the old stuff
final IAEItemStack oldAeIS = this.cachedAeStacks[is.getSlot()];
final ItemStack newIS = !is.isExtractable() && this.getMode() == StorageFilter.EXTRACTABLE_ONLY ? ItemStack.EMPTY : is.getItemStack();
this.handlePossibleSlotChanges( is.getSlot(), oldAeIS, newIS, changes );
}
// Handle cases where the number of slots actually is lower now than before
if( slots < this.cachedAeStacks.length )
{
for( int slot = slots; slot < this.cachedAeStacks.length; slot++ )
if( !newIS.isEmpty() )
{
final IAEItemStack aeStack = this.cachedAeStacks[slot];
if( aeStack != null )
{
final IAEItemStack a = aeStack.copy();
a.setStackSize( -a.getStackSize() );
changes.add( a );
}
currentlyOnStorage.add( is.getAEItemStack() );
}
// Reduce the cache size
this.cachedAeStacks = Arrays.copyOf( this.cachedAeStacks, slots );
}
for ( final IAEItemStack is : currentlyCached )
{
is.setStackSize( -is.getStackSize() );
}
for ( final IAEItemStack is : currentlyOnStorage )
{
currentlyCached.add( is );
}
for ( final IAEItemStack is : currentlyCached )
{
if( is.getStackSize() != 0 )
{
changes.add( is );
}
}
currentlyCached = currentlyOnStorage;
return changes;
}
private void handlePossibleSlotChanges( int slot, IAEItemStack oldAeIS, ItemStack newIS, List<IAEItemStack> changes )
{
if( oldAeIS != null && oldAeIS.isSameType( newIS ) )
{
this.handleStackSizeChanged( slot, oldAeIS, newIS, changes );
}
else
{
this.handleItemChanged( slot, oldAeIS, newIS, changes );
}
}
private void handleStackSizeChanged( int slot, IAEItemStack oldAeIS, ItemStack newIS, List<IAEItemStack> changes )
{
// Still the same item, but amount might have changed
final long diff = newIS.getCount() - oldAeIS.getStackSize();
if( diff != 0 )
{
final IAEItemStack stack = oldAeIS.copy();
stack.setStackSize( newIS.getCount() );
this.cachedAeStacks[slot] = stack;
final IAEItemStack a = stack.copy();
a.setStackSize( diff );
changes.add( a );
}
}
private void handleItemChanged( int slot, IAEItemStack oldAeIS, ItemStack newIS, List<IAEItemStack> changes )
{
// Completely different item
this.cachedAeStacks[slot] = AEItemStack.fromItemStack( newIS );
// If we had a stack previously in this slot, notify the network about its disappearance
if( oldAeIS != null )
{
oldAeIS.setStackSize( -oldAeIS.getStackSize() );
changes.add( oldAeIS );
}
// Notify the network about the new stack. Note that this is null if newIS was null
if( this.cachedAeStacks[slot] != null )
{
changes.add( this.cachedAeStacks[slot] );
}
}
@Override
public Iterator<ItemSlot> iterator()
{
@@ -13,7 +13,6 @@ import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList;
import appeng.core.AELog;
import appeng.me.GridAccessException;
import appeng.me.helpers.IGridProxyable;
import appeng.me.storage.ITickingMonitor;
import appeng.util.item.AEItemStack;
@@ -24,7 +23,6 @@ import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import net.minecraft.item.ItemStack;
import java.util.*;
import java.util.stream.Collectors;
/**
@@ -85,14 +83,9 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
if( type == Actionable.MODULATE )
{
try
{
this.proxyable.getProxy().getTick().alertDevice( this.proxyable.getProxy().getNode() );
}
catch( GridAccessException ex )
{
// meh
}
this.cache
.currentlyCached
.add( AEItemStack.fromItemStack( orgInput ).setStackSize( orgInput.getCount() - remaining.getCount() ) );
}
return AEItemStack.fromItemStack( remaining );
@@ -102,7 +95,7 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
@Override
public IAEItemStack extractItems( IAEItemStack request, Actionable mode, IActionSource src )
{
int remainingSize = Ints.saturatedCast(request.getStackSize());
int remainingSize = Ints.saturatedCast( request.getStackSize() );
final boolean simulate = ( mode == Actionable.SIMULATE );
@@ -112,25 +105,22 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
{
// Something broke. It should never return more than we requested...
// We're going to silently eat the remainder
AELog.warn( "Mod that provided item handler %s is broken. Returned %s items while only requesting %d.",
this.itemRepository.getClass().getName(), extracted.toString(), remainingSize );
AELog.warn( "Mod that provided item handler %s is broken. Returned %s items while only requesting %d.", this.itemRepository.getClass().getName(), extracted.toString(), remainingSize );
extracted.setCount( remainingSize );
}
if( !extracted.isEmpty() )
{
IAEItemStack extractedAEItemStack = AEItemStack.fromItemStack( extracted );
if( mode == Actionable.MODULATE )
{
try
IAEItemStack e = this.cache.currentlyCached.findPrecise( extractedAEItemStack );
if (e != null)
{
this.proxyable.getProxy().getTick().alertDevice( this.proxyable.getProxy().getNode() );
}
catch( GridAccessException ex )
{
// meh
e.decStackSize( extracted.getCount() );
}
}
return AEItemStack.fromItemStack( extracted );
return extractedAEItemStack;
}
return null;
}
@@ -202,7 +192,7 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
private static class InventoryCache
{
private IAEItemStack[] cachedAeStacks = new IAEItemStack[0];
private IItemList<IAEItemStack> currentlyCached = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList();
private final IItemRepository iItemRepository;
public InventoryCache( IItemRepository iItemRepository )
@@ -212,7 +202,7 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
public IItemList<IAEItemStack> getAvailableItems( IItemList<IAEItemStack> out )
{
Arrays.stream( this.cachedAeStacks ).forEach( out::add );
currentlyCached.iterator().forEachRemaining( out::add );
return out;
}
@@ -220,95 +210,31 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
{
final List<IAEItemStack> changes = new ArrayList<>();
List<IAEItemStack> out = this.iItemRepository.getAllItems().stream().map( s -> AEItemStack.fromItemStack( s.itemPrototype ).setStackSize( s.count ) ).collect( Collectors.toList() );
IItemList<IAEItemStack> currentlyOnStorage = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList();
this.iItemRepository.getAllItems().stream().map( s -> AEItemStack.fromItemStack( s.itemPrototype ).setStackSize( s.count ) ).forEach( currentlyOnStorage::add );
final int size = out.size();
// Make room for new slots
if( size > this.cachedAeStacks.length )
for ( final IAEItemStack is : currentlyCached )
{
this.cachedAeStacks = Arrays.copyOf( this.cachedAeStacks, size );
is.setStackSize( -is.getStackSize() );
}
for( int x = 0; x < size; x++ )
for ( final IAEItemStack is : currentlyOnStorage )
{
// Save the old stuff
final IAEItemStack oldAeIS = this.cachedAeStacks[x];
final IAEItemStack newIS = out.get( x );
this.handlePossibleSlotChanges( x, oldAeIS, newIS, changes );
currentlyCached.add( is );
}
// Handle cases where the number of slots actually is lower now than before
if( size < this.cachedAeStacks.length )
for ( final IAEItemStack is : currentlyCached )
{
for( int x = 0; x < this.cachedAeStacks.length; x++ )
if( is.getStackSize() != 0 )
{
final IAEItemStack aeStack = this.cachedAeStacks[x];
if( aeStack != null )
{
final IAEItemStack a = aeStack.copy();
a.setStackSize( -a.getStackSize() );
changes.add( a );
}
changes.add( is );
}
// Reduce the cache size
this.cachedAeStacks = Arrays.copyOf( this.cachedAeStacks, size );
}
currentlyCached = currentlyOnStorage;
return changes;
}
private void handlePossibleSlotChanges( int slot, IAEItemStack oldAeIS, IAEItemStack newIS, List<IAEItemStack> changes )
{
if( oldAeIS != null && oldAeIS.isSameType( newIS ) )
{
this.handleStackSizeChanged( slot, oldAeIS, newIS, changes );
}
else
{
this.handleItemChanged( slot, oldAeIS, newIS, changes );
}
}
private void handleStackSizeChanged( int slot, IAEItemStack oldAeIS, IAEItemStack newIS, List<IAEItemStack> changes )
{
// Still the same item, but amount might have changed
final long diff = newIS.getStackSize() - oldAeIS.getStackSize();
if( diff != 0 )
{
final IAEItemStack stack = oldAeIS.copy();
stack.setStackSize( newIS.getStackSize() );
this.cachedAeStacks[slot] = stack;
final IAEItemStack a = stack.copy();
a.setStackSize( diff );
changes.add( a );
}
}
private void handleItemChanged( int slot, IAEItemStack oldAeIS, IAEItemStack newIS, List<IAEItemStack> changes )
{
// Completely different item
this.cachedAeStacks[slot] = newIS ;
// If we had a stack previously in this slot, notify the network about its disappearance
if( oldAeIS != null )
{
oldAeIS.setStackSize( -oldAeIS.getStackSize() );
changes.add( oldAeIS );
}
// Notify the network about the new stack. Note that this is null if newIS was null
if( this.cachedAeStacks[slot] != null )
{
changes.add( this.cachedAeStacks[slot] );
}
}
}
}
@@ -258,20 +258,17 @@ public class PartStorageBus extends PartUpgradeable implements IGridTickable, IC
@Override
public void postChange( final IBaseMonitor<IAEItemStack> monitor, final Iterable<IAEItemStack> change, final IActionSource source )
{
if( source == this.mySrc || source.machine().map( machine -> machine == this ).orElse( false ) )
try
{
try
if( this.getProxy().isActive() )
{
if( this.getProxy().isActive() )
{
this.getProxy().getStorage().postAlterationOfStoredItems( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ), change, this.mySrc );
}
}
catch( final GridAccessException e )
{
// :(
this.getProxy().getStorage().postAlterationOfStoredItems( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ), change, this.mySrc );
}
}
catch( final GridAccessException e )
{
// :(
}
}
@Override
@@ -598,7 +595,7 @@ public class PartStorageBus extends PartUpgradeable implements IGridTickable, IC
{
if( channel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) )
{
final IMEInventoryHandler<IAEItemStack> out = this.getProxy().isActive() ? this.getInternalHandler() : null;
final IMEInventoryHandler<IAEItemStack> out = this.getInternalHandler();
if( out != null )
{
return Collections.singletonList( out );
@@ -21,10 +21,12 @@ package appeng.parts.reporting;
import java.io.IOException;
import appeng.api.networking.events.MENetworkChannelsChanged;
import appeng.api.networking.events.MENetworkEventSubscribe;
import appeng.api.networking.events.MENetworkPowerStatusChange;
import appeng.api.storage.channels.IFluidStorageChannel;
import appeng.api.storage.data.IAEFluidStack;
import appeng.fluids.util.AEFluidStack;
import appeng.util.item.AEStack;
import io.netty.buffer.ByteBuf;
import net.minecraft.client.renderer.GlStateManager;
@@ -43,7 +45,6 @@ import net.minecraftforge.fml.relauncher.SideOnly;
import appeng.api.AEApi;
import appeng.api.implementations.parts.IPartStorageMonitor;
import appeng.api.networking.security.IActionSource;
import appeng.api.networking.storage.IStackWatcher;
import appeng.api.networking.storage.IStackWatcherHost;
import appeng.api.parts.IPartModel;
@@ -52,7 +53,6 @@ import appeng.api.storage.IStorageChannel;
import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IAEStack;
import appeng.api.storage.data.IItemList;
import appeng.client.render.TesrRenderHelper;
import appeng.core.localization.PlayerMessages;
import appeng.helpers.Reflected;
@@ -385,19 +385,87 @@ public abstract class AbstractPartMonitor extends AbstractPartDisplay implements
this.configureWatchers();
}
@MENetworkEventSubscribe
public void powerStatusChange( final MENetworkPowerStatusChange ev )
{
if( !this.getProxy().isPowered() )
{
if( this.myWatcher != null )
{
if( this.configuredItem != null )
{
this.configuredItem.setStackSize( 0 );
}
if( this.configuredFluid != null )
{
this.configuredFluid.setStackSize( 0 );
}
}
}
else
{
try
{
if( this.configuredItem != null )
{
this.updateReportingValue( this.getProxy().getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) );
}
if( this.configuredFluid != null )
{
this.updateReportingValue( this.getProxy().getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ) );
}
}
catch( final GridAccessException e )
{
// ;P
}
}
}
@MENetworkEventSubscribe
public void channelChanged( final MENetworkChannelsChanged c )
{
if( !this.getProxy().isPowered() )
{
if( this.myWatcher != null )
{
if( this.configuredItem != null )
{
this.configuredItem.setStackSize( 0 );
}
if( this.configuredFluid != null )
{
this.configuredFluid.setStackSize( 0 );
}
}
}
else
{
try
{
if( this.configuredItem != null )
{
this.updateReportingValue( this.getProxy().getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) );
}
if( this.configuredFluid != null )
{
this.updateReportingValue( this.getProxy().getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ) );
}
}
catch( final GridAccessException e )
{
// ;P
}
}
}
@Override
public void onStackChange( final IItemList o, final IAEStack fullStack, final IAEStack diffStack, final IActionSource src, final IStorageChannel chan )
public void onStackChange( final IAEStack diffStack, final IStorageChannel chan )
{
if( this.configuredItem != null )
{
if( fullStack == null )
{
this.configuredItem.setStackSize( 0 );
}
else
{
this.configuredItem.setStackSize( fullStack.getStackSize() );
}
long diff = this.configuredItem.getStackSize() + diffStack.getStackSize();
this.configuredItem.setStackSize( diff >= 0 ? this.configuredItem.getStackSize() + diffStack.getStackSize() : 0 );
final long stackSize = this.configuredItem.getStackSize();
final String humanReadableText = NUMBER_CONVERTER.toWideReadableForm( stackSize );
@@ -410,14 +478,8 @@ public abstract class AbstractPartMonitor extends AbstractPartDisplay implements
}
else if( this.configuredFluid != null )
{
if( fullStack == null )
{
this.configuredFluid.setStackSize( 0 );
}
else
{
this.configuredFluid.setStackSize( fullStack.getStackSize() );
}
long diff = this.configuredFluid.getStackSize() + diffStack.getStackSize();
this.configuredFluid.setStackSize( diff >= 0 ? this.configuredFluid.getStackSize() + diffStack.getStackSize() : 0 );
final long stackSize = this.configuredFluid.getStackSize() / 1000;
final String humanReadableText = NUMBER_CONVERTER.toWideReadableForm( stackSize ) + "B";
+7 -5
View File
@@ -1246,18 +1246,20 @@ public class Platform
if( itemToAdd < input.getStackSize() )
{
final long original = input.getStackSize();
final T leftover = input.copy();
final T split = input.copy();
split.decStackSize( itemToAdd );
input.setStackSize( itemToAdd );
split.add( cell.injectItems( input, 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 - split.getStackSize();
final long diff = original - leftover.getStackSize();
Stats.ItemsInserted.addToPlayer( player, (int) diff );
} );
return split;
return leftover;
}
final T ret = cell.injectItems( input, Actionable.MODULATE, src );
@@ -148,7 +148,7 @@ class FuzzyItemVariantList extends ItemVariantList {
*/
static ItemDamageBound makeLowerBound(final ItemStack stack, final FuzzyMode fuzzy)
{
Preconditions.checkState( stack.getItem().isDamageable() || (Platform.isModLoaded( "gregtech" ) && stack.getItem() instanceof MetaTool), "Item#isDamageable() has to be true" );
Preconditions.checkState( stack.getItem().isDamageable() , "Item#isDamageable() has to be true" );
int damage;
if( fuzzy == FuzzyMode.IGNORE_ALL )
@@ -176,7 +176,7 @@ class FuzzyItemVariantList extends ItemVariantList {
* 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.isModLoaded( "gregtech" ) && stack.getItem() instanceof MetaTool), "Item#isDamageable() has to be true");
Preconditions.checkState(stack.getItem().isDamageable() , "Item#isDamageable() has to be true");
int damage;
if (fuzzy == FuzzyMode.IGNORE_ALL) {
+1 -1
View File
@@ -151,7 +151,7 @@ public final class ItemList implements IItemList<IAEItemStack> {
}
private ItemVariantList makeRecordMap(Item item) {
if (item.isDamageable() || (Platform.isModLoaded( "gregtech" ) && item instanceof MetaTool) ) {
if (item.isDamageable() ) {
return new FuzzyItemVariantList();
} else {
return new NormalItemVariantList();
@@ -43,7 +43,7 @@ public class OreReference
return this.otherOptions;
}
List<IAEItemStack> getAEEquivalents()
public List<IAEItemStack> getAEEquivalents()
{
if( this.aeOtherOptions == null )
{
@@ -18,32 +18,20 @@
"type": "appliedenergistics2:part",
"part": "material.card_pattern_expansion"
},
"type": "appliedenergistics2:part_shaped",
"pattern": [
"ci"
],
"type": "appliedenergistics2:part_shapeless",
"ingredients": [
{
"type": "appliedenergistics2:part",
"part": "material.advanced_card"
"part": "material.advanced_card"
},
{
"key": "#"
}
],
"key": {
"i": [
{
"item": "appliedenergistics2:interface"
},
{
"type": "appliedenergistics2:part",
"part": "part.interface"
}],
"c": {
"type": "appliedenergistics2:part",
"part": "material.advanced_card"
}
}
[
{
"item": "appliedenergistics2:interface"
},
{
"type": "appliedenergistics2:part",
"part": "part.interface"
}
]
]
}