Compare commits

...

93 Commits

Author SHA1 Message Date
PrototypeTrousers 304f394497 cut crafting tree earlier if the item is available
fix job byte size to 8 per crafting + 1 per item used/stored
2021-11-02 15:33:14 -03:00
PrototypeTrousers 50f21125c8 log if non-patterned items go missing before starting a craft 2021-11-02 02:00:01 -03:00
PrototypeTrousers 30b85bd239 potential fix for showing proper item names when failing to start craft 2021-11-01 23:23:45 -03:00
PrototypeTrousers 9ce00d338f only try to extract if its already in the cache 2021-10-29 17:04:24 -03:00
PrototypeTrousers 11f5b71089 update directly instead of relying on forge events 2021-10-29 15:14:33 -03:00
PrototypeTrousers e7da72163b backported #5349 2021-10-29 15:13:46 -03:00
PrototypeTrousers 6d7c65dd70 potential fix for an infinite loop while adding nodes 2021-10-29 14:09:19 -03:00
PrototypeTrousers 5e21101619 n-to-n p2p
network monitor checks nesting by action source
2021-10-28 23:49:16 -03:00
PrototypeTrousers 3db8d0185f fix security terminal and portable cell stored items not showing 2021-10-23 17:56:15 -03:00
PrototypeTrousers 2f5ecfe638 energy fixes 2021-10-22 15:37:08 -03:00
PrototypeTrousers 75843e802d WIP 2021-10-21 12:22:00 -03:00
PrototypeTrousers e41b6943aa fix swapping cells giving wrong item/fluid count 2021-09-28 23:29:52 -03:00
PrototypeTrousers 92347ad2f5 fix looping item count and hopefully energy issues 2021-09-26 22:07:16 -03:00
PrototypeTrousers 517bd77df7 yet another try at energy issues
fix requesters not being added to the energy grid


partially revert the energy 'fixes'


potential desync on item count


energy and items change
2021-09-17 00:09:49 -03:00
PrototypeTrousers 19f928a9a5 fluid pass 2021-09-13 04:22:52 -03:00
PrototypeTrousers 73251a0fe5 more item count changes.... 2021-09-13 02:10:28 -03:00
PrototypeTrousers 9335daff7d Revert "fixes item showing incorrect amounts"
This reverts commit 618e9390c6.
2021-09-11 22:48:45 -03:00
PrototypeTrousers cc5377d53b fluid storage bus handler cache tweaks and simplify energy cache 2021-09-06 23:51:32 -03:00
Salomão 059f20d801 yet another try at fixing power issues 2021-09-05 20:28:37 -03:00
Salomão d229570495 try to fix energy issues again
fix issue with voiding p2p parts when shift-right clicking with a memory card
2021-09-04 18:59:46 -03:00
PrototypeTrousers c284748b6c fix p2p not updating properly on memory card loading 2021-09-02 20:42:02 -03:00
PrototypeTrousers 880a9c8821 another case of wrong item count caused by weak reset logic overriding
a full reset needed
2021-09-01 16:11:45 -03:00
PrototypeTrousers c68c02ef3b more cases of wrong item counting fixed 2021-08-26 22:03:23 -03:00
PrototypeTrousers 89c4d2736c borrowed some fancy, colored, fluid rendering from gregicality
thank you @Yefancy
2021-08-23 22:35:26 -03:00
PrototypeTrousers 01778794e5 try to fix #51 2021-08-22 23:59:02 -03:00
PrototypeTrousers 8f2a06e457 fix #49. you can now actually clear storage and conversion monitors 2021-08-20 23:26:33 -03:00
PrototypeTrousers 2d71b75019 actually fix it 2021-08-17 07:46:47 -03:00
PrototypeTrousers 9f09cd04d4 enforce cache reset of storage bus attached to interfaces were configs
changed
2021-08-16 21:55:35 -03:00
PrototypeTrousers b041fae0d5 fix storage/monitors wrong item count and interactions 2021-08-16 19:26:25 -03:00
Salomão c466a0e00e fix items in level emitters with crafting cards not showing up 2021-08-14 09:44:47 -03:00
PrototypeTrousers 618e9390c6 fixes item showing incorrect amounts 2021-08-13 00:17:53 -03:00
PrototypeTrousers 9a71bfb0f0 hash drawers handler by the amount of slots 2021-08-10 09:06:18 -03:00
PrototypeTrousers 9680123906 fix JEI targeting disabled slots as valid 2021-08-06 06:25:12 -03:00
PrototypeTrousers 87730894e9 Update CHANGES.md 2021-08-05 21:36:49 -03:00
PrototypeTrousers 71c944daea fix fluid storagebus NPE crash 2021-08-04 20:49:38 -03:00
PrototypeTrousers e96b4a698a fluid containers can now be drained/filled from fluid interfaces 2021-08-04 19:38:00 -03:00
PrototypeTrousers 1d5465a4b8 partially revert fda8c8 2021-08-04 09:28:47 -03:00
PrototypeTrousers 09cbfe96d6 fix NPE when configuring storage busses 2021-08-01 17:36:23 -03:00
PrototypeTrousers cbdad7c58e hopefully fix storage busses for good
1
2021-07-31 23:05:59 -03:00
PrototypeTrousers 6be96956a9 small optimization to import/export busses 2021-07-30 23:26:42 -03:00
PrototypeTrousers e376e002e9 actually fix #43 ? .... 2021-07-30 07:51:57 -03:00
PrototypeTrousers 0b9df31d4e fix broken recipes resulting in item dupes 2021-07-28 19:46:42 -03:00
PrototypeTrousers cef6dbf0d7 fix copy-paste error in the fluid storage bus constructor 2021-07-27 19:32:59 -03:00
Salomão e4af7b1947 fix adapters insert-only mode still reporting items 2021-07-27 12:51:24 -03:00
Salomão 6eadb8f861 fix IO-Port transfer stopping too soon 2021-07-27 11:10:45 -03:00
PrototypeTrousers b6b6a83563 do the same for fluid storage bus 2021-07-26 20:34:15 -03:00
PrototypeTrousers 32ab4c6af4 Merge remote-tracking branch 'PrototypeTrousers/AE2-Omnifactory' into AE2-Omnifactory 2021-07-26 18:25:24 -03:00
PrototypeTrousers fda8c87410 attempts to fix #42 and #43 2021-07-26 18:25:08 -03:00
PrototypeTrousers 389e060707 Merge pull request #41 from BalaM314/patch-1
Fix #27
2021-07-23 10:40:01 -03:00
BalaM314 0942a90ef4 Fix #27
Not sure exactly what method is causing a crash, but added a catch to just say it is located in another dimension
2021-07-23 15:11:07 +05:30
PrototypeTrousers 8cef06512a restore breaking API change 2021-07-22 21:50:56 -03:00
PrototypeTrousers 8e4658be20 fix power not going to sub-networks
renamed variables
2021-07-18 17:52:01 -03:00
PrototypeTrousers 0bd2bd6b5a dont pause main thread when calculating 2021-07-17 22:15:54 -03:00
PrototypeTrousers db2c4c4325 ensure the local energy cache is iterated last 2021-07-17 22:11:11 -03:00
Salomão ac793ee847 Merge branch 'delta' into AE2-Omnifactory 2021-07-17 14:48:22 -03:00
Salomão 6404f26cca Merge remote-tracking branch 'origin/fluid-terminal-multiple-containers' into AE2-Omnifactory 2021-07-16 14:22:21 -03:00
Salomão ced6ad865c re-introduce time-based calculation quota
player initiated crafting calculation is not affected
2021-07-16 14:22:09 -03:00
Salomão 24750f00b1 reworked how changes are propagated in the network 2021-07-16 14:13:48 -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
Salomão aa5d5e3623 set idle power usage of expanded interface to a power of four 2021-06-21 16:25:26 -03:00
Salomão 42f4ef2855 tweak GUIs 2021-06-21 15:54:40 -03:00
Salomão 3eb2582f29 Merge branch 'bigger-interfaces' into AE2-Omnifactory 2021-06-21 15:22:13 -03:00
Salomão 307f86ded8 increase AE energy polling rate from once every 90 to once every 3 ticks 2021-06-18 12:48:01 -03:00
Salomão 56f57e18a5 Merge branch 'wip' into AE2-Omnifactory 2021-06-17 23:32:34 -03:00
Salomão eab695b692 try to not void fluids in fluid terminal when running out of power 2021-06-17 23:32:16 -03:00
Salomão 0fb393820b half-undo wip 2021-06-17 00:07:06 -03:00
Salomão 01fe5c7a8b jei transfer tweaks..again 2021-06-16 19:22:52 -03:00
Salomão 8468b47443 workaround for damaged tools and gtce tools not being set as damageable 2021-06-15 12:46:44 -03:00
Salomão 6cb583c918 clear old NBT from cells 2021-06-15 12:41:51 -03:00
Salomão d69395a117 cache fixes 2021-06-14 12:57:49 -03:00
Salomão 59effe8131 save NBT properly 2021-06-14 11:51:17 -03:00
Salomão 6f42876963 Merge branch 'fastutil' into AE2-Omnifactory 2021-06-14 10:54:12 -03:00
Salomão 08952b48dd backported fastutil implementation of the item list 2021-06-14 10:53:50 -03:00
Salomão e3c9c4ce65 clear cells of craftable status
remove unsupported removal call
2021-06-14 10:20:58 -03:00
Salomão 7b91da58c0 resolve suspicious calls 2021-06-14 02:33:43 -03:00
Salomão 26c06bca15 fix IO-Port copying craftable boolean 2021-06-14 02:33:23 -03:00
Salomão 4458bd28ab refresh ETA not only when items are crafted 2021-06-13 20:30:52 -03:00
Salomão df3f00d978 try to fix remaining concurrent modifications to energy grid 2021-06-13 20:29:56 -03:00
Salomão 18ae994ee4 try to avoid CME by copying FE p2p outputs before iterating
backported 1c88ea7b78 and attempt to fix #25 with feedback
2021-06-10 21:13:41 -03:00
Salomão 47888b5546 reworked Adapter caches ( storage busses ) 2021-06-09 16:31:49 -03:00
Salomão e18593feb5 fix pattern inventory size mismatch 2021-06-08 23:46:37 -03:00
Salomão af4c3de55e fix client desync 2021-06-08 23:23:12 -03:00
Salomão bea29331a3 implement pattern expansion cards for interfaces
Maximum of 4 rows
Uses 4x the previous tier for crafting operations (4 rows = 64 interfaces consumption)
2021-06-08 23:23:12 -03:00
Salomão 9b9579b358 storage drawer cache optimisation 2021-06-08 23:22:00 -03:00
Salomão 52da4f9528 fix shift-clicking patterns from pattern slot sometimes voiding them 2021-06-05 18:54:26 -03:00
Salomão 50aac2c768 send the player a message if the crafting job succeeds on simulation
but fails on real extraction
2021-06-02 23:46:35 -03:00
117 changed files with 3782 additions and 2570 deletions
+13 -2
View File
@@ -15,6 +15,10 @@ Fixes:
- Exclusive Blocking mode for GTCE ( shapes, molds and configured circuits do not block GTCE machines ) - Exclusive Blocking mode for GTCE ( shapes, molds and configured circuits do not block GTCE machines )
- Blocking modes default to block on any item in the iventory the entity exposes - Blocking modes default to block on any item in the iventory the entity exposes
- Fuzzy includes items that report that they're damageable, but report a maxDamage of 0 ( auto-crafting of basic capacitors -> resonant capacitors is now possible ) <- Broken item implementation. - Fuzzy includes items that report that they're damageable, but report a maxDamage of 0 ( auto-crafting of basic capacitors -> resonant capacitors is now possible ) <- Broken item implementation.
- Fix CME exceptions on the energy grid
- Fix AE going offline even with enough power by extracting from the local buffer always last
- Fix IO-Port copying craftable flag into items
- Fix NBT of old items not clearing on drives that reached 64 types once
Performance: Performance:
@@ -24,6 +28,9 @@ Performance:
- Count items set in interfaces before queuing crafting for them needlessly - Count items set in interfaces before queuing crafting for them needlessly
- Backported b7ca98d ( Avoid copying items on simulated item extraction ) - Backported b7ca98d ( Avoid copying items on simulated item extraction )
- Cache some level emitters functions - Cache some level emitters functions
- Reduced import bus insert simulation to 1 before real insertion (if possible)
- Backported itemlist re-implementation along with pattern changes to avoid CraftingManager fallback issues
- Instead of recalculating all the content of the network on every change, track the changes properly and apply them to the cached list of items
QOL: QOL:
@@ -31,7 +38,7 @@ QOL:
- Added bar on the interface terminal that search by inputs ( The one on the LEFT, also searchs by interface name ) - Added bar on the interface terminal that search by inputs ( The one on the LEFT, also searchs by interface name )
- Shortcut to molecular assemblers with free slots on the terminal interface by @Theisyat - Shortcut to molecular assemblers with free slots on the terminal interface by @Theisyat
- Toggle button on interface terminal to hide full interfaces - Toggle button on interface terminal to hide full interfaces
- JEI "U""R" and "A" (Usages/Recipes/Bookmark) now work on the Crafting Status GUI. ( the one that shows the total items to craft, and whats missing) - JEI "U", "R" and "A" (Usages/Recipes/Bookmark) now work on the Crafting Status GUI. ( the one that shows the total items to craft, and whats missing)
- Patterns can now be made with items currently showing on JEI. ( This is overriden by Just Enough Energistics. ) - Patterns can now be made with items currently showing on JEI. ( This is overriden by Just Enough Energistics. )
- Added multiplier buttons to processing pattern gui - Added multiplier buttons to processing pattern gui
- Switched crafting terminal JEI search to fuzzy mode. If the recipe uses a damageable item, AE will try to grab it ( damaged tools ) - Switched crafting terminal JEI search to fuzzy mode. If the recipe uses a damageable item, AE will try to grab it ( damaged tools )
@@ -39,7 +46,11 @@ QOL:
- Encoded patterns can be draggred on the interface terminal. - Encoded patterns can be draggred on the interface terminal.
- Storage Monitor and Conversion Monitor now also ccepts fluids - Storage Monitor and Conversion Monitor now also ccepts fluids
- Draggable JEI ghost items (also works on bookmarked items. SHIFT + Click will move the hovered item into the first free target slot) - Draggable JEI ghost items (also works on bookmarked items. SHIFT + Click will move the hovered item into the first free target slot)
-JEI auto switches between crafting and processing patterns - JEI auto switches between crafting and processing patterns
- GTCE Blocking mode work through phantom itemfaces
- Shift-clicking blank patterns into the pattern terminal will try to fill the blank pattern slots first
- Mismached simulated/real item count ( most often due to compacting drawers ) will now tell the player wich item cause the failure when trying to start a craft
- Added 'pattern expansion' cards that adds an extra row of patterns to interfaces. up to 3 card on an interface. (each card will increase the interface idle power draw by 4 times)
HOTKEYS: HOTKEYS:
+1 -1
View File
@@ -3,7 +3,7 @@ aechannel=stable
aebuild=7 aebuild=7
aegroup=appeng aegroup=appeng
aebasename=appliedenergistics2 aebasename=appliedenergistics2
trousers=omni-fixes-v21b trousers=omni-fixes-v49b
######################################################### #########################################################
# Versions # # Versions #
+1 -1
View File
@@ -80,7 +80,7 @@ configurations {
} }
dependencies { dependencies {
compileOnly "gregtechce:gregtech:1.12.2:1.12.0.662" compileOnly "gregtechce:gregtech:1.12.2:1.15.1.735"
// installable runtime dependencies // installable runtime dependencies
mods "mcp.mobius.waila:Hwyla:${hwyla_version}" mods "mcp.mobius.waila:Hwyla:${hwyla_version}"
+2 -1
View File
@@ -46,7 +46,8 @@ public enum Upgrades
*/ */
FUZZY( 1 ), FUZZY( 1 ),
SPEED( 1 ), SPEED( 1 ),
INVERTER( 1 ); INVERTER( 1 ),
PATTERN_EXPANSION(1);
private final int tier; private final int tier;
private final Map<ItemStack, Integer> supportedMax = new HashMap<>(); private final Map<ItemStack, Integer> supportedMax = new HashMap<>();
@@ -89,6 +89,8 @@ public interface IMaterials
IItemDefinition cardCapacity(); IItemDefinition cardCapacity();
IItemDefinition cardPatternExpansion();
IItemDefinition cardFuzzy(); IItemDefinition cardFuzzy();
IItemDefinition cardInverter(); IItemDefinition cardInverter();
@@ -31,6 +31,9 @@ import net.minecraft.world.World;
import appeng.api.implementations.ICraftingPatternItem; import appeng.api.implementations.ICraftingPatternItem;
import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IAEItemStack;
import java.util.Collections;
import java.util.List;
/** /**
* do not implement provided by {@link ICraftingPatternItem} * do not implement provided by {@link ICraftingPatternItem}
@@ -84,6 +87,11 @@ public interface ICraftingPatternDetails
*/ */
boolean canSubstitute(); 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. * Allow using this INSTANCE of the pattern details to preform the crafting action with performance enhancements.
* *
@@ -44,10 +44,7 @@ public interface IStackWatcherHost
/** /**
* Called when a watched item changes amounts. * Called when a watched item changes amounts.
* *
* @param o changed item list
* @param fullStack old stack
* @param diffStack new stack * @param diffStack new stack
* @param src action source
* @param chan storage channel * @param chan storage channel
*/ */
void onStackChange( IItemList<?> o, IAEStack<?> fullStack, IAEStack<?> diffStack, IActionSource src, IStorageChannel<?> chan ); void onStackChange( IItemList<?> o, IAEStack<?> fullStack, IAEStack<?> diffStack, IActionSource src, IStorageChannel<?> chan );
@@ -51,6 +51,7 @@ public interface IStorageGrid extends IGridCache, IStorageMonitorable
* @param input injected items * @param input injected items
*/ */
void postAlterationOfStoredItems( IStorageChannel<?> chan, Iterable<? extends IAEStack<?>> input, IActionSource src ); void postAlterationOfStoredItems( IStorageChannel<?> chan, Iterable<? extends IAEStack<?>> input, IActionSource src );
void postCraftablesChanges( IStorageChannel<?> chan, Iterable<? extends IAEStack<?>> input, IActionSource src);
/** /**
* Used to add a cell provider to the storage system * Used to add a cell provider to the storage system
@@ -112,4 +112,13 @@ public interface IAEItemStack extends IAEStack<IAEItemStack>
* @return definition stack * @return definition stack
*/ */
ItemStack getDefinition(); ItemStack getDefinition();
/**
* Compare this AE item stack to another item stack, but ignores
* the amount. It checks the item type, NBT and damage values.
*
* @param is An item stack
*/
boolean equals(ItemStack is);
} }
@@ -50,7 +50,7 @@ public class GuiInterface extends GuiUpgradeable
public GuiInterface( final InventoryPlayer inventoryPlayer, final IInterfaceHost te ) public GuiInterface( final InventoryPlayer inventoryPlayer, final IInterfaceHost te )
{ {
super( new ContainerInterface( inventoryPlayer, te ) ); super( new ContainerInterface( inventoryPlayer, te ) );
this.ySize = 211; this.ySize = 256;
} }
@Override @Override
@@ -62,8 +62,7 @@ public class GuiInterface extends GuiUpgradeable
this.BlockMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.BLOCK, YesNo.NO ); this.BlockMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.BLOCK, YesNo.NO );
this.buttonList.add( this.BlockMode ); this.buttonList.add( this.BlockMode );
this.interfaceMode = new GuiToggleButton( this.guiLeft - 18, this.guiTop + 26, 84, 85, GuiText.InterfaceTerminal this.interfaceMode = new GuiToggleButton( this.guiLeft - 18, this.guiTop + 26, 84, 85, GuiText.InterfaceTerminal.getLocal(), GuiText.InterfaceTerminalHint.getLocal() );
.getLocal(), GuiText.InterfaceTerminalHint.getLocal() );
this.buttonList.add( this.interfaceMode ); this.buttonList.add( this.interfaceMode );
} }
@@ -86,13 +85,20 @@ public class GuiInterface extends GuiUpgradeable
this.fontRenderer.drawString( GuiText.StoredItems.getLocal(), 8, 6 + 60 + 7, 4210752 ); this.fontRenderer.drawString( GuiText.StoredItems.getLocal(), 8, 6 + 60 + 7, 4210752 );
this.fontRenderer.drawString( GuiText.Patterns.getLocal(), 8, 6 + 73 + 7, 4210752 ); this.fontRenderer.drawString( GuiText.Patterns.getLocal(), 8, 6 + 73 + 7, 4210752 );
this.fontRenderer.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 );
} }
@Override @Override
protected String getBackground() protected String getBackground()
{ {
return "guis/interface.png"; int upgrades = ( (ContainerInterface) this.cvb ).getPatternUpgrades();
if( upgrades == 0 )
{
return "guis/newinterface.png";
}
else
{
return "guis/newinterface" + upgrades + ".png";
}
} }
@Override @Override
@@ -117,4 +123,5 @@ public class GuiInterface extends GuiUpgradeable
NetworkHandler.instance().sendToServer( new PacketConfigButton( this.BlockMode.getSetting(), backwards ) ); NetworkHandler.instance().sendToServer( new PacketConfigButton( this.BlockMode.getSetting(), backwards ) );
} }
} }
} }
@@ -24,8 +24,13 @@ import java.util.*;
import appeng.api.config.ActionItems; import appeng.api.config.ActionItems;
import appeng.api.config.Settings; import appeng.api.config.Settings;
import appeng.api.config.Upgrades;
import appeng.client.gui.widgets.GuiImgButton; import appeng.client.gui.widgets.GuiImgButton;
import appeng.core.worlddata.IWorldPlayerMapping; import appeng.core.worlddata.IWorldPlayerMapping;
import appeng.helpers.DualityInterface;
import appeng.parts.misc.PartInterface;
import appeng.tile.inventory.AppEngInternalInventory;
import appeng.tile.misc.TileInterface;
import appeng.util.BlockPosUtils; import appeng.util.BlockPosUtils;
import com.google.common.collect.HashMultimap; import com.google.common.collect.HashMultimap;
@@ -69,6 +74,7 @@ public class GuiInterfaceTerminal extends AEBaseGui
private final HashMultimap<String, ClientDCInternalInv> byName = HashMultimap.create(); private final HashMultimap<String, ClientDCInternalInv> byName = HashMultimap.create();
private final HashMap<ClientDCInternalInv,BlockPos> blockPosHashMap = new HashMap<>(); private final HashMap<ClientDCInternalInv,BlockPos> blockPosHashMap = new HashMap<>();
private final HashMap<GuiButton,ClientDCInternalInv> guiButtonHashMap = new HashMap<>(); private final HashMap<GuiButton,ClientDCInternalInv> guiButtonHashMap = new HashMap<>();
private final Map<ClientDCInternalInv,Integer> numUpgradesMap = new HashMap<>();
private final ArrayList<String> names = new ArrayList<>(); private final ArrayList<String> names = new ArrayList<>();
private final ArrayList<Object> lines = new ArrayList<>(); private final ArrayList<Object> lines = new ArrayList<>();
private final Set<Object> matchedStacks = new HashSet<>(); private final Set<Object> matchedStacks = new HashSet<>();
@@ -91,7 +97,7 @@ public class GuiInterfaceTerminal extends AEBaseGui
final GuiScrollbar scrollbar = new GuiScrollbar(); final GuiScrollbar scrollbar = new GuiScrollbar();
this.setScrollBar( scrollbar ); this.setScrollBar( scrollbar );
this.xSize = 208; this.xSize = 208;
this.ySize = 256; this.ySize = 255;
} }
@Override @Override
@@ -136,36 +142,43 @@ public class GuiInterfaceTerminal extends AEBaseGui
this.fontRenderer.drawString( this.getGuiDisplayName( GuiText.InterfaceTerminal.getLocal() ), 8, 6, 4210752 ); this.fontRenderer.drawString( this.getGuiDisplayName( GuiText.InterfaceTerminal.getLocal() ), 8, 6, 4210752 );
this.fontRenderer.drawString( GuiText.inventory.getLocal(), this.offsetX + 2, this.ySize - 96 + 3, 4210752 ); this.fontRenderer.drawString( GuiText.inventory.getLocal(), this.offsetX + 2, this.ySize - 96 + 3, 4210752 );
final int ex = this.getScrollBar().getCurrentScroll(); final int currentScroll = this.getScrollBar().getCurrentScroll();
this.guiButtonNextAssembler = new GuiImgButton(guiLeft + 123, guiTop + 25,Settings.ACTIONS, ActionItems.FREE_MOLECULAR_SLOT_SHORTCUT); this.guiButtonNextAssembler = new GuiImgButton( guiLeft + 123, guiTop + 25, Settings.ACTIONS, ActionItems.FREE_MOLECULAR_SLOT_SHORTCUT );
this.buttonList.add( guiButtonNextAssembler ); this.buttonList.add( guiButtonNextAssembler );
guiButtonHide = new GuiImgButton( guiLeft + 141, guiTop + 25,Settings.ACTIONS, this.partInterfaceTerminal.onlyInterfacesWithFreeSlots ? guiButtonHide = new GuiImgButton( guiLeft + 141, guiTop + 25, Settings.ACTIONS, this.partInterfaceTerminal.onlyInterfacesWithFreeSlots ? ActionItems.TOGGLE_SHOW_FULL_INTERFACES_OFF : ActionItems.TOGGLE_SHOW_FULL_INTERFACES_ON );
ActionItems.TOGGLE_SHOW_FULL_INTERFACES_OFF :
ActionItems.TOGGLE_SHOW_FULL_INTERFACES_ON);
this.buttonList.add( guiButtonHide ); this.buttonList.add( guiButtonHide );
this.inventorySlots.inventorySlots.removeIf( slot -> slot instanceof SlotDisconnected ); this.inventorySlots.inventorySlots.removeIf( slot -> slot instanceof SlotDisconnected );
int offset = 51; int offset = 52;
for( int x = 0; x < LINES_ON_PAGE && ex + x < this.lines.size(); x++ ) int linesDraw = 0;
for( int x = 0; x < LINES_ON_PAGE && linesDraw < LINES_ON_PAGE && currentScroll + x < this.lines.size(); x++ )
{ {
final Object lineObj = this.lines.get( ex + x ); final Object lineObj = this.lines.get( currentScroll + x );
if( lineObj instanceof ClientDCInternalInv ) if( lineObj instanceof ClientDCInternalInv )
{ {
final ClientDCInternalInv inv = (ClientDCInternalInv) lineObj; final ClientDCInternalInv inv = (ClientDCInternalInv) lineObj;
for( int z = 0; z < inv.getInventory().getSlots(); z++ )
{
this.inventorySlots.inventorySlots.add( new SlotDisconnected( inv, z, z * 18 + 22, 1 + offset ) );
if (this.matchedStacks.contains(inv.getInventory().getStackInSlot(z)))
drawRect( z * 18 + 22, 1 + offset, z * 18 + 22 + 16, 1 + offset + 16, 0x2A00FF00 );
}
GuiButton guiButton = new GuiImgButton(guiLeft + 4, guiTop + offset + 1, Settings.ACTIONS, ActionItems.HIGHLIGHT_INTERFACE); GuiButton guiButton = new GuiImgButton( guiLeft + 4, guiTop + offset, Settings.ACTIONS, ActionItems.HIGHLIGHT_INTERFACE );
guiButtonHashMap.put( guiButton , inv); guiButtonHashMap.put( guiButton, inv );
this.buttonList.add( guiButton ); this.buttonList.add( guiButton );
int extraLines = numUpgradesMap.get( inv );
for( int row = 0; row < 1 + extraLines && linesDraw < LINES_ON_PAGE ; ++row )
{
for( int z = 0; z < 9 ; z++ )
{
this.inventorySlots.inventorySlots.add( new SlotDisconnected( inv, z + ( row * 9 ), ( z * 18 + 22 ), offset ) );
if( this.matchedStacks.contains( inv.getInventory().getStackInSlot( z + ( row * 9 ) ) ) )
{
drawRect( z * 18 + 22, offset, z * 18 + 22 + 16, offset + 16, 0x2A00FF00 );
}
}
linesDraw++;
offset += 18;
}
} }
else if( lineObj instanceof String ) else if( lineObj instanceof String )
{ {
@@ -176,17 +189,17 @@ public class GuiInterfaceTerminal extends AEBaseGui
name = name + " (" + rows + ')'; name = name + " (" + rows + ')';
} }
while( name.length() > 2 && this.fontRenderer.getStringWidth( name ) > 155 ) while ( name.length() > 2 && this.fontRenderer.getStringWidth( name ) > 155 )
{ {
name = name.substring( 0, name.length() - 1 ); name = name.substring( 0, name.length() - 1 );
} }
this.fontRenderer.drawString( name, this.offsetX + 2, 5 + offset, 4210752 );
this.fontRenderer.drawString( name, this.offsetX + 2, 6 + offset, 4210752 ); linesDraw++;
offset += 18;
} }
offset += 18;
} }
if( searchFieldInputs.isMouseIn( mouseX , mouseY ) ) drawTooltip( Mouse.getEventX() * this.width / this.mc.displayWidth - offsetX, mouseY - guiTop, "Inputs OR names" ); if( searchFieldInputs.isMouseIn( mouseX, mouseY ) ) drawTooltip( Mouse.getEventX() * this.width / this.mc.displayWidth - offsetX, mouseY - guiTop, "Inputs OR names" );
else if( searchFieldOutputs.isMouseIn( mouseX, mouseY ) ) drawTooltip( Mouse.getEventX() * this.width / this.mc.displayWidth - offsetX, mouseY - guiTop, "Outputs OR names" ); else if( searchFieldOutputs.isMouseIn( mouseX, mouseY ) ) drawTooltip( Mouse.getEventX() * this.width / this.mc.displayWidth - offsetX, mouseY - guiTop, "Outputs OR names" );
} }
@@ -224,7 +237,11 @@ public class GuiInterfaceTerminal extends AEBaseGui
int interfaceDim = dimHashMap.get( guiButtonHashMap.get( this.selectedButton ) ); int interfaceDim = dimHashMap.get( guiButtonHashMap.get( this.selectedButton ) );
if( playerDim != interfaceDim ) if( playerDim != interfaceDim )
{ {
mc.player.sendStatusMessage( new TextComponentString( "Interface located at dimension: " + interfaceDim + " [" + DimensionManager.getWorld( interfaceDim ).provider.getDimensionType().getName() + "] and cant be highlighted" ), false ); try {
mc.player.sendStatusMessage( new TextComponentString( "Interface located at dimension: " + interfaceDim + " [" + DimensionManager.getWorld( interfaceDim ).provider.getDimensionType().getName() + "] and cant be highlighted" ), false );
} catch(Exception e){
mc.player.sendStatusMessage( new TextComponentString( "Interface is located in another dimension and cannot be highlighted" ), false );
}
} }
else else
{ {
@@ -264,19 +281,28 @@ public class GuiInterfaceTerminal extends AEBaseGui
int offset = 51; int offset = 51;
final int ex = this.getScrollBar().getCurrentScroll(); final int ex = this.getScrollBar().getCurrentScroll();
int linesDraw = 0;
for( int x = 0; x < LINES_ON_PAGE && ex + x < this.lines.size(); x++ ) for( int x = 0; x < LINES_ON_PAGE && linesDraw < LINES_ON_PAGE && ex + x < this.lines.size(); x++ )
{ {
final Object lineObj = this.lines.get( ex + x ); final Object lineObj = this.lines.get( ex + x );
if( lineObj instanceof ClientDCInternalInv ) if( lineObj instanceof ClientDCInternalInv )
{ {
final ClientDCInternalInv inv = (ClientDCInternalInv) lineObj;
GlStateManager.color( 1, 1, 1, 1 ); GlStateManager.color( 1, 1, 1, 1 );
final int width = inv.getInventory().getSlots() * 18; final int width = 9 * 18;
this.drawTexturedModalRect( offsetX + 20, offsetY + offset, 20, 173, width, 18 );
int extraLines = numUpgradesMap.get( lineObj );
for( int row = 0; row < 1 + extraLines && linesDraw < LINES_ON_PAGE; ++row )
{
this.drawTexturedModalRect( offsetX + 20, offsetY + offset , 20, 173, width, 18 );
offset += 18;
linesDraw++;
}
}
else {
offset += 18;
linesDraw++;
} }
offset += 18;
} }
if( this.searchFieldInputs != null ) if( this.searchFieldInputs != null )
@@ -337,6 +363,7 @@ public class GuiInterfaceTerminal extends AEBaseGui
final ClientDCInternalInv current = this.getById( id, invData.getLong( "sortBy" ), invData.getString( "un" ) ); final ClientDCInternalInv current = this.getById( id, invData.getLong( "sortBy" ), invData.getString( "un" ) );
blockPosHashMap.put( current, NBTUtil.getPosFromTag( invData.getCompoundTag( "pos" )) ); blockPosHashMap.put( current, NBTUtil.getPosFromTag( invData.getCompoundTag( "pos" )) );
dimHashMap.put( current, invData.getInteger( "dim" )); dimHashMap.put( current, invData.getInteger( "dim" ));
numUpgradesMap.put( current, invData.getInteger("numUpgrades"));
for( int x = 0; x < current.getInventory().getSlots(); x++ ) for( int x = 0; x < current.getInventory().getSlots(); x++ )
{ {
@@ -395,8 +422,12 @@ public class GuiInterfaceTerminal extends AEBaseGui
// Search if the current inventory holds a pattern containing the search term. // Search if the current inventory holds a pattern containing the search term.
if( !found ) if( !found )
{ {
int slot = 0;
for( final ItemStack itemStack : entry.getInventory() ) for( final ItemStack itemStack : entry.getInventory() )
{ {
if (slot > 8 + numUpgradesMap.get(entry) * 9) {
break;
}
if( !searchFieldInputs.isEmpty() && !searchFieldOutputs.isEmpty() ) { if( !searchFieldInputs.isEmpty() && !searchFieldOutputs.isEmpty() ) {
if (this.itemStackMatchesSearchTerm(itemStack, searchFieldInputs, 0) || this.itemStackMatchesSearchTerm(itemStack, searchFieldOutputs, 1)) { if (this.itemStackMatchesSearchTerm(itemStack, searchFieldInputs, 0) || this.itemStackMatchesSearchTerm(itemStack, searchFieldOutputs, 1)) {
found = true; found = true;
@@ -418,6 +449,7 @@ public class GuiInterfaceTerminal extends AEBaseGui
// If only Interfaces with empty slots should be shown, check that here // If only Interfaces with empty slots should be shown, check that here
if(itemStack.isEmpty()) if(itemStack.isEmpty())
interfaceHasFreeSlots = true; interfaceHasFreeSlots = true;
slot++;
} }
} }
// if found, filter skipped or machine name matching the search term, add it // if found, filter skipped or machine name matching the search term, add it
@@ -458,7 +490,7 @@ public class GuiInterfaceTerminal extends AEBaseGui
this.lines.addAll( clientInventories ); this.lines.addAll( clientInventories );
} }
this.getScrollBar().setRange( 0, this.lines.size() - LINES_ON_PAGE, 2 ); this.getScrollBar().setRange( 0, this.lines.size() - 1, 1 );
} }
private boolean itemStackMatchesSearchTerm( final ItemStack itemStack, final String searchTerm,int pass ) private boolean itemStackMatchesSearchTerm( final ItemStack itemStack, final String searchTerm,int pass )
@@ -548,7 +580,7 @@ public class GuiInterfaceTerminal extends AEBaseGui
if( o == null ) if( o == null )
{ {
this.byId.put( id, o = new ClientDCInternalInv( 9, id, sortBy, string ) ); this.byId.put( id, o = new ClientDCInternalInv( DualityInterface.NUMBER_OF_PATTERN_SLOTS, id, sortBy, string ) );
this.refreshList = true; this.refreshList = true;
} }
@@ -270,12 +270,15 @@ public class GuiUpgradeable extends AEBaseGui implements IJEIGhostIngredients
@Override @Override
public Rectangle getArea() public Rectangle getArea()
{ {
if( slot instanceof SlotFake ) if( slot instanceof SlotFake && ( (SlotFake) slot ).isSlotEnabled() )
{
return new Rectangle( getGuiLeft() + ( (SlotFake) slot ).xPos, getGuiTop() + ( (SlotFake) slot ).yPos, 16, 16 ); return new Rectangle( getGuiLeft() + ( (SlotFake) slot ).xPos, getGuiTop() + ( (SlotFake) slot ).yPos, 16, 16 );
else }
else if( slot instanceof GuiFluidSlot && ( (GuiFluidSlot) slot ).isSlotEnabled() )
{ {
return new Rectangle( getGuiLeft() + ( (GuiFluidSlot) slot ).xPos(), getGuiTop() + ( (GuiFluidSlot) slot ).yPos(), 16, 16 ); return new Rectangle( getGuiLeft() + ( (GuiFluidSlot) slot ).xPos(), getGuiTop() + ( (GuiFluidSlot) slot ).yPos(), 16, 16 );
} }
return new Rectangle();
} }
@Override @Override
@@ -284,7 +287,7 @@ public class GuiUpgradeable extends AEBaseGui implements IJEIGhostIngredients
PacketInventoryAction p = null; PacketInventoryAction p = null;
try try
{ {
if( slot instanceof SlotFake ) if( slot instanceof SlotFake && ( (SlotFake) slot ).isSlotEnabled() )
{ {
if( finalItemStack.isEmpty() && finalFluidStack != null ) if( finalItemStack.isEmpty() && finalFluidStack != null )
{ {
@@ -10,9 +10,9 @@ import net.minecraft.item.ItemStack;
public abstract class GuiCustomSlot extends Gui implements ITooltip public abstract class GuiCustomSlot extends Gui implements ITooltip
{ {
private final int x; protected final int x;
private final int y; protected final int y;
private final int id; protected final int id;
public GuiCustomSlot( final int id, final int x, final int y ) public GuiCustomSlot( final int id, final int x, final int y )
{ {
@@ -22,9 +22,10 @@ package appeng.client.render;
import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IAEFluidStack;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.*;
import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.RenderItem; import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing;
@@ -32,6 +33,7 @@ import appeng.api.storage.data.IAEItemStack;
import appeng.util.IWideReadableNumberConverter; import appeng.util.IWideReadableNumberConverter;
import appeng.util.ReadableNumberConverter; import appeng.util.ReadableNumberConverter;
import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidStack;
import org.lwjgl.opengl.GL11;
/** /**
@@ -121,6 +123,49 @@ public class TesrRenderHelper
} }
} }
public static void renderFluid2d( FluidStack fluidStack, float scale )
{
if( fluidStack != null )
{
GlStateManager.pushMatrix();
int color = fluidStack.getFluid().getColor( fluidStack );
float r = ( color >> 16 & 255 ) / 255.0f;
float g = ( color >> 8 & 255 ) / 255.0f;
float b = ( color & 255 ) / 255.0f;
TextureAtlasSprite sprite = Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite( fluidStack.getFluid().getStill( fluidStack ).toString() );
GlStateManager.enableBlend();
GlStateManager.blendFunc( GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA );
GlStateManager.disableAlpha();
GlStateManager.disableLighting();
Minecraft.getMinecraft().getTextureManager().bindTexture( TextureMap.LOCATION_BLOCKS_TEXTURE );
Tessellator tess = Tessellator.getInstance();
BufferBuilder buf = tess.getBuffer();
float width = 0.4f;
float height = 0.4f;
float alpha = 1.0f;
float z = 0.0001f;
float x = -0.20f;
float y = -0.25f;
buf.begin( GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR );
double uMin = sprite.getInterpolatedU( 16D - width * 16D ), uMax = sprite.getInterpolatedU( width * 16D );
double vMin = sprite.getMinV(), vMax = sprite.getInterpolatedV( height * 16D );
buf.pos( x, y, z ).tex( uMin, vMin ).color( r, g, b, alpha ).endVertex();
buf.pos( x, y + height, z ).tex( uMin, vMax ).color( r, g, b, alpha ).endVertex();
buf.pos( x + width, y + height, z ).tex( uMax, vMax ).color( r, g, b, alpha ).endVertex();
buf.pos( x + width, y, z ).tex( uMax, vMin ).color( r, g, b, alpha ).endVertex();
tess.draw();
GlStateManager.enableLighting();
GlStateManager.enableAlpha();
GlStateManager.disableBlend();
GlStateManager.color( 1F, 1F, 1F, 1F );
GlStateManager.popMatrix();
}
}
/** /**
* Render an item in 2D and the given text below it. * Render an item in 2D and the given text below it.
* *
@@ -147,9 +192,9 @@ public class TesrRenderHelper
public static void renderFluid2dWithAmount( IAEFluidStack fluidStack, float scale, float spacing ) public static void renderFluid2dWithAmount( IAEFluidStack fluidStack, float scale, float spacing )
{ {
final ItemStack renderStack = fluidStack.asItemStackRepresentation(); final FluidStack renderStack = fluidStack.getFluidStack();
TesrRenderHelper.renderItem2d( renderStack, scale ); TesrRenderHelper.renderFluid2d( renderStack, scale );
final long stackSize = fluidStack.getStackSize() / 1000; final long stackSize = fluidStack.getStackSize() / 1000;
final String renderedStackSize = NUMBER_CONVERTER.toWideReadableForm( stackSize ) + "B"; final String renderedStackSize = NUMBER_CONVERTER.toWideReadableForm( stackSize ) + "B";
@@ -159,56 +159,58 @@ public class ContainerCraftingCPU extends AEBaseContainer implements IMEMonitorH
@Override @Override
public void detectAndSendChanges() public void detectAndSendChanges()
{ {
if( Platform.isServer() && this.getMonitor() != null && !this.list.isEmpty() ) if( Platform.isServer() && this.getMonitor() != null )
{ {
try if( this.getEstimatedTime() >= 0 )
{ {
if( this.getEstimatedTime() >= 0 ) final long elapsedTime = this.getMonitor().getElapsedTime();
final double remainingItems = this.getMonitor().getRemainingItemCount();
final double startItems = this.getMonitor().getStartItemCount();
final long eta = (long) ( elapsedTime / Math.max( 1d, ( startItems - remainingItems ) ) * remainingItems );
this.setEstimatedTime( eta );
}
if( !this.list.isEmpty() )
{
try
{ {
final long elapsedTime = this.getMonitor().getElapsedTime(); final PacketMEInventoryUpdate a = new PacketMEInventoryUpdate( (byte) 0 );
final double remainingItems = this.getMonitor().getRemainingItemCount(); final PacketMEInventoryUpdate b = new PacketMEInventoryUpdate( (byte) 1 );
final double startItems = this.getMonitor().getStartItemCount(); final PacketMEInventoryUpdate c = new PacketMEInventoryUpdate( (byte) 2 );
final long eta = (long) ( elapsedTime / Math.max( 1d, ( startItems - remainingItems ) ) * remainingItems );
this.setEstimatedTime( eta );
}
final PacketMEInventoryUpdate a = new PacketMEInventoryUpdate( (byte) 0 ); for( final IAEItemStack out : this.list )
final PacketMEInventoryUpdate b = new PacketMEInventoryUpdate( (byte) 1 );
final PacketMEInventoryUpdate c = new PacketMEInventoryUpdate( (byte) 2 );
for( final IAEItemStack out : this.list )
{
a.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.STORAGE ) );
b.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.ACTIVE ) );
c.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.PENDING ) );
}
this.list.resetStatus();
for( final Object g : this.listeners )
{
if( g instanceof EntityPlayer )
{ {
if( !a.isEmpty() ) a.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.STORAGE ) );
{ b.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.ACTIVE ) );
NetworkHandler.instance().sendTo( a, (EntityPlayerMP) g ); c.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.PENDING ) );
} }
if( !b.isEmpty() ) this.list.resetStatus();
{
NetworkHandler.instance().sendTo( b, (EntityPlayerMP) g );
}
if( !c.isEmpty() ) for( final Object g : this.listeners )
{
if( g instanceof EntityPlayer )
{ {
NetworkHandler.instance().sendTo( c, (EntityPlayerMP) g ); if( !a.isEmpty() )
{
NetworkHandler.instance().sendTo( a, (EntityPlayerMP) g );
}
if( !b.isEmpty() )
{
NetworkHandler.instance().sendTo( b, (EntityPlayerMP) g );
}
if( !c.isEmpty() )
{
NetworkHandler.instance().sendTo( c, (EntityPlayerMP) g );
}
} }
} }
} }
} catch( final IOException e )
catch( final IOException e ) {
{ // :P
// :P }
} }
} }
super.detectAndSendChanges(); super.detectAndSendChanges();
@@ -19,6 +19,9 @@
package appeng.container.implementations; package appeng.container.implementations;
import appeng.api.config.Upgrades;
import appeng.container.slot.*;
import appeng.util.Platform;
import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.entity.player.InventoryPlayer;
import appeng.api.config.SecurityPermissions; import appeng.api.config.SecurityPermissions;
@@ -26,14 +29,11 @@ import appeng.api.config.Settings;
import appeng.api.config.YesNo; import appeng.api.config.YesNo;
import appeng.api.util.IConfigManager; import appeng.api.util.IConfigManager;
import appeng.container.guisync.GuiSync; import appeng.container.guisync.GuiSync;
import appeng.container.slot.SlotFake;
import appeng.container.slot.SlotNormal;
import appeng.container.slot.SlotRestrictedInput;
import appeng.helpers.DualityInterface; import appeng.helpers.DualityInterface;
import appeng.helpers.IInterfaceHost; import appeng.helpers.IInterfaceHost;
public class ContainerInterface extends ContainerUpgradeable public class ContainerInterface extends ContainerUpgradeable implements IOptionalSlotHost
{ {
private final DualityInterface myDuality; private final DualityInterface myDuality;
@@ -44,16 +44,22 @@ public class ContainerInterface extends ContainerUpgradeable
@GuiSync( 4 ) @GuiSync( 4 )
public YesNo iTermMode = YesNo.YES; public YesNo iTermMode = YesNo.YES;
@GuiSync( 7 )
public int patternExpansions = 0;
public ContainerInterface( final InventoryPlayer ip, final IInterfaceHost te ) public ContainerInterface( final InventoryPlayer ip, final IInterfaceHost te )
{ {
super( ip, te.getInterfaceDuality().getHost() ); super( ip, te.getInterfaceDuality().getHost() );
this.myDuality = te.getInterfaceDuality(); this.myDuality = te.getInterfaceDuality();
for( int x = 0; x < DualityInterface.NUMBER_OF_PATTERN_SLOTS; x++ ) for (int row = 0 ; row < 4 ; ++row)
{ {
this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ENCODED_PATTERN, this.myDuality for( int x = 0; x < 9; x++ )
.getPatterns(), x, 8 + 18 * x, 90 + 7, this.getInventoryPlayer() ).setStackLimit( 1 ) ); {
this.addSlotToContainer( new OptionalSlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ENCODED_PATTERN, this.myDuality
.getPatterns(), this, x + row * 9, 8 + 18 * x, 97 + ( 18 * row ), row, this.getInventoryPlayer() ).setStackLimit( 1 ) );
}
} }
for( int x = 0; x < DualityInterface.NUMBER_OF_CONFIG_SLOTS; x++ ) for( int x = 0; x < DualityInterface.NUMBER_OF_CONFIG_SLOTS; x++ )
@@ -70,7 +76,7 @@ public class ContainerInterface extends ContainerUpgradeable
@Override @Override
protected int getHeight() protected int getHeight()
{ {
return 211; return 256;
} }
@Override @Override
@@ -82,16 +88,35 @@ public class ContainerInterface extends ContainerUpgradeable
@Override @Override
public int availableUpgrades() public int availableUpgrades()
{ {
return 1; return 4;
}
@Override
public boolean isSlotEnabled( final int idx )
{
return myDuality.getInstalledUpgrades(Upgrades.PATTERN_EXPANSION) >= idx;
} }
@Override @Override
public void detectAndSendChanges() public void detectAndSendChanges()
{ {
this.verifyPermissions( SecurityPermissions.BUILD, false ); this.verifyPermissions( SecurityPermissions.BUILD, false );
if (patternExpansions != getPatternUpgrades())
{
patternExpansions = getPatternUpgrades();
this.myDuality.dropExcessPatterns();
}
super.detectAndSendChanges(); super.detectAndSendChanges();
} }
@Override
public void onUpdate( final String field, final Object oldValue, final Object newValue ) {
super.onUpdate(field, oldValue, newValue);
if ( Platform.isClient() && field.equals("patternExpansions"))
this.myDuality.dropExcessPatterns();
}
@Override @Override
protected void loadSettingsFromHost( final IConfigManager cm ) protected void loadSettingsFromHost( final IConfigManager cm )
{ {
@@ -118,4 +143,9 @@ public class ContainerInterface extends ContainerUpgradeable
{ {
this.iTermMode = iTermMode; this.iTermMode = iTermMode;
} }
public int getPatternUpgrades()
{
return this.myDuality.getInstalledUpgrades( Upgrades.PATTERN_EXPANSION );
}
} }
@@ -24,6 +24,7 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import appeng.api.config.Upgrades;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
@@ -405,6 +406,7 @@ public final class ContainerInterfaceTerminal extends AEBaseContainer
tag.setString( "un", inv.unlocalizedName ); tag.setString( "un", inv.unlocalizedName );
tag.setTag( "pos", NBTUtil.createPosTag( inv.pos ) ); tag.setTag( "pos", NBTUtil.createPosTag( inv.pos ) );
tag.setInteger( "dim", inv.dim ); tag.setInteger( "dim", inv.dim );
tag.setInteger( "numUpgrades", inv.numUpgrades );
} }
for( int x = 0; x < length; x++ ) for( int x = 0; x < length; x++ )
@@ -437,6 +439,7 @@ public final class ContainerInterfaceTerminal extends AEBaseContainer
private final IItemHandler server; private final IItemHandler server;
private final BlockPos pos; private final BlockPos pos;
private final int dim; private final int dim;
private final int numUpgrades;
public InvTracker( final DualityInterface dual, final IItemHandler patterns, final String unlocalizedName ) public InvTracker( final DualityInterface dual, final IItemHandler patterns, final String unlocalizedName )
{ {
@@ -446,6 +449,7 @@ public final class ContainerInterfaceTerminal extends AEBaseContainer
this.sortBy = dual.getSortValue(); this.sortBy = dual.getSortValue();
this.pos = dual.getLocation().getPos(); this.pos = dual.getLocation().getPos();
this.dim = dual.getLocation().getWorld().provider.getDimension(); this.dim = dual.getLocation().getWorld().provider.getDimension();
this.numUpgrades = dual.getInstalledUpgrades( Upgrades.PATTERN_EXPANSION);
} }
} }
@@ -134,14 +134,16 @@ public class ContainerPatternTerm extends ContainerMEMonitorable implements IAEA
{ {
return ItemStack.EMPTY; return ItemStack.EMPTY;
} }
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();
if( AEApi.instance().definitions().materials().blankPattern().isSameAs( itemStack ) )
{ {
IItemHandler patternInv = this.getPatternTerminal().getInventoryByName( "pattern" ); final AppEngSlot clickSlot = ( AppEngSlot ) this.inventorySlots.get( idx ); // require AE SLots!
ItemStack remainder = patternInv.insertItem( 0, itemStack, false ); ItemStack itemStack = clickSlot.getStack();
clickSlot.putStack( remainder ); if( AEApi.instance().definitions().materials().blankPattern().isSameAs( itemStack ) )
{
IItemHandler patternInv = this.getPatternTerminal().getInventoryByName( "pattern" );
ItemStack remainder = patternInv.insertItem( 0, itemStack, false );
clickSlot.putStack( remainder );
}
} }
return super.transferStackInSlot( p, idx ); return super.transferStackInSlot( p, idx );
} }
@@ -157,7 +157,7 @@ public class AppEngSlot extends Slot
{ {
if( this.isSlotEnabled() ) if( this.isSlotEnabled() )
{ {
return !this.itemHandler.extractItem( this.index, 1, true ).isEmpty(); return !this.itemHandler.extractItem( this.index, Integer.MAX_VALUE, true ).isEmpty();
} }
return false; return false;
} }
@@ -363,6 +363,8 @@ final class Registration
// Interface // Interface
Upgrades.CRAFTING.registerItem( parts.iface(), 1 ); Upgrades.CRAFTING.registerItem( parts.iface(), 1 );
Upgrades.CRAFTING.registerItem( blocks.iface(), 1 ); Upgrades.CRAFTING.registerItem( blocks.iface(), 1 );
Upgrades.PATTERN_EXPANSION.registerItem( parts.iface(), 3 );
Upgrades.PATTERN_EXPANSION.registerItem( blocks.iface(), 3 );
// IO Port! // IO Port!
Upgrades.SPEED.registerItem( blocks.iOPort(), 3 ); Upgrades.SPEED.registerItem( blocks.iOPort(), 3 );
@@ -175,7 +175,7 @@ public class ApiStorage implements IStorageHelper
@Override @Override
public int transferFactor() public int transferFactor()
{ {
return 125; return 1000;
} }
@Override @Override
@@ -86,6 +86,7 @@ public final class ApiMaterials implements IMaterials
private final IItemDefinition cardRedstone; private final IItemDefinition cardRedstone;
private final IItemDefinition cardSpeed; private final IItemDefinition cardSpeed;
private final IItemDefinition cardCapacity; private final IItemDefinition cardCapacity;
private final IItemDefinition cardPatternExpansion;
private final IItemDefinition cardFuzzy; private final IItemDefinition cardFuzzy;
private final IItemDefinition cardInverter; private final IItemDefinition cardInverter;
private final IItemDefinition cardCrafting; private final IItemDefinition cardCrafting;
@@ -204,6 +205,7 @@ public final class ApiMaterials implements IMaterials
this.cardRedstone = new DamagedItemDefinition( "material.card.redstone", materials.createMaterial( MaterialType.CARD_REDSTONE ) ); this.cardRedstone = new DamagedItemDefinition( "material.card.redstone", materials.createMaterial( MaterialType.CARD_REDSTONE ) );
this.cardSpeed = new DamagedItemDefinition( "material.card.acceleration", materials.createMaterial( MaterialType.CARD_SPEED ) ); this.cardSpeed = new DamagedItemDefinition( "material.card.acceleration", materials.createMaterial( MaterialType.CARD_SPEED ) );
this.cardCapacity = new DamagedItemDefinition( "material.card.capacity", materials.createMaterial( MaterialType.CARD_CAPACITY ) ); this.cardCapacity = new DamagedItemDefinition( "material.card.capacity", materials.createMaterial( MaterialType.CARD_CAPACITY ) );
this.cardPatternExpansion = new DamagedItemDefinition( "material.card.pattern.expansion", materials.createMaterial(MaterialType.CARD_PATTERN_EXPANSION) );
this.cardFuzzy = new DamagedItemDefinition( "material.card.fuzzy", materials.createMaterial( MaterialType.CARD_FUZZY ) ); this.cardFuzzy = new DamagedItemDefinition( "material.card.fuzzy", materials.createMaterial( MaterialType.CARD_FUZZY ) );
this.cardInverter = new DamagedItemDefinition( "material.card.inverter", materials.createMaterial( MaterialType.CARD_INVERTER ) ); this.cardInverter = new DamagedItemDefinition( "material.card.inverter", materials.createMaterial( MaterialType.CARD_INVERTER ) );
this.cardCrafting = new DamagedItemDefinition( "material.card.crafting", materials.createMaterial( MaterialType.CARD_CRAFTING ) ); this.cardCrafting = new DamagedItemDefinition( "material.card.crafting", materials.createMaterial( MaterialType.CARD_CRAFTING ) );
@@ -424,6 +426,9 @@ public final class ApiMaterials implements IMaterials
return this.cardCapacity; return this.cardCapacity;
} }
@Override
public IItemDefinition cardPatternExpansion(){ return this.cardPatternExpansion;}
@Override @Override
public IItemDefinition cardFuzzy() public IItemDefinition cardFuzzy()
{ {
@@ -31,8 +31,10 @@ public enum WailaText
DeviceMissingChannel, DeviceMissingChannel,
P2PUnlinked, P2PUnlinked,
P2PInputOneOutput, P2P_INPUT_ONE_OUTPUT,
P2PInputManyOutputs, P2P_INPUT_MANY_OUTPUTS,
P2P_OUTPUT_ONE_INPUT,
P2P_OUTPUT_MANY_INPUTS,
P2POutput, P2POutput,
Locked, Locked,
@@ -29,6 +29,7 @@ import java.util.Iterator;
import appeng.api.config.FuzzyMode; import appeng.api.config.FuzzyMode;
import appeng.api.storage.data.IItemList; import appeng.api.storage.data.IItemList;
import appeng.container.implementations.ContainerPatternTerm; import appeng.container.implementations.ContainerPatternTerm;
import gregtech.common.items.MetaTool;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
@@ -211,23 +212,21 @@ public class PacketJEIRecipe extends AppEngPacket
out = Platform.poweredExtraction( energy, storage, request, cct.getActionSource() ); out = Platform.poweredExtraction( energy, storage, request, cct.getActionSource() );
if( out == null ) if( out == null )
{ {
Collection<IAEItemStack> outList = inv.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ).getStorageList().findFuzzy( request, FuzzyMode.IGNORE_ALL ); if( request.getItem().isDamageable() || ( Platform.isModLoaded( "gregtech" ) && request.getItem() instanceof MetaTool ) )
IAEItemStack mostDamaged = null;
for( IAEItemStack is : outList )
{ {
if( !is.isCraftable() ) Collection<IAEItemStack> outList = inv.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ).getStorageList().findFuzzy( request, FuzzyMode.IGNORE_ALL );
for( IAEItemStack is : outList )
{ {
if( mostDamaged == null || mostDamaged.getItemDamage() < is.getItemDamage() ) if( is.getDefinition().getMetadata() == request.getDefinition().getMetadata() )
{ {
mostDamaged = is; out = Platform.poweredExtraction( energy, storage, is.copy().setStackSize( 1 ), cct.getActionSource() );
}
if( out != null )
{
break;
} }
} }
} }
if( mostDamaged != null )
{
mostDamaged.setStackSize( 1 );
out = Platform.poweredExtraction( energy, storage, mostDamaged, cct.getActionSource() );
}
} }
} }
else else
@@ -246,7 +245,10 @@ public class PacketJEIRecipe extends AppEngPacket
if( out != null ) if( out != null )
{ {
out.setStackSize( recipe[x][y].getCount() ); if (!cct.useRealItems())
{
out.setStackSize( recipe[x][y].getCount() );
}
currentItem = out.createItemStack(); currentItem = out.createItemStack();
} }
} }
@@ -19,6 +19,7 @@
package appeng.core.sync.packets; package appeng.core.sync.packets;
import appeng.fluids.container.ContainerFluidInterface;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
@@ -90,5 +91,9 @@ public class PacketTargetFluidStack extends AppEngPacket
{ {
( (ContainerFluidTerminal) player.openContainer ).setTargetStack( this.stack ); ( (ContainerFluidTerminal) player.openContainer ).setTargetStack( this.stack );
} }
else if( player.openContainer instanceof ContainerFluidInterface )
{
( (ContainerFluidInterface) player.openContainer ).setTargetStack( this.stack );
}
} }
} }
+56 -3
View File
@@ -59,6 +59,7 @@ public class CraftingJob implements Runnable, ICraftingJob
private final IItemList<IAEItemStack> missing = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); private final IItemList<IAEItemStack> missing = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList();
private final HashMap<String, TwoIntegers> opsAndMultiplier = new HashMap<>(); private final HashMap<String, TwoIntegers> opsAndMultiplier = new HashMap<>();
private final Object monitor = new Object(); private final Object monitor = new Object();
private final Stopwatch watch = Stopwatch.createUnstarted();
private CraftingTreeNode tree; private CraftingTreeNode tree;
private final IAEItemStack output; private final IAEItemStack output;
private boolean simulate = false; private boolean simulate = false;
@@ -66,7 +67,10 @@ public class CraftingJob implements Runnable, ICraftingJob
private long bytes = 0; private long bytes = 0;
private final IActionSource actionSrc; private final IActionSource actionSrc;
private final ICraftingCallback callback; private final ICraftingCallback callback;
private boolean running = false;
private boolean done = false; private boolean done = false;
private int time;
private int incTime;
private World wrapWorld( final World w ) private World wrapWorld( final World w )
{ {
@@ -133,6 +137,7 @@ public class CraftingJob implements Runnable, ICraftingJob
try try
{ {
TickHandler.INSTANCE.registerCraftingSimulation( this.world, this ); TickHandler.INSTANCE.registerCraftingSimulation( this.world, this );
this.handlePausing();
final Stopwatch timer = Stopwatch.createStarted(); final Stopwatch timer = Stopwatch.createStarted();
@@ -214,6 +219,41 @@ public class CraftingJob implements Runnable, ICraftingJob
this.finish(); this.finish();
} }
void handlePausing() throws InterruptedException
{
if( !this.actionSrc.player().isPresent() && this.incTime > 100 )
{
this.incTime = 0;
synchronized ( this.monitor )
{
if( this.watch.elapsed( TimeUnit.MICROSECONDS ) > this.time )
{
this.running = false;
this.watch.stop();
this.monitor.notify();
}
if( !this.running )
{
AELog.craftingDebug( "crafting job will now sleep" );
while ( !this.running )
{
this.monitor.wait();
}
AELog.craftingDebug( "crafting job now active" );
}
}
if( Thread.interrupted() )
{
throw new InterruptedException();
}
}
this.incTime++;
}
private void finish() private void finish()
{ {
if( this.callback != null ) if( this.callback != null )
@@ -225,6 +265,7 @@ public class CraftingJob implements Runnable, ICraftingJob
synchronized( this.monitor ) synchronized( this.monitor )
{ {
this.running = false;
this.done = true; this.done = true;
this.monitor.notify(); this.monitor.notify();
} }
@@ -270,13 +311,25 @@ public class CraftingJob implements Runnable, ICraftingJob
/** /**
* @return true if this needs more simulation * @return true if this needs more simulation
*/ */
public boolean simulateFor() public boolean simulateFor(final int milli)
{ {
synchronized( this.monitor ) { this.time = milli;
if ( this.done ) {
synchronized ( this.monitor )
{
if( this.done )
{
return false; return false;
} }
if( !this.actionSrc.player().isPresent() )
{
this.watch.reset();
this.watch.start();
this.monitor.notify();
}
this.running = true;
} }
return true; return true;
} }
@@ -25,6 +25,7 @@ import java.util.List;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.world.World; import net.minecraft.world.World;
import appeng.api.AEApi; import appeng.api.AEApi;
@@ -119,18 +120,48 @@ public class CraftingTreeNode
IAEItemStack request( final MECraftingInventory inv, long l, final IActionSource src ) throws CraftBranchFailure, InterruptedException IAEItemStack request( final MECraftingInventory inv, long l, final IActionSource src ) throws CraftBranchFailure, InterruptedException
{ {
this.job.handlePausing();
final List<IAEItemStack> thingsUsed = new ArrayList<>(); final List<IAEItemStack> thingsUsed = new ArrayList<>();
this.what.setStackSize( l ); this.what.setStackSize( l );
if( this.getSlot() >= 0 && this.parent != null && this.parent.details.isCraftable() ) IAEItemStack available = inv.extractItems( this.what, Actionable.MODULATE, src );
if( available != null )
{
if( !this.exhausted )
{
final IAEItemStack is = this.job.checkUse( available );
if( is != null )
{
thingsUsed.add( is.copy() );
this.used.add( is );
}
}
this.bytes += available.getStackSize();
l -= available.getStackSize();
if( l == 0 )
{
return available;
}
}
else if( this.getSlot() >= 0 && this.parent != null && this.parent.details.isCraftable() )
{ {
final Collection<IAEItemStack> itemList; final Collection<IAEItemStack> itemList;
final IItemList<IAEItemStack> inventoryList = inv.getItemList(); final IItemList<IAEItemStack> inventoryList = inv.getItemList();
if( this.parent.details.canSubstitute() ) 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 else
{ {
@@ -151,7 +182,7 @@ public class CraftingTreeNode
fuzz = fuzz.copy(); fuzz = fuzz.copy();
fuzz.setStackSize( l ); fuzz.setStackSize( l );
final IAEItemStack available = inv.extractItems( fuzz, Actionable.MODULATE, src ); available = inv.extractItems( fuzz, Actionable.MODULATE, src );
if( available != null ) if( available != null )
{ {
@@ -177,32 +208,6 @@ public class CraftingTreeNode
} }
} }
} }
else
{
final IAEItemStack available = inv.extractItems( this.what, Actionable.MODULATE, src );
if( available != null )
{
if( !this.exhausted )
{
final IAEItemStack is = this.job.checkUse( available );
if( is != null )
{
thingsUsed.add( is.copy() );
this.used.add( is );
}
}
this.bytes += available.getStackSize();
l -= available.getStackSize();
if( l == 0 )
{
return available;
}
}
}
if( this.canEmit ) if( this.canEmit )
{ {
@@ -221,7 +226,7 @@ public class CraftingTreeNode
{ {
final CraftingTreeProcess pro = this.nodes.get( 0 ); final CraftingTreeProcess pro = this.nodes.get( 0 );
while( pro.possible && l > 0 ) while ( pro.possible && l > 0 )
{ {
final IAEItemStack madeWhat = pro.getAmountCrafted( this.what ); final IAEItemStack madeWhat = pro.getAmountCrafted( this.what );
@@ -229,7 +234,7 @@ public class CraftingTreeNode
madeWhat.setStackSize( l ); madeWhat.setStackSize( l );
final IAEItemStack available = inv.extractItems( madeWhat, Actionable.MODULATE, src ); available = inv.extractItems( madeWhat, Actionable.MODULATE, src );
if( available != null ) if( available != null )
{ {
@@ -253,13 +258,13 @@ public class CraftingTreeNode
{ {
try try
{ {
while( pro.possible && l > 0 ) while ( pro.possible && l > 0 )
{ {
final MECraftingInventory subInv = new MECraftingInventory( inv, true, true, true ); final MECraftingInventory subInv = new MECraftingInventory( inv, true, true, true );
pro.request( subInv, 1, src ); pro.request( subInv, 1, src );
this.what.setStackSize( l ); this.what.setStackSize( l );
final IAEItemStack available = subInv.extractItems( this.what, Actionable.MODULATE, src ); available = subInv.extractItems( this.what, Actionable.MODULATE, src );
if( available != null ) if( available != null )
{ {
@@ -316,7 +321,7 @@ public class CraftingTreeNode
} }
// missing = 0; // missing = 0;
job.addBytes( 8 + this.bytes ); job.addBytes( this.bytes );
for( final CraftingTreeProcess pro : this.nodes ) for( final CraftingTreeProcess pro : this.nodes )
{ {
@@ -353,6 +358,10 @@ public class CraftingTreeNode
if( ex == null || ex.getStackSize() != i.getStackSize() ) if( ex == null || ex.getStackSize() != i.getStackSize() )
{ {
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 );
}
throw new CraftBranchFailure( i, i.getStackSize() ); throw new CraftBranchFailure( i, i.getStackSize() );
} }
@@ -185,7 +185,7 @@ public class CraftingTreeProcess
void request( final MECraftingInventory inv, final long i, final IActionSource src ) throws CraftBranchFailure, InterruptedException void request( final MECraftingInventory inv, final long i, final IActionSource src ) throws CraftBranchFailure, InterruptedException
{ {
this.job.handlePausing();
if( this.fullSimulation ) if( this.fullSimulation )
{ {
final InventoryCrafting ic = new InventoryCrafting( new ContainerNull(), 3, 3 ); final InventoryCrafting ic = new InventoryCrafting( new ContainerNull(), 3, 3 );
@@ -241,7 +241,6 @@ public class CraftingTreeProcess
o.setStackSize( o.getStackSize() * i ); o.setStackSize( o.getStackSize() * i );
inv.injectItems( o, Actionable.MODULATE, src ); inv.injectItems( o, Actionable.MODULATE, src );
} }
this.crafts += i; this.crafts += i;
} }
@@ -253,7 +252,7 @@ public class CraftingTreeProcess
pro.dive( job ); pro.dive( job );
} }
job.addBytes( 8 + this.crafts + this.bytes ); job.addBytes( this.crafts * 8 + this.bytes );
} }
IAEItemStack getAmountCrafted( IAEItemStack what2 ) IAEItemStack getAmountCrafted( IAEItemStack what2 )
@@ -28,7 +28,9 @@ import appeng.api.storage.IStorageChannel;
import appeng.api.storage.channels.IItemStorageChannel; import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList; import appeng.api.storage.data.IItemList;
import appeng.me.helpers.PlayerSource;
import appeng.util.inv.ItemListIgnoreCrafting; import appeng.util.inv.ItemListIgnoreCrafting;
import net.minecraft.util.text.TextComponentString;
public class MECraftingInventory implements IMEInventory<IAEItemStack> public class MECraftingInventory implements IMEInventory<IAEItemStack>
@@ -307,8 +309,19 @@ public class MECraftingInventory implements IMEInventory<IAEItemStack>
if( result == null || result.getStackSize() != extra.getStackSize() ) if( result == null || result.getStackSize() != extra.getStackSize() )
{ {
if( src.player().isPresent() )
{
if( result == null )
{
src.player().get().sendStatusMessage( new TextComponentString( "System reported " + extra.getStackSize() + " " + extra.getDefinition().getItem().getItemStackDisplayName( extra.getDefinition() ) + " available but could not extract anything" ), false );
}
else
{
src.player().get().sendStatusMessage( new TextComponentString( "System reported " + extra.getStackSize() + " " + extra.getDefinition().getItem().getItemStackDisplayName( extra.getDefinition() ) + " available but could only extract " + result.getStackSize() ), false );
}
}
failed = true; failed = true;
break; if( !src.player().isPresent() ) break;
} }
} }
} }
@@ -21,6 +21,9 @@ package appeng.fluids.client.gui;
import java.io.IOException; import java.io.IOException;
import appeng.api.util.IConfigManager;
import appeng.client.gui.widgets.GuiCustomSlot;
import appeng.util.IConfigManagerHost;
import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiButton;
import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.entity.player.InventoryPlayer;
@@ -38,11 +41,12 @@ import appeng.fluids.helper.IFluidInterfaceHost;
import appeng.fluids.util.IAEFluidTank; import appeng.fluids.util.IAEFluidTank;
public class GuiFluidInterface extends GuiUpgradeable public class GuiFluidInterface extends GuiUpgradeable implements IConfigManagerHost
{ {
public final static int ID_BUTTON_TANK = 222; public final static int ID_BUTTON_TANK = 222;
private final IFluidInterfaceHost host; private final IFluidInterfaceHost host;
private final ContainerFluidInterface container;
private GuiTabButton priority; private GuiTabButton priority;
public GuiFluidInterface( final InventoryPlayer ip, final IFluidInterfaceHost te ) public GuiFluidInterface( final InventoryPlayer ip, final IFluidInterfaceHost te )
@@ -50,6 +54,8 @@ public class GuiFluidInterface extends GuiUpgradeable
super( new ContainerFluidInterface( ip, te ) ); super( new ContainerFluidInterface( ip, te ) );
this.ySize = 231; this.ySize = 231;
this.host = te; this.host = te;
( this.container = (ContainerFluidInterface) this.inventorySlots ).setGui( this );
} }
@Override @Override
@@ -62,9 +68,7 @@ public class GuiFluidInterface extends GuiUpgradeable
for( int i = 0; i < DualityFluidInterface.NUMBER_OF_TANKS; ++i ) for( int i = 0; i < DualityFluidInterface.NUMBER_OF_TANKS; ++i )
{ {
final GuiFluidTank guiTank = new GuiFluidTank( fluidTank, i, DualityFluidInterface.NUMBER_OF_TANKS + i, this.getGuiLeft() + 35 + 18 * i, this this.guiSlots.add( new GuiFluidTank( fluidTank, i, DualityFluidInterface.NUMBER_OF_TANKS + i, 36 + 18 * i, 53, 16, 68 ) );
.getGuiTop() + 53, 16, 68 );
this.buttonList.add( guiTank );
this.guiSlots.add( new GuiFluidSlot( configFluids, i, i, 35 + 18 * i, 35 ) ); this.guiSlots.add( new GuiFluidSlot( configFluids, i, i, 35 + 18 * i, 35 ) );
} }
@@ -104,9 +108,33 @@ public class GuiFluidInterface extends GuiUpgradeable
} }
} }
@Override
protected void mouseClicked( int xCoord, int yCoord, int btn ) throws IOException
{
for( GuiCustomSlot slot : this.guiSlots )
{
if( slot instanceof GuiFluidTank )
{
if( this.isPointInRegion( slot.xPos(), slot.yPos(), slot.getWidth(), slot.getHeight(), xCoord, yCoord ) && slot.canClick( this.mc.player ) )
{
this.container.setTargetStack( ( (GuiFluidTank) slot ).getFluidStack() );
slot.slotClicked( this.mc.player.inventory.getItemStack(), btn );
return;
}
}
}
super.mouseClicked( xCoord, yCoord, btn );
}
@Override @Override
protected boolean drawUpgrades() protected boolean drawUpgrades()
{ {
return false; return false;
} }
@Override
public void updateSetting( IConfigManager manager, Enum settingName, Enum newValue )
{
}
} }
@@ -19,42 +19,50 @@
package appeng.fluids.client.gui.widgets; package appeng.fluids.client.gui.widgets;
import appeng.client.gui.widgets.GuiCustomSlot;
import appeng.core.sync.network.NetworkHandler;
import appeng.core.sync.packets.PacketInventoryAction;
import appeng.helpers.InventoryAction;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.fml.relauncher.SideOnly;
import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IAEFluidStack;
import appeng.api.util.AEColor;
import appeng.client.gui.widgets.ITooltip; import appeng.client.gui.widgets.ITooltip;
import appeng.fluids.util.IAEFluidTank; import appeng.fluids.util.IAEFluidTank;
@SideOnly( Side.CLIENT ) @SideOnly( Side.CLIENT )
public class GuiFluidTank extends GuiButton implements ITooltip public class GuiFluidTank extends GuiCustomSlot implements ITooltip
{ {
private final IAEFluidTank tank; private final IAEFluidTank tank;
private final int slot; private final int slot;
private final int width;
private final int height;
public GuiFluidTank( IAEFluidTank tank, int slot, int id, int x, int y, int w, int h ) public GuiFluidTank( IAEFluidTank tank, int slot, int id, int x, int y, int w, int h )
{ {
super( id, x, y, w, h, "" ); super( id, x, y );
this.tank = tank; this.tank = tank;
this.slot = slot; this.slot = slot;
this.width = w;
this.height = h;
} }
@Override @Override
public void drawButton( final Minecraft mc, final int mouseX, final int mouseY, final float partialTicks ) public void drawContent( Minecraft mc, int mouseX, int mouseY, float partialTicks )
{ {
if( this.visible ) final IAEFluidStack fs = this.getFluidStack();
if( fs != null )
{ {
GlStateManager.disableBlend(); GlStateManager.disableBlend();
GlStateManager.disableLighting(); GlStateManager.disableLighting();
drawRect( this.x, this.y, this.x + this.width, this.y + this.height, AEColor.GRAY.blackVariant | 0xFF000000 ); //drawRect( this.x, this.y, this.x + this.width, this.y + this.height, AEColor.GRAY.blackVariant | 0xFF000000 );
final IAEFluidStack fluid = this.tank.getFluidInSlot( this.slot ); final IAEFluidStack fluid = this.tank.getFluidInSlot( this.slot );
if( fluid != null && fluid.getStackSize() > 0 ) if( fluid != null && fluid.getStackSize() > 0 )
@@ -69,17 +77,16 @@ public class GuiFluidTank extends GuiButton implements ITooltip
TextureAtlasSprite sprite = mc.getTextureMapBlocks().getAtlasSprite( fluid.getFluid().getStill().toString() ); TextureAtlasSprite sprite = mc.getTextureMapBlocks().getAtlasSprite( fluid.getFluid().getStill().toString() );
final int scaledHeight = (int) ( this.height * ( (float) fluid.getStackSize() / this.tank.getTankProperties()[this.slot].getCapacity() ) ); final int scaledHeight = (int) ( this.height * ( (float) fluid.getStackSize() / this.tank.getTankProperties()[this.slot].getCapacity() ) );
int iconHeightRemainder = scaledHeight % 16; int iconHeightRemainder = scaledHeight % this.getHeight();
if( iconHeightRemainder > 0 ) if( iconHeightRemainder > 0 )
{ {
this.drawTexturedModalRect( this.x, this.y + this.height - iconHeightRemainder, sprite, 16, iconHeightRemainder ); this.drawTexturedModalRect( this.xPos(), this.yPos() + this.getHeight() - iconHeightRemainder, sprite, this.getWidth(), iconHeightRemainder );
} }
for( int i = 0; i < scaledHeight / 16; i++ ) for( int i = 0; i < scaledHeight / this.getHeight(); i++ )
{ {
this.drawTexturedModalRect( this.x, this.y + this.height - iconHeightRemainder - ( i + 1 ) * 16, sprite, 16, 16 ); this.drawTexturedModalRect( this.xPos(), this.yPos() + this.getHeight() - iconHeightRemainder - ( i + 1 ) * 16, sprite, this.getWidth(), this.getHeight() );
} }
} }
} }
} }
@@ -100,25 +107,25 @@ public class GuiFluidTank extends GuiButton implements ITooltip
@Override @Override
public int xPos() public int xPos()
{ {
return this.x - 2; return this.x - 1;
} }
@Override @Override
public int yPos() public int yPos()
{ {
return this.y - 2; return this.y - 1;
} }
@Override @Override
public int getWidth() public int getWidth()
{ {
return this.width + 4; return this.width;
} }
@Override @Override
public int getHeight() public int getHeight()
{ {
return this.height + 4; return this.height + 1;
} }
@Override @Override
@@ -127,4 +134,24 @@ public class GuiFluidTank extends GuiButton implements ITooltip
return true; return true;
} }
public IAEFluidStack getFluidStack()
{
return this.tank.getFluidInSlot( this.slot );
}
@Override
public void slotClicked( ItemStack clickStack, final int mouseButton )
{
if( getFluidStack() != null )
{
NetworkHandler.instance().sendToServer( new PacketInventoryAction( InventoryAction.FILL_ITEM, slot, 0 ) );
}
else
{
NetworkHandler.instance().sendToServer( new PacketInventoryAction( InventoryAction.EMPTY_ITEM, slot, 0 ) );
}
}
} }
@@ -19,9 +19,17 @@
package appeng.fluids.container; package appeng.fluids.container;
import javax.annotation.Nonnull;
import java.util.Collections; import java.util.Collections;
import java.util.Map; import java.util.Map;
import appeng.core.sync.network.NetworkHandler;
import appeng.core.sync.packets.PacketTargetFluidStack;
import appeng.fluids.util.AEFluidStack;
import appeng.helpers.InventoryAction;
import appeng.util.IConfigManagerHost;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.IContainerListener; import net.minecraft.inventory.IContainerListener;
@@ -33,12 +41,19 @@ import appeng.fluids.helper.FluidSyncHelper;
import appeng.fluids.helper.IFluidInterfaceHost; import appeng.fluids.helper.IFluidInterfaceHost;
import appeng.fluids.util.IAEFluidTank; import appeng.fluids.util.IAEFluidTank;
import appeng.util.Platform; import appeng.util.Platform;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidUtil;
import net.minecraftforge.fluids.capability.IFluidHandlerItem;
public class ContainerFluidInterface extends ContainerFluidConfigurable public class ContainerFluidInterface extends ContainerFluidConfigurable implements IConfigManagerHost
{ {
private final DualityFluidInterface myDuality; private final DualityFluidInterface myDuality;
private final FluidSyncHelper tankSync; private final FluidSyncHelper tankSync;
private IConfigManagerHost gui;
// Holds the fluid the client wishes to extract, or null for insert
private IAEFluidStack clientRequestedTargetFluid = null;
public ContainerFluidInterface( final InventoryPlayer ip, final IFluidInterfaceHost te ) public ContainerFluidInterface( final InventoryPlayer ip, final IFluidInterfaceHost te )
{ {
@@ -60,6 +75,15 @@ public class ContainerFluidInterface extends ContainerFluidConfigurable
return this.myDuality.getConfig(); return this.myDuality.getConfig();
} }
@Override
public void updateSetting( IConfigManager manager, Enum settingName, Enum newValue )
{
if( this.getGui() != null )
{
this.getGui().updateSetting( manager, settingName, newValue );
}
}
@Override @Override
public void detectAndSendChanges() public void detectAndSendChanges()
{ {
@@ -97,6 +121,126 @@ public class ContainerFluidInterface extends ContainerFluidConfigurable
this.tankSync.readPacket( fluids ); this.tankSync.readPacket( fluids );
} }
private IConfigManagerHost getGui()
{
return this.gui;
}
public void setGui( @Nonnull final IConfigManagerHost gui )
{
this.gui = gui;
}
public void doAction( EntityPlayerMP player, InventoryAction action, int slot, long id )
{
if( action != InventoryAction.FILL_ITEM && action != InventoryAction.EMPTY_ITEM )
{
super.doAction( player, action, slot, id );
return;
}
final ItemStack held = player.inventory.getItemStack();
ItemStack heldCopy = held.copy();
heldCopy.setCount( 1 );
IFluidHandlerItem fh = FluidUtil.getFluidHandler( heldCopy );
if( fh == null )
{
// only fluid handlers items
return;
}
if( action == InventoryAction.FILL_ITEM && this.clientRequestedTargetFluid != null )
{
final IAEFluidStack stack = this.clientRequestedTargetFluid.copy();
// Check how much we can store in the item
stack.setStackSize( Integer.MAX_VALUE );
int amountAllowed = fh.fill( stack.getFluidStack(), false );
int heldAmount = held.getCount();
for( int i = 0; i < heldAmount; i++ )
{
ItemStack copiedFluidContainer = held.copy();
copiedFluidContainer.setCount( 1 );
fh = FluidUtil.getFluidHandler( copiedFluidContainer );
FluidStack extractableFluid = this.myDuality.getTanks().drain( stack.setStackSize( amountAllowed ).getFluidStack(), false );
if( extractableFluid == null || extractableFluid.amount == 0 )
{
break;
}
int fillableAmount = fh.fill( extractableFluid, false );
if( fillableAmount > 0 )
{
FluidStack extractedFluid = this.myDuality.getTanks().drain( extractableFluid, true );
fh.fill( extractedFluid, 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 );
}
}
}
}
else if( action == InventoryAction.EMPTY_ITEM )
{
int heldAmount = held.getCount();
for( int i = 0; i < heldAmount; i++ )
{
ItemStack copiedFluidContainer = held.copy();
copiedFluidContainer.setCount( 1 );
fh = FluidUtil.getFluidHandler( copiedFluidContainer );
FluidStack drainable = fh.drain( this.myDuality.getTanks().getTankProperties()[slot].getCapacity(), false );
if( drainable != null )
{
fh.drain( drainable, true );
this.myDuality.getTanks().fill( drainable, 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 );
}
}
}
}
this.updateHeld( player );
}
public void setTargetStack( final IAEFluidStack stack )
{
if( Platform.isClient() )
{
if( stack == null && this.clientRequestedTargetFluid == null )
{
return;
}
if( stack != null && this.clientRequestedTargetFluid != null && stack.getFluidStack().isFluidEqual( this.clientRequestedTargetFluid.getFluidStack() ) )
{
return;
}
NetworkHandler.instance().sendToServer( new PacketTargetFluidStack( (AEFluidStack) stack ) );
}
this.clientRequestedTargetFluid = stack == null ? null : stack.copy();
}
@Override @Override
protected boolean supportCapacity() protected boolean supportCapacity()
{ {
@@ -24,6 +24,9 @@ import java.nio.BufferOverflowException;
import javax.annotation.Nonnull; 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.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.entity.player.InventoryPlayer;
@@ -70,6 +73,7 @@ import appeng.me.helpers.ChannelPowerSrc;
import appeng.util.ConfigManager; import appeng.util.ConfigManager;
import appeng.util.IConfigManagerHost; import appeng.util.IConfigManagerHost;
import appeng.util.Platform; 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 @Override
public void doAction( EntityPlayerMP player, InventoryAction action, int slot, long id ) 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(); final ItemStack held = player.inventory.getItemStack();
if( held.getCount() != 1 ) ItemStack heldCopy = held.copy();
{ heldCopy.setCount( 1 );
// only support stacksize 1 for now IFluidHandlerItem fh = FluidUtil.getFluidHandler( heldCopy );
return;
}
final IFluidHandlerItem fh = FluidUtil.getFluidHandler( held );
if( fh == null ) if( fh == null )
{ {
// only fluid handlers items // only fluid handlers items
@@ -372,84 +455,122 @@ public class ContainerFluidTerminal extends AEBaseContainer implements IConfigMa
// Check how much we can store in the item // Check how much we can store in the item
stack.setStackSize( Integer.MAX_VALUE ); stack.setStackSize( Integer.MAX_VALUE );
int amountAllowed = fh.fill( stack.getFluidStack(), false ); int amountAllowed = fh.fill( stack.getFluidStack(), false );
stack.setStackSize( amountAllowed ); int heldAmount = held.getCount();
for( int i = 0; i < heldAmount; i++ )
// 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 )
{ {
return; ItemStack copiedFluidContainer = held.copy();
} copiedFluidContainer.setCount( 1 );
fh = FluidUtil.getFluidHandler( copiedFluidContainer );
// How much could fit into the container // Check if we can pull out of the system
final int canFill = fh.fill( canPull.getFluidStack(), false ); final IAEFluidStack canPull = Platform.poweredExtraction( this.getPowerSource(), this.monitor, stack.setStackSize( amountAllowed ), this.getActionSource(), Actionable.SIMULATE );
if( canFill == 0 ) if( canPull == null || canPull.getStackSize() < 1 )
{
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 )
{ {
return; 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 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 ); else if( action == InventoryAction.EMPTY_ITEM )
extract.amount = drained.amount; {
int heldAmount = held.getCount();
final IAEFluidStack notInserted = Platform.poweredInsert( this.getPowerSource(), this.monitor, AEFluidStack.fromFluidStack( extract ), for( int i = 0; i < heldAmount; i++ )
this.getActionSource() );
if( notInserted != null && notInserted.getStackSize() > 0 )
{ {
AELog.error( "Fluid item [%s] reported a different possible amount to drain than it actually provided.", held.getDisplayName() ); ItemStack copiedFluidContainer = held.copy();
} copiedFluidContainer.setCount( 1 );
fh = FluidUtil.getFluidHandler( copiedFluidContainer );
player.inventory.setItemStack( fh.getContainer() ); // 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 )
{
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 );
}
}
}
this.updateHeld( player ); this.updateHeld( player );
} }
} }
@@ -91,12 +91,10 @@ public class DualityFluidInterface implements IGridTickable, IStorageMonitorable
private int isWorking = -1; private int isWorking = -1;
private int priority; private int priority;
private final MEMonitorPassThrough<IAEItemStack> items = new MEMonitorPassThrough<>( new NullInventory<IAEItemStack>(), AEApi.instance() private final MEMonitorPassThrough<IAEItemStack> items = new MEMonitorPassThrough<>( new NullInventory<IAEItemStack>(), AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) );
.storage() private final MEMonitorPassThrough<IAEFluidStack> fluids = new MEMonitorPassThrough<>( new NullInventory<IAEFluidStack>(), AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) );
.getStorageChannel( IItemStorageChannel.class ) ); private boolean resetConfigCache;
private final MEMonitorPassThrough<IAEFluidStack> fluids = new MEMonitorPassThrough<>( new NullInventory<IAEFluidStack>(), AEApi.instance() private IMEMonitor<IAEFluidStack> configCachedHandler;
.storage()
.getStorageChannel( IFluidStorageChannel.class ) );
public DualityFluidInterface( final AENetworkProxy networkProxy, final IFluidInterfaceHost ih ) public DualityFluidInterface( final AENetworkProxy networkProxy, final IFluidInterfaceHost ih )
{ {
@@ -146,7 +144,12 @@ public class DualityFluidInterface implements IGridTickable, IStorageMonitorable
{ {
if( this.hasConfig() ) if( this.hasConfig() )
{ {
return (IMEMonitor<T>) new InterfaceInventory( this ); if( resetConfigCache )
{
resetConfigCache = false;
configCachedHandler = new InterfaceInventory( this );
}
return (IMEMonitor<T>) configCachedHandler;
} }
return (IMEMonitor<T>) this.fluids; return (IMEMonitor<T>) this.fluids;
@@ -383,7 +386,7 @@ public class DualityFluidInterface implements IGridTickable, IStorageMonitorable
{ {
changed = true; changed = true;
} }
else else if( this.gridProxy.getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ).getStorageList().findPrecise( work ) != null )
{ {
final IAEFluidStack acquired = Platform.poweredExtraction( src, dest, work, this.interfaceRequestSource ); final IAEFluidStack acquired = Platform.poweredExtraction( src, dest, work, this.interfaceRequestSource );
if( acquired != null ) if( acquired != null )
@@ -450,7 +453,12 @@ public class DualityFluidInterface implements IGridTickable, IStorageMonitorable
if( inventory == this.config ) if( inventory == this.config )
{ {
boolean cfg = hasConfig();
this.readConfig(); this.readConfig();
if( cfg != hasConfig )
{
resetConfigCache = true;
}
} }
else if( inventory == this.tanks ) else if( inventory == this.tanks )
{ {
@@ -555,7 +563,6 @@ public class DualityFluidInterface implements IGridTickable, IStorageMonitorable
InterfaceInventory( final DualityFluidInterface tileInterface ) InterfaceInventory( final DualityFluidInterface tileInterface )
{ {
super( tileInterface.tanks ); super( tileInterface.tanks );
this.setActionSource( new MachineSource( tileInterface.iHost ) );
} }
@Override @Override
@@ -19,16 +19,15 @@
package appeng.fluids.parts; package appeng.fluids.parts;
import java.util.ArrayList; import java.util.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import appeng.api.config.AccessRestriction;
import appeng.api.config.Settings; import appeng.api.config.Settings;
import appeng.api.config.StorageFilter; import appeng.api.config.StorageFilter;
import appeng.parts.misc.PartStorageBus; import appeng.api.storage.data.IAEItemStack;
import appeng.me.GridAccessException;
import appeng.util.inv.ItemSlot;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.fluids.capability.IFluidHandler;
import net.minecraftforge.fluids.capability.IFluidTankProperties; import net.minecraftforge.fluids.capability.IFluidTankProperties;
@@ -45,7 +44,6 @@ import appeng.api.storage.channels.IFluidStorageChannel;
import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IAEFluidStack;
import appeng.api.storage.data.IItemList; import appeng.api.storage.data.IItemList;
import appeng.fluids.util.AEFluidStack; import appeng.fluids.util.AEFluidStack;
import appeng.me.GridAccessException;
import appeng.me.helpers.IGridProxyable; import appeng.me.helpers.IGridProxyable;
import appeng.me.storage.ITickingMonitor; import appeng.me.storage.ITickingMonitor;
@@ -65,17 +63,20 @@ public class FluidHandlerAdapter implements IMEInventory<IAEFluidStack>, IBaseMo
private final IGridProxyable proxyable; private final IGridProxyable proxyable;
private final FluidHandlerAdapter.InventoryCache cache; private final FluidHandlerAdapter.InventoryCache cache;
private StorageFilter mode; private StorageFilter mode;
private AccessRestriction access;
FluidHandlerAdapter( IFluidHandler fluidHandler, IGridProxyable proxy ) FluidHandlerAdapter( IFluidHandler fluidHandler, IGridProxyable proxy )
{ {
this.fluidHandler = fluidHandler; this.fluidHandler = fluidHandler;
this.proxyable = proxy; this.proxyable = proxy;
if( this.proxyable instanceof PartStorageBus ) if( this.proxyable instanceof PartFluidStorageBus )
{ {
PartStorageBus partStorageBus = (PartStorageBus) this.proxyable; PartFluidStorageBus partFluidStorageBus = (PartFluidStorageBus) this.proxyable;
this.mode = ( (StorageFilter) partStorageBus.getConfigManager().getSetting( Settings.STORAGE_FILTER ) ); this.mode = ( (StorageFilter) partFluidStorageBus.getConfigManager().getSetting( Settings.STORAGE_FILTER ) );
this.access = ( (AccessRestriction) partFluidStorageBus.getConfigManager().getSetting( Settings.ACCESS ) );
} }
this.cache = new FluidHandlerAdapter.InventoryCache( this.fluidHandler, this.mode); this.cache = new FluidHandlerAdapter.InventoryCache( this.fluidHandler, this.mode );
this.cache.update();
} }
@Override @Override
@@ -94,11 +95,14 @@ public class FluidHandlerAdapter implements IMEInventory<IAEFluidStack>, IBaseMo
if( type == Actionable.MODULATE ) if( type == Actionable.MODULATE )
{ {
IAEFluidStack added = input.copy().setStackSize( input.getStackSize() - remaining );
this.cache.currentlyCached.add( added );
this.postDifference( Collections.singletonList( added ) );
try try
{ {
this.proxyable.getProxy().getTick().alertDevice( this.proxyable.getProxy().getNode() ); this.proxyable.getProxy().getTick().alertDevice( this.proxyable.getProxy().getNode() );
} }
catch( GridAccessException ignore ) catch( GridAccessException ex )
{ {
// meh // meh
} }
@@ -123,25 +127,32 @@ public class FluidHandlerAdapter implements IMEInventory<IAEFluidStack>, IBaseMo
return null; return null;
} }
IAEFluidStack gatheredAEFluidstack = AEFluidStack.fromFluidStack( gathered );
if( mode == Actionable.MODULATE ) if( mode == Actionable.MODULATE )
{ {
IAEFluidStack cachedStack = this.cache.currentlyCached.findPrecise( request );
if( cachedStack != null )
{
cachedStack.decStackSize( gatheredAEFluidstack.getStackSize() );
this.postDifference( Collections.singletonList( gatheredAEFluidstack.copy().setStackSize( -gatheredAEFluidstack.getStackSize() ) ) );
}
try try
{ {
this.proxyable.getProxy().getTick().alertDevice( this.proxyable.getProxy().getNode() ); this.proxyable.getProxy().getTick().alertDevice( this.proxyable.getProxy().getNode() );
} }
catch( GridAccessException ignore ) catch( GridAccessException ex )
{ {
// meh // meh
} }
} }
return AEFluidStack.fromFluidStack( gathered ); return gatheredAEFluidstack;
} }
@Override @Override
public TickRateModulation onTick() public TickRateModulation onTick()
{ {
List<IAEFluidStack> changes = this.cache.update(); List<IAEFluidStack> changes = this.cache.update();
if( !changes.isEmpty() ) if( !changes.isEmpty() && access.hasPermission( AccessRestriction.READ ) )
{ {
this.postDifference( changes ); this.postDifference( changes );
return TickRateModulation.URGENT; return TickRateModulation.URGENT;
@@ -202,9 +213,9 @@ public class FluidHandlerAdapter implements IMEInventory<IAEFluidStack>, IBaseMo
private static class InventoryCache private static class InventoryCache
{ {
private IAEFluidStack[] cachedAeStacks = new IAEFluidStack[0];
private final IFluidHandler fluidHandler; private final IFluidHandler fluidHandler;
private final StorageFilter mode; private final StorageFilter mode;
IItemList<IAEFluidStack> currentlyCached = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ).createList();
public InventoryCache( IFluidHandler fluidHandler, StorageFilter mode ) public InventoryCache( IFluidHandler fluidHandler, StorageFilter mode )
{ {
@@ -216,102 +227,46 @@ public class FluidHandlerAdapter implements IMEInventory<IAEFluidStack>, IBaseMo
{ {
final List<IAEFluidStack> changes = new ArrayList<>(); final List<IAEFluidStack> changes = new ArrayList<>();
final IFluidTankProperties[] tankProperties = this.fluidHandler.getTankProperties(); final IFluidTankProperties[] tankProperties = this.fluidHandler.getTankProperties();
final int slots = tankProperties.length;
// Make room for new slots IItemList<IAEFluidStack> currentlyOnStorage = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ).createList();
if( slots > this.cachedAeStacks.length )
{
this.cachedAeStacks = Arrays.copyOf( this.cachedAeStacks, slots );
}
for( int slot = 0; slot < slots; slot++ ) for( IFluidTankProperties tankProperty : tankProperties )
{ {
// Save the old stuff if( this.mode == StorageFilter.EXTRACTABLE_ONLY && this.fluidHandler.drain( 1, false ) == null )
final IAEFluidStack oldAEFS = this.cachedAeStacks[slot];
FluidStack newFS = tankProperties[slot].getContents();
if( this.mode == StorageFilter.EXTRACTABLE_ONLY && newFS != null )
{ {
if( this.fluidHandler.drain( 1, false ) == null ) continue;
{
newFS = null;
}
} }
this.handlePossibleSlotChanges( slot, oldAEFS, newFS, changes ); currentlyOnStorage.add( AEFluidStack.fromFluidStack( tankProperty.getContents() ) );
} }
// Handle cases where the number of slots actually is lower now than before for ( final IAEFluidStack is : currentlyCached )
if( slots < this.cachedAeStacks.length )
{ {
for( int slot = slots; slot < this.cachedAeStacks.length; slot++ ) is.setStackSize( -is.getStackSize() );
{
final IAEFluidStack aeStack = this.cachedAeStacks[slot];
if( aeStack != null )
{
final IAEFluidStack a = aeStack.copy();
a.setStackSize( -a.getStackSize() );
changes.add( a );
}
}
this.cachedAeStacks = Arrays.copyOf( this.cachedAeStacks, slots );
} }
for ( final IAEFluidStack is : currentlyOnStorage )
{
currentlyCached.add( is );
}
for ( final IAEFluidStack is : currentlyCached )
{
if( is.getStackSize() != 0 )
{
changes.add( is );
}
}
currentlyCached = currentlyOnStorage;
return changes; return changes;
} }
public IItemList<IAEFluidStack> getAvailableItems( IItemList<IAEFluidStack> out ) public IItemList<IAEFluidStack> getAvailableItems( IItemList<IAEFluidStack> out )
{ {
Arrays.stream( this.cachedAeStacks ).forEach( out::add ); currentlyCached.iterator().forEachRemaining( out::add );
return out; 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] );
}
}
} }
} }
@@ -178,8 +178,9 @@ public class PartFluidFormationPlane extends PartAbstractFormationPlane<IAEFluid
this.stateChanged(); this.stateChanged();
} }
@Override
@MENetworkEventSubscribe @MENetworkEventSubscribe
public void updateChannels( final MENetworkChannelsChanged changedChannels ) public void chanRender( final MENetworkChannelsChanged changedChannels )
{ {
this.stateChanged(); this.stateChanged();
} }
@@ -204,7 +205,7 @@ public class PartFluidFormationPlane extends PartAbstractFormationPlane<IAEFluid
@Override @Override
public List<IMEInventoryHandler> getCellArray( final IStorageChannel channel ) public List<IMEInventoryHandler> getCellArray( final IStorageChannel channel )
{ {
if( this.getProxy().isActive() && channel == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ) if( channel == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) )
{ {
final List<IMEInventoryHandler> handler = new ArrayList<>( 1 ); final List<IMEInventoryHandler> handler = new ArrayList<>( 1 );
handler.add( this.myHandler ); handler.add( this.myHandler );
@@ -90,14 +90,16 @@ public class PartFluidInterface extends PartBasicState implements IGridTickable,
return this.duality; return this.duality;
} }
@Override
@MENetworkEventSubscribe @MENetworkEventSubscribe
public void stateChange( final MENetworkChannelsChanged c ) public void chanRender( final MENetworkChannelsChanged c )
{ {
this.duality.notifyNeighbors(); this.duality.notifyNeighbors();
} }
@Override
@MENetworkEventSubscribe @MENetworkEventSubscribe
public void stateChange( final MENetworkPowerStatusChange c ) public void powerRender( final MENetworkPowerStatusChange c )
{ {
this.duality.notifyNeighbors(); this.duality.notifyNeighbors();
} }
@@ -4,7 +4,9 @@ package appeng.fluids.parts;
import java.util.Random; import java.util.Random;
import appeng.api.storage.data.IItemList;
import appeng.fluids.helper.IConfigurableFluidInventory; import appeng.fluids.helper.IConfigurableFluidInventory;
import appeng.me.cache.NetworkMonitor;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
@@ -34,7 +36,6 @@ import appeng.api.storage.IStorageChannel;
import appeng.api.storage.channels.IFluidStorageChannel; import appeng.api.storage.channels.IFluidStorageChannel;
import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IAEFluidStack;
import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IAEStack;
import appeng.api.storage.data.IItemList;
import appeng.api.util.AECableType; import appeng.api.util.AECableType;
import appeng.api.util.AEPartLocation; import appeng.api.util.AEPartLocation;
import appeng.api.util.IConfigManager; import appeng.api.util.IConfigManager;
@@ -114,7 +115,7 @@ public class PartFluidLevelEmitter extends PartUpgradeable implements IStackWatc
@Override @Override
public void onStackChange( IItemList<?> o, IAEStack<?> fullStack, IAEStack<?> diffStack, IActionSource src, IStorageChannel<?> chan ) public void onStackChange( IItemList<?> o, IAEStack<?> fullStack, IAEStack<?> diffStack, IActionSource src, 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 = fullStack.getStackSize();
this.updateState(); this.updateState();
@@ -127,15 +128,25 @@ public class PartFluidLevelEmitter extends PartUpgradeable implements IStackWatc
this.configureWatchers(); this.configureWatchers();
} }
@Override
@MENetworkEventSubscribe @MENetworkEventSubscribe
public void channelChanged( final MENetworkChannelsChanged c ) public void powerRender( final MENetworkPowerStatusChange powerEvent )
{ {
if (this.getProxy().isActive())
{
onListUpdate();
}
this.updateState(); this.updateState();
} }
@Override
@MENetworkEventSubscribe @MENetworkEventSubscribe
public void powerChanged( final MENetworkPowerStatusChange c ) public void chanRender( final MENetworkChannelsChanged c )
{ {
if (this.getProxy().isActive())
{
onListUpdate();
}
this.updateState(); this.updateState();
} }
@@ -247,10 +258,9 @@ public class PartFluidLevelEmitter extends PartUpgradeable implements IStackWatc
if( myStack == null ) if( myStack == null )
{ {
this.lastReportedValue = 0; if( monitor instanceof NetworkMonitor )
for( final IAEFluidStack st : monitor.getStorageList() )
{ {
this.lastReportedValue += st.getStackSize(); this.lastReportedValue = ( (NetworkMonitor<IAEFluidStack>) monitor ).getGridCurrentCount();
} }
} }
else else
@@ -25,7 +25,11 @@ import java.util.Objects;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import appeng.api.networking.storage.IStorageGrid;
import appeng.api.storage.channels.IItemStorageChannel;
import appeng.fluids.helper.IConfigurableFluidInventory; import appeng.fluids.helper.IConfigurableFluidInventory;
import appeng.me.cache.GridStorageCache;
import appeng.util.ConfigManager;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
@@ -167,11 +171,27 @@ public class PartFluidStorageBus extends PartSharedStorageBus implements IMEMoni
final boolean fullReset = this.resetCacheLogic == 2; final boolean fullReset = this.resetCacheLogic == 2;
this.resetCacheLogic = 0; this.resetCacheLogic = 0;
final IMEInventory<IAEFluidStack> in = this.getInternalHandler(); final MEInventoryHandler<IAEFluidStack> in = this.getInternalHandler();
IItemList<IAEFluidStack> before = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ).createList(); IItemList<IAEFluidStack> before = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ).createList();
if( in != null ) if( in != null )
{ {
before = in.getAvailableItems( before ); if( accessChanged )
{
AccessRestriction currentAccess = (AccessRestriction) ( (ConfigManager) this.getConfigManager() ).getSetting( Settings.ACCESS );
AccessRestriction oldAccess = (AccessRestriction) ( (ConfigManager) this.getConfigManager() ).getOldSetting( Settings.ACCESS );
if( oldAccess.hasPermission( AccessRestriction.READ ) && !currentAccess.hasPermission( AccessRestriction.READ ) )
{
readOncePass = true;
}
in.setBaseAccess( oldAccess );
before = in.getAvailableItems( before );
in.setBaseAccess( currentAccess );
accessChanged = false;
}
else
{
before = in.getAvailableItems( before );
}
} }
this.cached = false; this.cached = false;
@@ -180,11 +200,11 @@ public class PartFluidStorageBus extends PartSharedStorageBus implements IMEMoni
this.handlerHash = 0; this.handlerHash = 0;
} }
final IMEInventory<IAEFluidStack> out = this.getInternalHandler(); final MEInventoryHandler<IAEFluidStack> out = this.getInternalHandler();
IItemList<IAEFluidStack> after = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ).createList();
if( in != out ) if( in != out )
{ {
IItemList<IAEFluidStack> after = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ).createList();
if( out != null ) if( out != null )
{ {
after = out.getAvailableItems( after ); after = out.getAvailableItems( after );
@@ -207,7 +227,7 @@ public class PartFluidStorageBus extends PartSharedStorageBus implements IMEMoni
{ {
this.resetCacheLogic = 2; this.resetCacheLogic = 2;
} }
else else if( this.resetCacheLogic < 2 )
{ {
this.resetCacheLogic = 1; this.resetCacheLogic = 1;
} }
@@ -264,14 +284,29 @@ public class PartFluidStorageBus extends PartSharedStorageBus implements IMEMoni
@Override @Override
public void postChange( final IBaseMonitor<IAEFluidStack> monitor, final Iterable<IAEFluidStack> change, final IActionSource source ) 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 ) ) if( this.getProxy().isActive() )
{ {
AccessRestriction currentAccess = (AccessRestriction) ( (ConfigManager) this.getConfigManager() ).getSetting( Settings.ACCESS );
if( readOncePass )
{
readOncePass = false;
try
{
this.getProxy().getStorage().postAlterationOfStoredItems( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ), change, source );
}
catch( final GridAccessException e )
{
// :(
}
return;
}
if( !currentAccess.hasPermission( AccessRestriction.READ ) )
{
return;
}
try try
{ {
if( this.getProxy().isActive() ) this.getProxy().getStorage().postAlterationOfStoredItems( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ), change, source );
{
this.getProxy().getStorage().postAlterationOfStoredItems( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ), change, this.source );
}
} }
catch( final GridAccessException e ) catch( final GridAccessException e )
{ {
@@ -301,6 +336,10 @@ public class PartFluidStorageBus extends PartSharedStorageBus implements IMEMoni
this.handlerHash = newHandlerHash; this.handlerHash = newHandlerHash;
this.handler = null; this.handler = null;
if( this.monitor != null )
{
( (IBaseMonitor<IAEFluidStack>) monitor ).removeListener( this );
}
this.monitor = null; this.monitor = null;
if( target != null ) if( target != null )
{ {
@@ -308,7 +347,8 @@ public class PartFluidStorageBus extends PartSharedStorageBus implements IMEMoni
if( inv instanceof ITickingMonitor ) if( inv instanceof ITickingMonitor )
{ {
this.monitor = (ITickingMonitor) inv; this.monitor = (ITickingMonitor) inv;
this.monitor.setActionSource( new MachineSource( this ) ); this.monitor.setActionSource( this.source );
this.monitor.setMode( (StorageFilter) this.getConfigManager().getSetting( Settings.STORAGE_FILTER ) );
} }
if( inv != null ) if( inv != null )
@@ -345,7 +385,10 @@ public class PartFluidStorageBus extends PartSharedStorageBus implements IMEMoni
if( inv instanceof IBaseMonitor ) if( inv instanceof IBaseMonitor )
{ {
( (IBaseMonitor<IAEFluidStack>) inv ).addListener( this, this.handler ); if( ( (AccessRestriction) ( (ConfigManager) this.getConfigManager() ).getSetting( Settings.ACCESS ) ).hasPermission( AccessRestriction.READ ) )
{
( (IBaseMonitor<IAEFluidStack>) inv ).addListener( this, this.handler );
}
} }
} }
} }
@@ -374,7 +417,7 @@ public class PartFluidStorageBus extends PartSharedStorageBus implements IMEMoni
try try
{ {
// force grid to update handlers... // force grid to update handlers...
this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); (( GridStorageCache ) this.getProxy().getGrid().getCache( IStorageGrid.class )).cellUpdate( null );
} }
catch( final GridAccessException ignore ) catch( final GridAccessException ignore )
{ {
@@ -415,7 +458,7 @@ public class PartFluidStorageBus extends PartSharedStorageBus implements IMEMoni
{ {
if( channel == this.getStorageChannel() ) if( channel == this.getStorageChannel() )
{ {
final IMEInventoryHandler<IAEFluidStack> out = this.getProxy().isActive() ? this.getInternalHandler() : null; final IMEInventoryHandler<IAEFluidStack> out = this.getInternalHandler();
if( out != null ) if( out != null )
{ {
return Collections.singletonList( out ); return Collections.singletonList( out );
@@ -20,7 +20,6 @@ package appeng.helpers;
import java.util.*; import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@@ -33,8 +32,6 @@ import de.ellpeck.actuallyadditions.api.tile.IPhantomTile;
import gregtech.api.block.machines.BlockMachine; import gregtech.api.block.machines.BlockMachine;
import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.MetaTileEntity;
import gregtech.api.metatileentity.MetaTileEntityHolder; import gregtech.api.metatileentity.MetaTileEntityHolder;
import gregtech.api.metatileentity.TieredMetaTileEntity;
import gregtech.api.metatileentity.WorkableTieredMetaTileEntity;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Items; import net.minecraft.init.Items;
@@ -115,7 +112,7 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
public static final int NUMBER_OF_STORAGE_SLOTS = 9; public static final int NUMBER_OF_STORAGE_SLOTS = 9;
public static final int NUMBER_OF_CONFIG_SLOTS = 9; public static final int NUMBER_OF_CONFIG_SLOTS = 9;
public static final int NUMBER_OF_PATTERN_SLOTS = 9; public static final int NUMBER_OF_PATTERN_SLOTS = 36;
private static final Collection<Block> BAD_BLOCKS = new HashSet<>( 100 ); 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 };
@@ -143,15 +140,17 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
private int isWorking = -1; private int isWorking = -1;
private final Accessor accessor = new Accessor(); private final Accessor accessor = new Accessor();
private EnumSet<EnumFacing> visitedFaces = EnumSet.noneOf( EnumFacing.class ); private EnumSet<EnumFacing> visitedFaces = EnumSet.noneOf( EnumFacing.class );
private EnumMap<EnumFacing,List<ItemStack>> waitingToSendFacing = new EnumMap<>(EnumFacing.class); private EnumMap<EnumFacing, List<ItemStack>> waitingToSendFacing = new EnumMap<>( EnumFacing.class );
private GTCEInventoryAdaptor GTad; private GTCEInventoryAdaptor GTad;
private boolean resetConfigCache = true;
private IMEMonitor<IAEItemStack> configCachedHandler;
public DualityInterface( final AENetworkProxy networkProxy, final IInterfaceHost ih ) public DualityInterface( final AENetworkProxy networkProxy, final IInterfaceHost ih )
{ {
this.gridProxy = networkProxy; this.gridProxy = networkProxy;
this.gridProxy.setFlags( GridFlags.REQUIRE_CHANNEL ); this.gridProxy.setFlags( GridFlags.REQUIRE_CHANNEL );
this.upgrades = new StackUpgradeInventory( this.gridProxy.getMachineRepresentation(), this, 1 ); this.upgrades = new StackUpgradeInventory( this.gridProxy.getMachineRepresentation(), this, 4 );
this.cm.registerSetting( Settings.BLOCK, YesNo.NO ); this.cm.registerSetting( Settings.BLOCK, YesNo.NO );
this.cm.registerSetting( Settings.INTERFACE_TERMINAL, YesNo.YES ); this.cm.registerSetting( Settings.INTERFACE_TERMINAL, YesNo.YES );
@@ -179,10 +178,14 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
{ {
return; return;
} }
if( inv == this.config && ( !removed.isEmpty() || !added.isEmpty() ) )
if( inv == this.config )
{ {
boolean cfg = hasConfig();
this.readConfig(); this.readConfig();
if( cfg != hasConfig )
{
resetConfigCache = true;
}
} }
else if( inv == this.patterns && ( !removed.isEmpty() || !added.isEmpty() ) ) else if( inv == this.patterns && ( !removed.isEmpty() || !added.isEmpty() ) )
{ {
@@ -279,10 +282,11 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
} }
this.waitingToSendFacing = null; this.waitingToSendFacing = null;
final NBTTagCompound waitingListSided = data.getCompoundTag("sidedWaitList"); final NBTTagCompound waitingListSided = data.getCompoundTag( "sidedWaitList" );
for (EnumFacing s : EnumFacing.values()) for( EnumFacing s : EnumFacing.values() )
if (waitingListSided.hasKey( s.name() )) { if( waitingListSided.hasKey( s.name() ) )
{
NBTTagList w = waitingListSided.getTagList( s.name(), 10 ); NBTTagList w = waitingListSided.getTagList( s.name(), 10 );
for( int x = 0; x < w.tagCount(); x++ ) for( int x = 0; x < w.tagCount(); x++ )
{ {
@@ -290,14 +294,31 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
if( c != null ) if( c != null )
{ {
final ItemStack is = new ItemStack( c ); final ItemStack is = new ItemStack( c );
this.addToSendListFacing( is , EnumFacing.getFront( s.getIndex() ) ); this.addToSendListFacing( is, EnumFacing.getFront( s.getIndex() ) );
} }
} }
} }
this.craftingTracker.readFromNBT( data ); this.craftingTracker.readFromNBT( data );
// fix upgrade slot size mismatch
NBTTagCompound up = data.getCompoundTag( "upgrades" );
if( up.hasKey( "Size" ) && up.getInteger( "Size" ) != this.upgrades.getSlots() )
{
up.setInteger( "Size", this.upgrades.getSlots() );
this.upgrades.writeToNBT( up, "upgrades" );
}
this.upgrades.readFromNBT( data, "upgrades" ); this.upgrades.readFromNBT( data, "upgrades" );
this.config.readFromNBT( data, "config" ); this.config.readFromNBT( data, "config" );
NBTTagCompound pa = data.getCompoundTag( "patterns" );
if( pa.hasKey( "Size" ) && pa.getInteger( "Size" ) != this.patterns.getSlots() )
{
pa.setInteger( "Size", this.patterns.getSlots() );
this.upgrades.writeToNBT( pa, "patterns" );
}
this.patterns.readFromNBT( data, "patterns" ); this.patterns.readFromNBT( data, "patterns" );
this.storage.readFromNBT( data, "storage" ); this.storage.readFromNBT( data, "storage" );
this.priority = data.getInteger( "priority" ); this.priority = data.getInteger( "priority" );
@@ -400,9 +421,8 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
private void updateCraftingList() private void updateCraftingList()
{ {
final Boolean[] accountedFor = { false, false, false, false, false, false, false, false, false }; // 9... final Boolean[] accountedFor = new Boolean[this.patterns.getSlots()];
Arrays.fill( accountedFor, false );
assert ( accountedFor.length == this.patterns.getSlots() );
if( !this.gridProxy.isReady() ) if( !this.gridProxy.isReady() )
{ {
@@ -417,7 +437,7 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
final ICraftingPatternDetails details = i.next(); final ICraftingPatternDetails details = i.next();
boolean found = false; boolean found = false;
for( int x = 0; x < accountedFor.length; x++ ) for( int x = 0; x < accountedFor.length ; x++ )
{ {
final ItemStack is = this.patterns.getStackInSlot( x ); final ItemStack is = this.patterns.getStackInSlot( x );
if( details.getPattern() == is ) if( details.getPattern() == is )
@@ -433,7 +453,7 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
} }
} }
for( int x = 0; x < accountedFor.length; x++ ) for( int x = 0; x < accountedFor.length ; x++ )
{ {
if( !accountedFor[x] ) if( !accountedFor[x] )
{ {
@@ -586,6 +606,30 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
return false; return false;
} }
public void dropExcessPatterns()
{
IItemHandler patterns = getPatterns();
List<ItemStack> dropList = new ArrayList<>();
for( int invSlot = 0; invSlot < patterns.getSlots(); invSlot++ )
{
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() > 0 )
{
World world = this.getLocation().getWorld();
BlockPos blockPos = this.getLocation().getPos();
Platform.spawnDrops( world, blockPos, dropList );
}
this.gridProxy.setIdlePowerUsage( Math.pow( 4, ( this.getInstalledUpgrades( Upgrades.PATTERN_EXPANSION ) ) ) );
}
@Override @Override
public boolean canInsert( final ItemStack stack ) public boolean canInsert( final ItemStack stack )
{ {
@@ -812,19 +856,26 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
throw new GridAccessException(); throw new GridAccessException();
} }
final IAEItemStack acquired = Platform.poweredExtraction( src, this.destination, itemStack, this.interfaceRequestSource ); IAEItemStack storedStack = this.gridProxy.getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ).getStorageList().findPrecise( itemStack );
if( acquired != null ) if( storedStack != null )
{ {
changed = true; if( storedStack.getStackSize() > 0 )
final ItemStack issue = adaptor.addItems( acquired.createItemStack() );
if( !issue.isEmpty() )
{ {
throw new IllegalStateException( "bad attempt at managing inventory. ( addItems )" ); final IAEItemStack acquired = Platform.poweredExtraction( src, this.destination, itemStack, this.interfaceRequestSource );
if( acquired != null )
{
changed = true;
final ItemStack issue = adaptor.addItems( acquired.createItemStack() );
if( !issue.isEmpty() )
{
throw new IllegalStateException( "bad attempt at managing inventory. ( addItems )" );
}
}
}
else if( storedStack.isCraftable() )
{
changed = this.handleCrafting( x, adaptor, itemStack ) || changed;
} }
}
else
{
changed = this.handleCrafting( x, adaptor, itemStack ) || changed;
} }
} }
else if( itemStack.getStackSize() < 0 ) else if( itemStack.getStackSize() < 0 )
@@ -936,7 +987,12 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
{ {
if( this.hasConfig() ) if( this.hasConfig() )
{ {
return (IMEMonitor<T>) new InterfaceInventory( this ); if( resetConfigCache )
{
resetConfigCache = false;
configCachedHandler = new InterfaceInventory( this );
}
return (IMEMonitor<T>) configCachedHandler;
} }
return (IMEMonitor<T>) this.items; return (IMEMonitor<T>) this.items;
@@ -1544,7 +1600,6 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
public InterfaceInventory( final DualityInterface tileInterface ) public InterfaceInventory( final DualityInterface tileInterface )
{ {
super( new AdaptorItemHandler( tileInterface.storage ) ); super( new AdaptorItemHandler( tileInterface.storage ) );
this.setActionSource( new MachineSource( DualityInterface.this.iHost ) );
} }
@Override @Override
+114 -46
View File
@@ -19,21 +19,18 @@
package appeng.helpers; package appeng.helpers;
import java.util.ArrayList; import java.util.*;
import java.util.HashMap; import java.util.stream.Collectors;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringJoiner;
import net.minecraft.inventory.InventoryCrafting; import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager; import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.IRecipe; import net.minecraft.item.crafting.IRecipe;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.NonNullList;
import net.minecraft.world.World; import net.minecraft.world.World;
import appeng.api.AEApi; import appeng.api.AEApi;
@@ -46,11 +43,17 @@ import appeng.core.AELog;
import appeng.core.features.AEFeature; import appeng.core.features.AEFeature;
import appeng.util.Platform; import appeng.util.Platform;
import appeng.util.item.AEItemStack; import appeng.util.item.AEItemStack;
import net.minecraftforge.common.crafting.IShapedRecipe;
public class PatternHelper implements ICraftingPatternDetails, Comparable<PatternHelper> 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 ItemStack patternItem;
private final InventoryCrafting crafting = new InventoryCrafting( new ContainerNull(), 3, 3 ); private final InventoryCrafting crafting = new InventoryCrafting( new ContainerNull(), 3, 3 );
private final InventoryCrafting testFrame = 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[] condensedOutputs;
private final IAEItemStack[] inputs; private final IAEItemStack[] inputs;
private final IAEItemStack[] outputs; private final IAEItemStack[] outputs;
private final Map<Integer, List<IAEItemStack>> substituteInputs;
private final boolean isCrafting; private final boolean isCrafting;
private final boolean canSubstitute; private final boolean canSubstitute;
private final Set<TestLookup> failCache = new HashSet<>(); private final Set<TestLookup> failCache = new HashSet<>();
@@ -143,9 +147,11 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable<Patter
} }
} }
} }
final int outputLength = out.size();
this.outputs = out.toArray( new IAEItemStack[out.size()] ); this.inputs = in.toArray(new IAEItemStack[ALL_INPUT_LIMIT]);
this.inputs = in.toArray( new IAEItemStack[in.size()] ); this.outputs = out.toArray(new IAEItemStack[outputLength]);
this.substituteInputs = new HashMap<>(ALL_INPUT_LIMIT);
final Map<IAEItemStack, IAEItemStack> tmpOutputs = new HashMap<>(); final Map<IAEItemStack, IAEItemStack> tmpOutputs = new HashMap<>();
@@ -257,6 +263,14 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable<Patter
this.testFrame.setInventorySlotContents( slotIndex, i ); 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 ) ) if( this.standardRecipe.matches( this.testFrame, w ) )
{ {
final ItemStack testOutput = this.standardRecipe.getCraftingResult( this.testFrame ); final ItemStack testOutput = this.standardRecipe.getCraftingResult( this.testFrame );
@@ -268,25 +282,6 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable<Patter
return true; 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 ); this.markItemAs( slotIndex, i, TestStatus.DECLINE );
return false; return false;
@@ -328,6 +323,97 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable<Patter
return this.canSubstitute; 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 @Override
public ItemStack getOutput( final InventoryCrafting craftingInv, final World w ) public ItemStack getOutput( final InventoryCrafting craftingInv, final World w )
{ {
@@ -406,24 +492,6 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable<Patter
return this.pattern.hashCode(); 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 @Override
public boolean equals( final Object obj ) public boolean equals( final Object obj )
{ {
+7 -12
View File
@@ -187,20 +187,15 @@ public class TickHandler
if( ev.type == Type.WORLD && ev.phase == Phase.END ) if( ev.type == Type.WORLD && ev.phase == Phase.END )
{ {
final WorldTickEvent wte = (WorldTickEvent) ev; final WorldTickEvent wte = (WorldTickEvent) ev;
synchronized( this.craftingJobs ) synchronized ( this.craftingJobs )
{ {
final Collection<CraftingJob> jobSet = this.craftingJobs.get( wte.world ); final Collection<CraftingJob> jobSet = this.craftingJobs.get( wte.world );
if( !jobSet.isEmpty() ) if (!jobSet.isEmpty()) {
{ final int jobSize = jobSet.size();
final Iterator<CraftingJob> i = jobSet.iterator(); final int microSecondsPerTick = AEConfig.instance().getCraftingCalculationTimePerTick() * 1000;
while( i.hasNext() ) final int simTime = Math.max(1, microSecondsPerTick / jobSize);
{
final CraftingJob cj = i.next(); jobSet.removeIf( cj -> !cj.simulateFor( simTime ) );
if( !cj.simulateFor() )
{
i.remove();
}
}
} }
} }
} }
@@ -147,8 +147,12 @@ class RecipeTransferHandler<T extends Container> implements IRecipeTransferHandl
} }
// prefer pure crystals. // prefer pure crystals.
for( ItemStack stack : ingredient.getAllIngredients() ) for ( ItemStack stack : ingredient.getAllIngredients() )
{ {
if( stack == null )
{
continue;
}
if( Platform.isRecipePrioritized( stack ) ) if( Platform.isRecipePrioritized( stack ) )
{ {
list.add( 0, 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(); final NBTTagCompound tag = new NBTTagCompound();
is.writeToNBT( tag ); is.writeToNBT( tag );
@@ -35,6 +35,8 @@ public enum TheOneProbeText
P2P_UNLINKED, P2P_UNLINKED,
P2P_INPUT_ONE_OUTPUT, P2P_INPUT_ONE_OUTPUT,
P2P_INPUT_MANY_OUTPUTS, P2P_INPUT_MANY_OUTPUTS,
P2P_OUTPUT_ONE_INPUT,
P2P_OUTPUT_MANY_INPUTS,
P2P_OUTPUT, P2P_OUTPUT,
P2P_FREQUENCY, P2P_FREQUENCY,
@@ -57,11 +57,11 @@ public class P2PStateInfoProvider implements IPartProbInfoProvider
// The default state // The default state
int state = STATE_UNLINKED; int state = STATE_UNLINKED;
int outputCount = 0; int outputCount = getOutputCount( tunnel );
int inputCount = getInputCount( tunnel );
if( !tunnel.isOutput() ) if( !tunnel.isOutput() )
{ {
outputCount = getOutputCount( tunnel );
if( outputCount > 0 ) if( outputCount > 0 )
{ {
// Only set it to INPUT if we know there are any outputs // Only set it to INPUT if we know there are any outputs
@@ -70,8 +70,7 @@ public class P2PStateInfoProvider implements IPartProbInfoProvider
} }
else else
{ {
final PartP2PTunnel input = tunnel.getInput(); if( inputCount > 0 )
if( input != null )
{ {
state = STATE_OUTPUT; state = STATE_OUTPUT;
} }
@@ -83,7 +82,7 @@ public class P2PStateInfoProvider implements IPartProbInfoProvider
probeInfo.text( TheOneProbeText.P2P_UNLINKED.getLocal() ); probeInfo.text( TheOneProbeText.P2P_UNLINKED.getLocal() );
break; break;
case STATE_OUTPUT: case STATE_OUTPUT:
probeInfo.text( TheOneProbeText.P2P_OUTPUT.getLocal() ); probeInfo.text( getInputText( inputCount ) );
break; break;
case STATE_INPUT: case STATE_INPUT:
probeInfo.text( getOutputText( outputCount ) ); probeInfo.text( getOutputText( outputCount ) );
@@ -110,6 +109,19 @@ public class P2PStateInfoProvider implements IPartProbInfoProvider
} }
} }
private static int getInputCount( PartP2PTunnel tunnel )
{
try
{
return Iterators.size( tunnel.getInputs().iterator() );
}
catch( GridAccessException e )
{
// Well... unknown size it is!
return 0;
}
}
private static String getOutputText( int outputs ) private static String getOutputText( int outputs )
{ {
if( outputs <= 1 ) if( outputs <= 1 )
@@ -122,4 +134,16 @@ public class P2PStateInfoProvider implements IPartProbInfoProvider
} }
} }
private static String getInputText( int inputs )
{
if( inputs <= 1 )
{
return TheOneProbeText.P2P_OUTPUT_ONE_INPUT.getLocal();
}
else
{
return String.format( TheOneProbeText.P2P_OUTPUT_MANY_INPUTS.getLocal(), inputs );
}
}
} }
@@ -21,6 +21,7 @@ package appeng.integration.modules.waila.part;
import java.util.List; import java.util.List;
import appeng.integration.modules.theoneprobe.TheOneProbeText;
import com.google.common.collect.Iterators; import com.google.common.collect.Iterators;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.EntityPlayerMP;
@@ -117,11 +118,11 @@ public final class P2PStateWailaDataProvider extends BasePartWailaDataProvider
// The default state // The default state
int state = STATE_UNLINKED; int state = STATE_UNLINKED;
int outputCount = 0; int outputCount = getOutputCount( tunnel );
int inputCount = getInputCount( tunnel );
if( !tunnel.isOutput() ) if( !tunnel.isOutput() )
{ {
outputCount = getOutputCount( tunnel );
if( outputCount > 0 ) if( outputCount > 0 )
{ {
// Only set it to INPUT if we know there are any outputs // Only set it to INPUT if we know there are any outputs
@@ -130,8 +131,7 @@ public final class P2PStateWailaDataProvider extends BasePartWailaDataProvider
} }
else else
{ {
PartP2PTunnel input = tunnel.getInput(); if( inputCount > 0 )
if( input != null )
{ {
state = STATE_OUTPUT; state = STATE_OUTPUT;
} }
@@ -160,15 +160,40 @@ public final class P2PStateWailaDataProvider extends BasePartWailaDataProvider
} }
} }
private static int getInputCount( PartP2PTunnel tunnel )
{
try
{
return Iterators.size( tunnel.getInputs().iterator() );
}
catch( GridAccessException e )
{
// Well... unknown size it is!
return 0;
}
}
private static String getOutputText( int outputs ) private static String getOutputText( int outputs )
{ {
if( outputs <= 1 ) if( outputs <= 1 )
{ {
return WailaText.P2PInputOneOutput.getLocal(); return WailaText.P2P_INPUT_ONE_OUTPUT.getLocal();
} }
else else
{ {
return String.format( WailaText.P2PInputManyOutputs.getLocal(), outputs ); return String.format( WailaText.P2P_INPUT_MANY_OUTPUTS.getLocal(), outputs );
}
}
private static String getInputText( int inputs )
{
if( inputs <= 1 )
{
return WailaText.P2P_OUTPUT_ONE_INPUT.getLocal();
}
else
{
return String.format( WailaText.P2P_OUTPUT_MANY_INPUTS.getLocal(), inputs );
} }
} }
@@ -19,6 +19,7 @@
package appeng.items.contents; package appeng.items.contents;
import appeng.api.networking.security.IActionSource;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
@@ -42,6 +43,8 @@ import appeng.me.helpers.MEMonitorHandler;
import appeng.util.ConfigManager; import appeng.util.ConfigManager;
import appeng.util.Platform; import appeng.util.Platform;
import java.util.Collections;
public class PortableCellViewer extends MEMonitorHandler<IAEItemStack> implements IPortableCell, IInventorySlotAware public class PortableCellViewer extends MEMonitorHandler<IAEItemStack> implements IPortableCell, IInventorySlotAware
{ {
@@ -83,6 +86,34 @@ public class PortableCellViewer extends MEMonitorHandler<IAEItemStack> implement
return usePowerMultiplier.divide( this.ips.extractAEPower( this.target, amt, Actionable.MODULATE ) ); return usePowerMultiplier.divide( this.ips.extractAEPower( this.target, amt, Actionable.MODULATE ) );
} }
@Override
public IAEItemStack injectItems( IAEItemStack input, Actionable mode, IActionSource src )
{
final long size = input.getStackSize();
final IAEItemStack injected = super.injectItems( input, mode, src );
if( mode == Actionable.MODULATE && ( injected == null || injected.getStackSize() != size ) )
{
this.notifyListenersOfChange( Collections.singletonList( input.copy().setStackSize( input.getStackSize() - ( injected == null ? 0 : injected.getStackSize() ) ) ), null);
}
return injected;
}
@Override
public IAEItemStack extractItems( IAEItemStack request, Actionable mode, IActionSource src )
{
final IAEItemStack extractable = super.extractItems( request, mode, src );
if( mode == Actionable.MODULATE && extractable != null )
{
this.notifyListenersOfChange( Collections.singletonList( request.copy().setStackSize( -extractable.getStackSize() ) ), null );
}
return extractable;
}
@Override @Override
public <T extends IAEStack<T>> IMEMonitor<T> getInventory( IStorageChannel<T> channel ) public <T extends IAEStack<T>> IMEMonitor<T> getInventory( IStorageChannel<T> channel )
{ {
@@ -164,6 +164,8 @@ public final class ItemMaterial extends AEBaseItem implements IStorageComponent,
return Upgrades.INVERTER; return Upgrades.INVERTER;
case CARD_CRAFTING: case CARD_CRAFTING:
return Upgrades.CRAFTING; return Upgrades.CRAFTING;
case CARD_PATTERN_EXPANSION:
return Upgrades.PATTERN_EXPANSION;
default: default:
return null; return null;
} }
@@ -118,7 +118,10 @@ public enum MaterialType
FLUID_CELL1K_PART( 54, "material_fluid_cell1k_part", EnumSet.of( AEFeature.STORAGE_CELLS ) ), FLUID_CELL1K_PART( 54, "material_fluid_cell1k_part", EnumSet.of( AEFeature.STORAGE_CELLS ) ),
FLUID_CELL4K_PART( 55, "material_fluid_cell4k_part", EnumSet.of( AEFeature.STORAGE_CELLS ) ), FLUID_CELL4K_PART( 55, "material_fluid_cell4k_part", EnumSet.of( AEFeature.STORAGE_CELLS ) ),
FLUID_CELL16K_PART( 56, "material_fluid_cell16k_part", EnumSet.of( AEFeature.STORAGE_CELLS ) ), FLUID_CELL16K_PART( 56, "material_fluid_cell16k_part", EnumSet.of( AEFeature.STORAGE_CELLS ) ),
FLUID_CELL64K_PART( 57, "material_fluid_cell64k_part", EnumSet.of( AEFeature.STORAGE_CELLS ) ); FLUID_CELL64K_PART( 57, "material_fluid_cell64k_part", EnumSet.of( AEFeature.STORAGE_CELLS ) ),
CARD_PATTERN_EXPANSION( 58, "material_card_pattern_expansion", EnumSet.of( AEFeature.ADVANCED_CARDS ) );
private final Set<AEFeature> features; private final Set<AEFeature> features;
private final ModelResourceLocation model; private final ModelResourceLocation model;
@@ -403,7 +403,7 @@ public class ToolMatterCannon extends AEBasePoweredItem implements IStorageCell<
} }
else if( pos.entityHit.attackEntityFrom( dmgSrc, dmg ) ) else if( pos.entityHit.attackEntityFrom( dmgSrc, dmg ) )
{ {
hasDestroyed = true; hasDestroyed = pos.entityHit.isEntityAlive();
} }
} }
else if( pos.typeOfHit == RayTraceResult.Type.BLOCK ) else if( pos.typeOfHit == RayTraceResult.Type.BLOCK )
+2 -2
View File
@@ -633,10 +633,10 @@ public class GridNode implements IGridNode, IPathItem
this.usedChannels = 0; this.usedChannels = 0;
} }
final int idx = this.connections.indexOf( fast ); final int idx = this.connections.indexOf( (IGridConnection) fast );
if( idx > 0 ) if( idx > 0 )
{ {
this.connections.remove( fast ); this.connections.remove( (IGridConnection) fast );
this.connections.add( 0, (IGridConnection) fast ); this.connections.add( 0, (IGridConnection) fast );
} }
} }
+61 -16
View File
@@ -30,7 +30,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Set; import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.Future; import java.util.concurrent.Future;
@@ -42,6 +41,7 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap; import com.google.common.collect.Multimap;
import it.unimi.dsi.fastutil.objects.*;
import net.minecraft.world.World; import net.minecraft.world.World;
import appeng.api.AEApi; import appeng.api.AEApi;
@@ -105,8 +105,8 @@ public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper
private final Set<ICraftingProvider> craftingProviders = new HashSet<>(); private final Set<ICraftingProvider> craftingProviders = new HashSet<>();
private final Map<IGridNode, ICraftingWatcher> craftingWatchers = new HashMap<>(); private final Map<IGridNode, ICraftingWatcher> craftingWatchers = new HashMap<>();
private final IGrid grid; private final IGrid grid;
private final Map<ICraftingPatternDetails, List<ICraftingMedium>> craftingMethods = new HashMap<>(); private final Object2ObjectMap<ICraftingPatternDetails, List<ICraftingMedium>> craftingMethods = new Object2ObjectOpenHashMap<>();
private final Map<IAEItemStack, ImmutableList<ICraftingPatternDetails>> craftableItems = new HashMap<>(); private final Object2ObjectMap<IAEItemStack, ImmutableList<ICraftingPatternDetails>> craftableItems = new Object2ObjectOpenHashMap<>();
private final Set<IAEItemStack> emitableItems = new HashSet<>(); private final Set<IAEItemStack> emitableItems = new HashSet<>();
private final Map<String, CraftingLinkNexus> craftingLinks = new HashMap<>(); private final Map<String, CraftingLinkNexus> craftingLinks = new HashMap<>();
private final Multimap<IAEStack, CraftingWatcher> interests = HashMultimap.create(); private final Multimap<IAEStack, CraftingWatcher> interests = HashMultimap.create();
@@ -160,11 +160,11 @@ public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper
{ {
if( machine instanceof ICraftingWatcherHost ) if( machine instanceof ICraftingWatcherHost )
{ {
final ICraftingWatcher craftingWatcher = this.craftingWatchers.get( machine ); final ICraftingWatcher craftingWatcher = this.craftingWatchers.get( gridNode );
if( craftingWatcher != null ) if( craftingWatcher != null )
{ {
craftingWatcher.reset(); craftingWatcher.reset();
this.craftingWatchers.remove( machine ); this.craftingWatchers.remove( gridNode );
} }
} }
@@ -270,24 +270,21 @@ public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper
return; return;
} }
final Map<IAEItemStack, ImmutableList<ICraftingPatternDetails>> oldItems = this.craftableItems; final Object2ObjectMap<IAEItemStack, ImmutableList<ICraftingPatternDetails>> oldItems = new Object2ObjectOpenHashMap<>(this.craftableItems);
final Set<IAEItemStack> oldEmitableItems = new HashSet<>(this.emitableItems);
// erase list. // erase list.
this.craftingMethods.clear(); this.craftingMethods.clear();
this.craftableItems.clear(); this.craftableItems.clear();
this.emitableItems.clear(); this.emitableItems.clear();
// update the stuff that was in the list...
this.storageGrid.postAlterationOfStoredItems( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ), oldItems.keySet(),
new BaseActionSource() );
// re-create list.. // re-create list..
for( final ICraftingProvider provider : this.craftingProviders ) for( final ICraftingProvider provider : this.craftingProviders )
{ {
provider.provideCrafting( this ); provider.provideCrafting( this );
} }
final Map<IAEItemStack, Set<ICraftingPatternDetails>> tmpCraft = new HashMap<>(); final Object2ObjectMap<IAEItemStack, ObjectSet<ICraftingPatternDetails>> tmpCraft = new Object2ObjectOpenHashMap<>();
// new craftables! // new craftables!
for( final ICraftingPatternDetails details : this.craftingMethods.keySet() ) for( final ICraftingPatternDetails details : this.craftingMethods.keySet() )
@@ -298,11 +295,11 @@ public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper
out.reset(); out.reset();
out.setCraftable( true ); out.setCraftable( true );
Set<ICraftingPatternDetails> methods = tmpCraft.get( out ); ObjectSet<ICraftingPatternDetails> methods = tmpCraft.get( out );
if( methods == null ) if( methods == null )
{ {
tmpCraft.put( out, methods = new TreeSet<>( COMPARATOR ) ); tmpCraft.put( out, methods = new ObjectRBTreeSet<>( COMPARATOR ) );
} }
methods.add( details ); methods.add( details );
@@ -310,12 +307,56 @@ public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper
} }
// make them immutable // make them immutable
for( final Entry<IAEItemStack, Set<ICraftingPatternDetails>> e : tmpCraft.entrySet() ) for( final Entry<IAEItemStack, ObjectSet<ICraftingPatternDetails>> e : tmpCraft.entrySet() )
{ {
this.craftableItems.put( e.getKey(), ImmutableList.copyOf( e.getValue() ) ); this.craftableItems.put( e.getKey(), ImmutableList.copyOf( e.getValue() ) );
} }
this.storageGrid.postAlterationOfStoredItems( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ), this.craftableItems.keySet(), Object2ObjectMap<IAEItemStack, ImmutableList<ICraftingPatternDetails>> craftablesChanged = new Object2ObjectArrayMap<>();
ObjectSet<Entry<IAEItemStack, ImmutableList<ICraftingPatternDetails>>> i = oldItems.entrySet();
for ( Entry<IAEItemStack, ImmutableList<ICraftingPatternDetails>> ais : i) {
if (!this.craftableItems.containsKey( ais.getKey() )) {
IAEItemStack changedStack = ais.getKey().copy();
changedStack.reset();
changedStack.setCraftable( false );
craftablesChanged.put( changedStack, ais.getValue() );
}
}
ObjectSet<Entry<IAEItemStack, ImmutableList<ICraftingPatternDetails>>> j = this.craftableItems.entrySet();
for ( Entry<IAEItemStack, ImmutableList<ICraftingPatternDetails>> ais : j) {
if (!oldItems.containsKey( ais )){
IAEItemStack changedStack = ais.getKey().copy();
changedStack.reset();
changedStack.setCraftable( true );
craftablesChanged.put( changedStack, ais.getValue() );
}
}
for( final IAEItemStack st : oldEmitableItems )
{
if( !emitableItems.contains( st ) )
{
IAEItemStack changedStack = st.copy();
changedStack.reset();
changedStack.setCraftable( false );
craftablesChanged.put( changedStack, null );
}
}
for( final IAEItemStack st : this.emitableItems )
{
if( !oldEmitableItems.contains( st ) )
{
IAEItemStack changedStack = st.copy();
changedStack.reset();
changedStack.setCraftable( true );
craftablesChanged.put( changedStack, null );
}
}
this.storageGrid.postCraftablesChanges( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ), craftablesChanged.keySet(),
new BaseActionSource() ); new BaseActionSource() );
} }
@@ -635,7 +676,11 @@ public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper
public boolean hasCpu( final ICraftingCPU cpu ) public boolean hasCpu( final ICraftingCPU cpu )
{ {
return this.craftingCPUClusters.contains( cpu ); if (cpu instanceof CraftingCPUCluster)
{
return this.craftingCPUClusters.contains( (CraftingCPUCluster) cpu );
}
return false;
} }
public GenericInterestManager<CraftingWatcher> getInterestManager() public GenericInterestManager<CraftingWatcher> getInterestManager()
+177 -41
View File
@@ -30,6 +30,7 @@ import java.util.PriorityQueue;
import java.util.Queue; import java.util.Queue;
import java.util.Set; import java.util.Set;
import com.google.common.base.Preconditions;
import com.google.common.collect.HashMultiset; import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset; import com.google.common.collect.Multiset;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
@@ -63,12 +64,10 @@ import appeng.me.energy.EnergyWatcher;
public class EnergyGridCache implements IEnergyGrid public class EnergyGridCache implements IEnergyGrid
{ {
private static final double MAX_BUFFER_STORAGE = 200; private static final double MAX_BUFFER_STORAGE = 800;
private static final Comparator<IEnergyGridProvider> COMPARATOR_HIGHEST_AMOUNT_STORED_FIRST = ( o1, o2 ) -> Double.compare( o2.getProviderStoredEnergy(), private static final Comparator<IEnergyGridProvider> COMPARATOR_HIGHEST_AMOUNT_STORED_FIRST = ( o1, o2 ) -> Double.compare( o2.getProviderStoredEnergy(), o1.getProviderStoredEnergy() );
o1.getProviderStoredEnergy() );
private static final Comparator<IEnergyGridProvider> COMPARATOR_LOWEST_PERCENTAGE_FIRST = ( o1, o2 ) -> private static final Comparator<IEnergyGridProvider> COMPARATOR_LOWEST_PERCENTAGE_FIRST = ( o1, o2 ) -> {
{
final double percent1 = ( o1.getProviderStoredEnergy() + 1 ) / ( o1.getProviderMaxEnergy() + 1 ); final double percent1 = ( o1.getProviderStoredEnergy() + 1 ) / ( o1.getProviderMaxEnergy() + 1 );
final double percent2 = ( o2.getProviderStoredEnergy() + 1 ) / ( o2.getProviderMaxEnergy() + 1 ); final double percent2 = ( o2.getProviderStoredEnergy() + 1 ) / ( o2.getProviderMaxEnergy() + 1 );
@@ -76,9 +75,24 @@ public class EnergyGridCache implements IEnergyGrid
}; };
private final NavigableSet<EnergyThreshold> interests = Sets.newTreeSet(); private final NavigableSet<EnergyThreshold> interests = Sets.newTreeSet();
// Should only be modified from the add/remove methods below to guard against
// concurrent modifications
private final double averageLength = 40.0; private final double averageLength = 40.0;
private final Set<IAEPowerStorage> providers = new LinkedHashSet<>(); private final Set<IAEPowerStorage> providers = new LinkedHashSet<>();
// Used to track whether an extraction is currently in progress, to fail fast
// when something externally
// modifies the energy grid.
private boolean ongoingExtractOperation = false;
// Should only be modified from the add/remove methods below to guard against
// concurrent modifications
private final Set<IAEPowerStorage> requesters = new LinkedHashSet<>(); private final Set<IAEPowerStorage> requesters = new LinkedHashSet<>();
// Used to track whether an injection is currently in progress, to fail fast
// when something externally
// modifies the energy grid.
private boolean ongoingInjectOperation = false;
private final Multiset<IEnergyGridProvider> energyGridProviders = HashMultiset.create(); private final Multiset<IEnergyGridProvider> energyGridProviders = HashMultiset.create();
private final IGrid myGrid; private final IGrid myGrid;
private final HashMap<IGridNode, IEnergyWatcher> watchers = new HashMap<>(); private final HashMap<IGridNode, IEnergyWatcher> watchers = new HashMap<>();
@@ -110,6 +124,10 @@ public class EnergyGridCache implements IEnergyGrid
private double lastStoredPower = -1; private double lastStoredPower = -1;
private final GridPowerStorage localStorage = new GridPowerStorage(); private final GridPowerStorage localStorage = new GridPowerStorage();
private Set<IAEPowerStorage> providerToRemove = new HashSet<>();
private Set<IAEPowerStorage> requesterToRemove = new HashSet<>();
private Set<IAEPowerStorage> providersToAdd = new HashSet<>();
private Set<IAEPowerStorage> requesterToAdd = new HashSet<>();
public EnergyGridCache( final IGrid g ) public EnergyGridCache( final IGrid g )
{ {
@@ -143,20 +161,33 @@ public class EnergyGridCache implements IEnergyGrid
{ {
if( ev.storage.isAEPublicPowerStorage() ) if( ev.storage.isAEPublicPowerStorage() )
{ {
switch( ev.type ) if( ev.type == PowerEventType.PROVIDE_POWER )
{ {
case PROVIDE_POWER: if( ev.storage.getPowerFlow() != AccessRestriction.WRITE )
if( ev.storage.getPowerFlow() != AccessRestriction.WRITE ) {
if( !ongoingExtractOperation )
{ {
this.providers.add( ev.storage ); addProvider( ev.storage );
} }
break; else
case REQUEST_POWER:
if( ev.storage.getPowerFlow() != AccessRestriction.READ )
{ {
this.requesters.add( ev.storage ); this.providersToAdd.add( ev.storage );
} }
break; }
}
else if( ev.type == PowerEventType.REQUEST_POWER )
{
if( ev.storage.getPowerFlow() != AccessRestriction.READ )
{
if( !ongoingInjectOperation )
{
addRequester( ev.storage );
}
else
{
this.requesterToAdd.add( ev.storage );
}
}
} }
} }
else else
@@ -301,19 +332,56 @@ public class EnergyGridCache implements IEnergyGrid
{ {
double extractedPower = 0; double extractedPower = 0;
this.providers.addAll( providersToAdd );
providersToAdd.clear();
providers.removeIf( providerToRemove::contains );
this.providerToRemove.clear();
final Iterator<IAEPowerStorage> it = this.providers.iterator(); final Iterator<IAEPowerStorage> it = this.providers.iterator();
while( extractedPower < amt && it.hasNext() ) ongoingExtractOperation = true;
boolean ls = false;
try
{ {
final IAEPowerStorage node = it.next(); while ( extractedPower < amt && it.hasNext() )
final double req = amt - extractedPower;
final double newPower = node.extractAEPower( req, mode, PowerMultiplier.ONE );
extractedPower += newPower;
if( newPower < req && mode == Actionable.MODULATE )
{ {
it.remove(); final IAEPowerStorage node = it.next();
if( node != null )
{
if( node == localStorage && mode == Actionable.MODULATE )
{
ls = true;
continue;
}
final double req = amt - extractedPower;
final double newPower = node.extractAEPower( req, mode, PowerMultiplier.ONE );
extractedPower += newPower;
if( newPower < req && mode == Actionable.MODULATE )
{
it.remove();
}
}
else
{
it.remove();
}
}
} finally
{
ongoingExtractOperation = false;
if( ls && extractedPower < amt )
{
final double req = amt - extractedPower;
final double newPower = localStorage.extractAEPower( req, mode, PowerMultiplier.ONE );
extractedPower += newPower;
if( newPower < req )
{
providers.remove( localStorage );
}
} }
} }
@@ -338,17 +406,37 @@ public class EnergyGridCache implements IEnergyGrid
{ {
final double originalAmount = amt; final double originalAmount = amt;
this.requesters.addAll( requesterToAdd );
requesterToAdd.clear();
requesters.removeIf( requesterToRemove::contains );
this.requesterToRemove.clear();
final Iterator<IAEPowerStorage> it = this.requesters.iterator(); final Iterator<IAEPowerStorage> it = this.requesters.iterator();
while( amt > 0 && it.hasNext() ) ongoingInjectOperation = true;
try
{ {
final IAEPowerStorage node = it.next(); while ( amt > 0 && it.hasNext() )
amt = node.injectAEPower( amt, mode );
if( amt > 0 && mode == Actionable.MODULATE )
{ {
it.remove(); final IAEPowerStorage node = it.next();
if( node != null )
{
amt = node.injectAEPower( amt, mode );
if( amt > 0 && mode == Actionable.MODULATE )
{
it.remove();
}
}
else
{
it.remove();
}
} }
} finally
{
ongoingInjectOperation = false;
} }
final double overflow = Math.max( 0.0, amt ); final double overflow = Math.max( 0.0, amt );
@@ -367,7 +455,7 @@ public class EnergyGridCache implements IEnergyGrid
double required = 0; double required = 0;
final Iterator<IAEPowerStorage> it = this.requesters.iterator(); final Iterator<IAEPowerStorage> it = this.requesters.iterator();
while( required < maxRequired && it.hasNext() ) while ( required < maxRequired && it.hasNext() )
{ {
final IAEPowerStorage node = it.next(); final IAEPowerStorage node = it.next();
if( node.getPowerFlow() != AccessRestriction.READ ) if( node.getPowerFlow() != AccessRestriction.READ )
@@ -428,11 +516,7 @@ public class EnergyGridCache implements IEnergyGrid
@Override @Override
public double getStoredPower() public double getStoredPower()
{ {
if( this.availableTicksSinceUpdate > 90 ) this.refreshPower();
{
this.refreshPower();
}
return Math.max( 0.0, this.globalAvailablePower ); return Math.max( 0.0, this.globalAvailablePower );
} }
@@ -505,9 +589,22 @@ public class EnergyGridCache implements IEnergyGrid
this.globalMaxPower -= ps.getAEMaxPower(); this.globalMaxPower -= ps.getAEMaxPower();
this.globalAvailablePower -= ps.getAECurrentPower(); this.globalAvailablePower -= ps.getAECurrentPower();
} }
if( !ongoingExtractOperation )
this.providers.remove( ps ); {
this.requesters.remove( ps ); removeProvider( ps );
}
else
{
this.providerToRemove.add( ps );
}
if( !ongoingInjectOperation )
{
removeRequester( ps );
}
else
{
this.requesterToRemove.add( ps );
}
} }
} }
@@ -523,6 +620,31 @@ public class EnergyGridCache implements IEnergyGrid
} }
} }
private void addRequester( IAEPowerStorage requester )
{
Preconditions.checkState( !ongoingInjectOperation, "Cannot modify energy requesters while energy is being injected." );
this.requesters.add( requester );
}
private void removeRequester( IAEPowerStorage requester )
{
Preconditions.checkState( !ongoingInjectOperation, "Cannot modify energy requesters while energy is being injected." );
this.requesters.remove( requester );
}
private void addProvider( IAEPowerStorage provider )
{
Preconditions.checkState( !ongoingExtractOperation, "Cannot modify energy providers while energy is being extracted." );
this.providers.add( provider );
}
private void removeProvider( IAEPowerStorage provider )
{
Preconditions.checkState( !ongoingExtractOperation, "Cannot modify energy providers while energy is being extracted." );
this.providers.remove( provider );
}
@Override @Override
public void addNode( final IGridNode node, final IGridHost machine ) public void addNode( final IGridNode node, final IGridHost machine )
{ {
@@ -554,12 +676,26 @@ public class EnergyGridCache implements IEnergyGrid
if( current > 0 && ps.getPowerFlow() != AccessRestriction.WRITE ) if( current > 0 && ps.getPowerFlow() != AccessRestriction.WRITE )
{ {
this.globalAvailablePower += current; this.globalAvailablePower += current;
this.providers.add( ps ); if( !ongoingExtractOperation )
{
addProvider( ps );
}
else
{
this.providersToAdd.add( ps );
}
} }
if( current < max && ps.getPowerFlow() != AccessRestriction.READ ) if( current < max && ps.getPowerFlow() != AccessRestriction.READ )
{ {
this.requesters.add( ps ); if( !ongoingInjectOperation )
{
addRequester( ps );
}
else
{
this.requesterToAdd.add( ps );
}
} }
} }
} }
@@ -686,4 +822,4 @@ public class EnergyGridCache implements IEnergyGrid
} }
} }
} }
} }
+15 -8
View File
@@ -94,19 +94,19 @@ public class GridStorageCache implements IStorageGrid
this.removeCellProvider( cc, tracker ); this.removeCellProvider( cc, tracker );
this.inactiveCellProviders.remove( cc ); this.inactiveCellProviders.remove( cc );
this.getGrid().postEvent( new MENetworkCellArrayUpdate() ); cellUpdate( null );
tracker.applyChanges(); tracker.applyChanges();
} }
if( machine instanceof IStackWatcherHost ) if( machine instanceof IStackWatcherHost )
{ {
final IStackWatcher myWatcher = this.watchers.get( machine ); final IStackWatcher myWatcher = this.watchers.get( node );
if( myWatcher != null ) if( myWatcher != null )
{ {
myWatcher.reset(); myWatcher.reset();
this.watchers.remove( machine ); this.watchers.remove( node );
} }
} }
} }
@@ -119,7 +119,7 @@ public class GridStorageCache implements IStorageGrid
final ICellContainer cc = (ICellContainer) machine; final ICellContainer cc = (ICellContainer) machine;
this.inactiveCellProviders.add( cc ); this.inactiveCellProviders.add( cc );
this.getGrid().postEvent( new MENetworkCellArrayUpdate() ); cellUpdate( null );
if( node.isActive() ) if( node.isActive() )
{ {
@@ -170,7 +170,7 @@ public class GridStorageCache implements IStorageGrid
private CellChangeTracker addCellProvider( final ICellProvider cc, final CellChangeTracker tracker ) private CellChangeTracker addCellProvider( final ICellProvider cc, final CellChangeTracker tracker )
{ {
if( this.inactiveCellProviders.contains( cc ) ) if( this.inactiveCellProviders.contains( cc ) && !this.activeCellProviders.contains( cc ))
{ {
this.inactiveCellProviders.remove( cc ); this.inactiveCellProviders.remove( cc );
this.activeCellProviders.add( cc ); this.activeCellProviders.add( cc );
@@ -248,8 +248,6 @@ public class GridStorageCache implements IStorageGrid
} }
} }
this.storageMonitors.forEach( ( channel, monitor ) -> monitor.forceUpdate() );
tracker.applyChanges(); tracker.applyChanges();
} }
@@ -281,6 +279,12 @@ public class GridStorageCache implements IStorageGrid
this.storageMonitors.get( chan ).postChange( true, (Iterable) input, src ); this.storageMonitors.get( chan ).postChange( true, (Iterable) input, src );
} }
@Override
public void postCraftablesChanges( IStorageChannel<?> chan, Iterable<? extends IAEStack<?>> input, IActionSource src )
{
this.storageMonitors.get( chan ).updateCraftables( (Iterable) input, src );
}
@Override @Override
public void registerCellProvider( final ICellProvider provider ) public void registerCellProvider( final ICellProvider provider )
{ {
@@ -324,7 +328,10 @@ public class GridStorageCache implements IStorageGrid
public void applyChanges() public void applyChanges()
{ {
GridStorageCache.this.postChangesToNetwork( this.channel, this.up_or_down, this.list, this.src ); if( !this.list.isEmpty() )
{
GridStorageCache.this.postChangesToNetwork( this.channel, this.up_or_down, this.list, this.src );
}
} }
} }
+141 -96
View File
@@ -19,20 +19,10 @@
package appeng.me.cache; package appeng.me.cache;
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.Nonnegative;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import appeng.api.AEApi;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Queues;
import appeng.api.config.AccessRestriction; import appeng.api.config.AccessRestriction;
import appeng.api.config.Actionable; import appeng.api.config.Actionable;
import appeng.api.networking.events.MENetworkStorageEvent; import appeng.api.networking.events.MENetworkStorageEvent;
@@ -41,17 +31,26 @@ import appeng.api.storage.IMEInventoryHandler;
import appeng.api.storage.IMEMonitor; import appeng.api.storage.IMEMonitor;
import appeng.api.storage.IMEMonitorHandlerReceiver; import appeng.api.storage.IMEMonitorHandlerReceiver;
import appeng.api.storage.IStorageChannel; import appeng.api.storage.IStorageChannel;
import appeng.api.storage.channels.IFluidStorageChannel;
import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IAEStack;
import appeng.api.storage.data.IItemList; import appeng.api.storage.data.IItemList;
import appeng.me.storage.ItemWatcher; import appeng.me.storage.ItemWatcher;
import com.google.common.collect.Queues;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import java.util.*;
import java.util.Map.Entry;
public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T> public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
{ {
@Nonnull @Nonnull
private static final Deque<NetworkMonitor<?>> GLOBAL_DEPTH = Queues.newArrayDeque(); private static final Set<NetworkMonitor<?>> NESTED_MONITORS = new HashSet<>();
private static final HashMap<IActionSource, Set<NetworkMonitor<?>>> sourceSetHashMap = new HashMap<>();
protected static boolean nested = false;
protected boolean isNested = false;
@Nonnull @Nonnull
private final GridStorageCache myGridCache; private final GridStorageCache myGridCache;
@@ -63,9 +62,11 @@ public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
private final Object2ObjectMap<IMEMonitorHandlerReceiver<T>, Object> listeners; private final Object2ObjectMap<IMEMonitorHandlerReceiver<T>, Object> listeners;
private boolean sendEvent = false; private boolean sendEvent = false;
private boolean hasChanged = false; private boolean forceUpdate = false;
@Nonnegative @Nonnegative
private int localDepthSemaphore = 0; private int localDepthSemaphore = 0;
private long gridItemCount;
private long gridFluidCount;
public NetworkMonitor( final GridStorageCache cache, final IStorageChannel<T> chan ) public NetworkMonitor( final GridStorageCache cache, final IStorageChannel<T> chan )
{ {
@@ -90,21 +91,7 @@ public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
@Override @Override
public T extractItems( final T request, final Actionable mode, final IActionSource src ) public T extractItems( final T request, final Actionable mode, final IActionSource src )
{ {
if( mode == Actionable.SIMULATE ) return this.getHandler().extractItems( request, mode, src );
{
return this.getHandler().extractItems( request, mode, src );
}
this.localDepthSemaphore++;
final T leftover = this.getHandler().extractItems( request, mode, src );
this.localDepthSemaphore--;
if( this.localDepthSemaphore == 0 )
{
this.monitorDifference( request.copy(), leftover, true, src );
}
return leftover;
} }
@Override @Override
@@ -137,38 +124,42 @@ public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
return this.getHandler().getSlot(); 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 void incGridCurrentCount( long count )
{
if( myChannel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) )
{
gridItemCount += count;
}
else if( myChannel == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) )
{
gridFluidCount += count;
}
}
@Nonnull @Nonnull
@Override @Override
public IItemList<T> getStorageList() public IItemList<T> getStorageList()
{ {
if( hasChanged )
{
hasChanged = false;
this.cachedList.resetStatus();
return this.getAvailableItems( this.cachedList );
}
return this.cachedList; return this.cachedList;
} }
@Override @Override
public T injectItems( final T input, final Actionable mode, final IActionSource src ) public T injectItems( final T input, final Actionable mode, final IActionSource src )
{ {
if( mode == Actionable.SIMULATE ) return this.getHandler().injectItems( input, mode, src );
{
return this.getHandler().injectItems( input, mode, src );
}
this.localDepthSemaphore++;
final T leftover = this.getHandler().injectItems( input, mode, src );
this.localDepthSemaphore--;
if( this.localDepthSemaphore == 0 )
{
this.monitorDifference( input.copy(), leftover, false, src );
}
return leftover;
} }
@Override @Override
@@ -200,36 +191,15 @@ public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
return this.listeners.entrySet().iterator(); return this.listeners.entrySet().iterator();
} }
private T monitorDifference( final IAEStack<T> original, final T leftOvers, final boolean extraction, final IActionSource src )
{
final T diff = original.copy();
if( extraction )
{
diff.setStackSize( leftOvers == null ? 0 : -leftOvers.getStackSize() );
}
else if( leftOvers != null )
{
diff.decStackSize( leftOvers.getStackSize() );
}
if( diff.getStackSize() != 0 )
{
this.postChangesToListeners( ImmutableList.of( diff ), src );
}
return leftOvers;
}
private void notifyListenersOfChange( final Iterable<T> diff, final IActionSource src ) private void notifyListenersOfChange( final Iterable<T> diff, final IActionSource src )
{ {
this.hasChanged = true;
final Iterator<Entry<IMEMonitorHandlerReceiver<T>, Object>> i = this.getListeners(); final Iterator<Entry<IMEMonitorHandlerReceiver<T>, Object>> i = this.getListeners();
while( i.hasNext() ) while( i.hasNext() )
{ {
final Entry<IMEMonitorHandlerReceiver<T>, Object> o = i.next(); final Entry<IMEMonitorHandlerReceiver<T>, Object> o = i.next();
final IMEMonitorHandlerReceiver<T> receiver = o.getKey(); final IMEMonitorHandlerReceiver<T> receiver = o.getKey();
if( receiver.isValid( o.getValue() ) ) if( receiver.isValid( o.getValue() ) )
{ {
receiver.postChange( this, diff, src ); receiver.postChange( this, diff, src );
@@ -241,46 +211,60 @@ public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
} }
} }
private void postChangesToListeners( final Iterable<T> changes, final IActionSource src ) protected void updateCraftables( Iterable<T> input, IActionSource src )
{ {
this.postChange( true, changes, src ); for( final T changedItem : input )
{
if (changedItem.isCraftable()) {
this.cachedList.add( changedItem );
}
else
{
T i = this.cachedList.findPrecise( changedItem );
if (i != null)
i.setCraftable( false );
}
}
} }
protected void postChange( final boolean add, final Iterable<T> changes, final IActionSource src ) protected void postChange( final boolean add, final Iterable<T> changes, final IActionSource src )
{ {
if( this.localDepthSemaphore > 0 || GLOBAL_DEPTH.contains( this ) )
if( sourceSetHashMap.get( src ) != null && sourceSetHashMap.get( src ).contains( this ) )
{ {
NESTED_MONITORS.add( this );
nested = true;
return; return;
} }
GLOBAL_DEPTH.push( this ); sourceSetHashMap.putIfAbsent( src, new HashSet<>() );
this.localDepthSemaphore++; sourceSetHashMap.get( src ).add( this );
this.sendEvent = true; this.sendEvent = true;
this.notifyListenersOfChange( changes, src ); for( final T change : changes )
for( final T changedItem : changes )
{ {
T difference = changedItem; //T change = changed;
if( !add && change != null )
if( !add && changedItem != null )
{ {
difference = changedItem.copy(); //change = changed.copy();
difference.setStackSize( -changedItem.getStackSize() ); change.setStackSize( -change.getStackSize() );
} }
if( this.myGridCache.getInterestManager().containsKey( changedItem ) ) incGridCurrentCount( change.getStackSize() );
this.cachedList.addStorage( change );
if( this.myGridCache.getInterestManager().containsKey( change ) )
{ {
final Collection<ItemWatcher> list = this.myGridCache.getInterestManager().get( changedItem ); final Collection<ItemWatcher> list = this.myGridCache.getInterestManager().get( change );
if( !list.isEmpty() ) if( !list.isEmpty() )
{ {
IAEStack<T> fullStack = this.getStorageList().findPrecise( changedItem ); IAEStack<T> fullStack = this.getStorageList().findPrecise( change );
if( fullStack == null ) if( fullStack == null )
{ {
fullStack = changedItem.copy(); fullStack = change.copy();
fullStack.setStackSize( 0 ); fullStack.setStackSize( 0 );
} }
@@ -288,7 +272,7 @@ public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
for( final ItemWatcher iw : list ) for( final ItemWatcher iw : list )
{ {
iw.getHost().onStackChange( this.getStorageList(), fullStack, difference, src, this.getChannel() ); iw.getHost().onStackChange( this.getStorageList(), fullStack, change, src, this.getChannel() );
} }
this.myGridCache.getInterestManager().disableTransactions(); this.myGridCache.getInterestManager().disableTransactions();
@@ -296,21 +280,82 @@ public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
} }
} }
final NetworkMonitor<?> last = GLOBAL_DEPTH.pop(); this.notifyListenersOfChange( changes, src );
this.localDepthSemaphore--;
if( last != this ) sourceSetHashMap.get( src ).remove( this );
if( sourceSetHashMap.get( src ).isEmpty() )
{ {
throw new IllegalStateException( "Invalid Access to Networked Storage API detected." ); sourceSetHashMap.remove( src );
}
if( sourceSetHashMap.isEmpty() )
{
for( NetworkMonitor<?> nm : NESTED_MONITORS )
{
nm.setupForceUpdate();
}
nested = false;
NESTED_MONITORS.clear();
}
}
void setupForceUpdate()
{
if( nested != isNested )
{
isNested = nested;
forceUpdate();
} }
} }
void forceUpdate() void forceUpdate()
{ {
this.hasChanged = true; forceUpdate = false;
this.cachedList.resetStatus();
this.getAvailableItems( this.cachedList );
long count = 0;
for( T stack : this.cachedList )
{
count += stack.getStackSize();
if( this.myGridCache.getInterestManager().containsKey( stack ) )
{
final Collection<ItemWatcher> list = this.myGridCache.getInterestManager().get( stack );
if( !list.isEmpty() )
{
IAEStack<T> fullStack = this.getStorageList().findPrecise( stack );
if( fullStack == null )
{
fullStack = stack.copy();
fullStack.setStackSize( 0 );
}
this.myGridCache.getInterestManager().enableTransactions();
for ( final ItemWatcher iw : list )
{
iw.getHost().onStackChange( this.getStorageList(), fullStack, stack, null, this.getChannel() );
}
this.myGridCache.getInterestManager().disableTransactions();
}
}
}
if( myChannel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) )
{
gridItemCount = count;
}
else if( myChannel == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) )
{
gridFluidCount = count;
}
final Iterator<Entry<IMEMonitorHandlerReceiver<T>, Object>> i = this.getListeners(); final Iterator<Entry<IMEMonitorHandlerReceiver<T>, Object>> i = this.getListeners();
while( i.hasNext() ) while ( i.hasNext() )
{ {
final Entry<IMEMonitorHandlerReceiver<T>, Object> o = i.next(); final Entry<IMEMonitorHandlerReceiver<T>, Object> o = i.next();
final IMEMonitorHandlerReceiver<T> receiver = o.getKey(); final IMEMonitorHandlerReceiver<T> receiver = o.getKey();
+56 -17
View File
@@ -19,7 +19,7 @@
package appeng.me.cache; package appeng.me.cache;
import java.util.HashMap; import java.util.Collection;
import java.util.Random; import java.util.Random;
import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.LinkedHashMultimap;
@@ -46,7 +46,7 @@ public class P2PCache implements IGridCache
private static final TunnelCollection<PartP2PTunnel> NULL_COLLECTION = new TunnelCollection<PartP2PTunnel>( null, null ); private static final TunnelCollection<PartP2PTunnel> NULL_COLLECTION = new TunnelCollection<PartP2PTunnel>( null, null );
private final IGrid myGrid; private final IGrid myGrid;
private final HashMap<Short, PartP2PTunnel> inputs = new HashMap<>(); private final Multimap<Short, PartP2PTunnel> inputs = LinkedHashMultimap.create();
private final Multimap<Short, PartP2PTunnel> outputs = LinkedHashMultimap.create(); private final Multimap<Short, PartP2PTunnel> outputs = LinkedHashMultimap.create();
private final Random frequencyGenerator; private final Random frequencyGenerator;
@@ -110,10 +110,19 @@ public class P2PCache implements IGridCache
} }
else else
{ {
this.inputs.remove( t.getFrequency() ); this.inputs.remove( t.getFrequency(), t );
} }
this.updateTunnel( t.getFrequency(), !t.isOutput(), false ); if( this.inputs.get( t.getFrequency() ).isEmpty() )
{
this.inputs.removeAll( t.getFrequency() );
}
if( this.outputs.get( t.getFrequency() ).isEmpty() )
{
this.outputs.removeAll( t.getFrequency() );
}
this.updateTunnel( t.getFrequency(), t.isOutput(), false );
} }
} }
@@ -142,7 +151,7 @@ public class P2PCache implements IGridCache
this.inputs.put( t.getFrequency(), t ); this.inputs.put( t.getFrequency(), t );
} }
this.updateTunnel( t.getFrequency(), !t.isOutput(), false ); this.updateTunnel( t.getFrequency(), t.isOutput(), false );
} }
} }
@@ -164,6 +173,20 @@ public class P2PCache implements IGridCache
} }
public void removeTunnel( final PartP2PTunnel t, short freq )
{
this.outputs.remove( freq, t );
this.inputs.remove( freq, t );
if( this.inputs.get( t.getFrequency() ).isEmpty() )
{
this.inputs.removeAll( t.getFrequency() );
}
if( this.outputs.get( t.getFrequency() ).isEmpty() )
{
this.outputs.removeAll( t.getFrequency() );
}
}
private void updateTunnel( final short freq, final boolean updateOutputs, final boolean configChange ) private void updateTunnel( final short freq, final boolean updateOutputs, final boolean configChange )
{ {
for( final PartP2PTunnel p : this.outputs.get( freq ) ) for( final PartP2PTunnel p : this.outputs.get( freq ) )
@@ -175,8 +198,7 @@ public class P2PCache implements IGridCache
p.onTunnelNetworkChange(); p.onTunnelNetworkChange();
} }
final PartP2PTunnel in = this.inputs.get( freq ); for( final PartP2PTunnel in : this.inputs.get( freq ) )
if( in != null )
{ {
if( configChange ) if( configChange )
{ {
@@ -195,7 +217,7 @@ public class P2PCache implements IGridCache
if( this.inputs.containsValue( t ) ) if( this.inputs.containsValue( t ) )
{ {
this.inputs.remove( t.getFrequency() ); this.inputs.remove( t.getFrequency(), t );
} }
t.setFrequency( newFrequency ); t.setFrequency( newFrequency );
@@ -211,7 +233,6 @@ public class P2PCache implements IGridCache
// AELog.info( "update-" + (t.output ? "output: " : "input: ") + t.freq ); // AELog.info( "update-" + (t.output ? "output: " : "input: ") + t.freq );
this.updateTunnel( t.getFrequency(), t.isOutput(), true ); this.updateTunnel( t.getFrequency(), t.isOutput(), true );
this.updateTunnel( t.getFrequency(), !t.isOutput(), true );
} }
public short newFrequency() public short newFrequency()
@@ -236,25 +257,43 @@ public class P2PCache implements IGridCache
public TunnelCollection<PartP2PTunnel> getOutputs( final short freq, final Class<? extends PartP2PTunnel> c ) public TunnelCollection<PartP2PTunnel> getOutputs( final short freq, final Class<? extends PartP2PTunnel> c )
{ {
final PartP2PTunnel in = this.inputs.get( freq ); Collection<PartP2PTunnel> in = this.inputs.get( freq );
if( in == null ) if( in == null )
{ {
return NULL_COLLECTION; return NULL_COLLECTION;
} }
final TunnelCollection<PartP2PTunnel> out = this.inputs.get( freq ).getCollection( this.outputs.get( freq ), c ); TunnelCollection<PartP2PTunnel> out;
for( PartP2PTunnel part : this.inputs.get( freq ) )
{
out = part.getCollection( this.outputs.get( freq ), c );
if( out != null )
{
return out;
}
}
return NULL_COLLECTION;
}
public TunnelCollection<PartP2PTunnel> getInputs( final short freq, final Class<? extends PartP2PTunnel> c )
{
Collection<PartP2PTunnel> out = this.outputs.get( freq );
if( out == null ) if( out == null )
{ {
return NULL_COLLECTION; return NULL_COLLECTION;
} }
return out; TunnelCollection<PartP2PTunnel> in;
} for( PartP2PTunnel part : this.outputs.get( freq ) )
{
public PartP2PTunnel getInput( final short freq ) in = part.getCollection( this.inputs.get( freq ), c );
{ if( in != null )
return this.inputs.get( freq ); {
return in;
}
}
return NULL_COLLECTION;
} }
} }
+1 -1
View File
@@ -314,7 +314,7 @@ public class PathGridCache implements IPathingGrid
int depth = 0; int depth = 0;
for( final IGridNode nodes : this.requireChannels ) for( final IGridNode nodes : this.requireChannels )
{ {
if( !this.semiOpen.contains( nodes ) ) if( !this.semiOpen.contains( (IPathItem) nodes ) )
{ {
final IGridBlock gb = nodes.getGridBlock(); final IGridBlock gb = nodes.getGridBlock();
final EnumSet<GridFlags> flags = gb.getFlags(); final EnumSet<GridFlags> flags = gb.getFlags();
-1
View File
@@ -138,7 +138,6 @@ public class TickManagerCache implements ITickManager
tt.addEntityCrashInfo( crashreportcategory ); tt.addEntityCrashInfo( crashreportcategory );
throw new ReportedException( crashreport ); throw new ReportedException( crashreport );
} }
PartLevelEmitter.wipeCache();
} }
private void addToQueue( final TickTracker tt ) private void addToQueue( final TickTracker tt )
@@ -23,6 +23,9 @@ import java.util.*;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import appeng.api.config.Upgrades;
import appeng.helpers.DualityInterface;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import net.minecraft.inventory.InventoryCrafting; import net.minecraft.inventory.InventoryCrafting;
@@ -233,8 +236,9 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
public IAEItemStack injectItems( final IAEItemStack input, final Actionable type, final IActionSource src ) public IAEItemStack injectItems( final IAEItemStack input, final Actionable type, final IActionSource src )
{ {
if( !( input instanceof IAEItemStack ) ) // 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) {
return input; return input;
} }
@@ -292,7 +296,7 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
{ {
is.decStackSize( what.getStackSize() ); is.decStackSize( what.getStackSize() );
this.updateElapsedTime( what ); this.updateRemainingItemCount( what );
this.markDirty(); this.markDirty();
this.postCraftingStatusChange( what.copy().setStackSize( -what.getStackSize() ) ); this.postCraftingStatusChange( what.copy().setStackSize( -what.getStackSize() ) );
@@ -431,6 +435,11 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
AELog.crafting( LOG_MARK_AS_COMPLETE, logStack ); AELog.crafting( LOG_MARK_AS_COMPLETE, logStack );
} }
// Waiting for can potentially contain items at this point, if the user has a 64xplank->64xbutton processing
// recipe for example, but only requested 1xbutton. We just ignore the rest since it will be dumped
// back into the network inventory regardless. For this to work it's important that injectItems in this CPU
// does not accept any further items if isComplete is true.
this.waitingFor.resetStatus();
this.remainingItemCount = 0; this.remainingItemCount = 0;
this.startItemCount = 0; this.startItemCount = 0;
this.lastTime = 0; this.lastTime = 0;
@@ -485,22 +494,87 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
return null; 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; 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 = fuzz.copy();
fuzz.setStackSize( g.getStackSize() ); fuzz.setStackSize( g.getStackSize() );
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() == g.getStackSize()) if( ais != null && ais.getStackSize() >= g.getStackSize() )
{ {
found = true; found = true;
break; break;
@@ -517,15 +591,7 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
return false; 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; return true;
@@ -680,71 +746,67 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
ic = new InventoryCrafting( new ContainerNull(), 3, 3 ); ic = new InventoryCrafting( new ContainerNull(), 3, 3 );
boolean found = false; boolean found = false;
for( int x = 0; x < input.length; x++ ) for (int x = 0; x < input.length; x++) {
{ if (input[x] != null) {
if( input[x] != null )
{
found = false; found = false;
if( details.isCraftable() ) if (details.isCraftable()) {
{
final Collection<IAEItemStack> itemList; final Collection<IAEItemStack> itemList;
if( details.canSubstitute() ) if (details.canSubstitute()) {
{ final List<IAEItemStack> substitutes = details.getSubstituteInputs(x);
itemList = this.inventory.getItemList().findFuzzy( input[x], FuzzyMode.IGNORE_ALL ); itemList = new ArrayList<>(substitutes.size());
}
else
{
itemList = new ArrayList<>( 1 );
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 ) final IAEItemStack item = this.inventory.getItemList()
{ .findPrecise(input[x]);
itemList.add( item );
if (item != null) {
itemList.add(item);
} }
} }
for( IAEItemStack fuzz : itemList ) for (IAEItemStack fuzz : itemList) {
{
fuzz = fuzz.copy(); fuzz = fuzz.copy();
fuzz.setStackSize( input[x].getStackSize() ); fuzz.setStackSize(input[x].getStackSize());
if( details.isValidItemForSlot( x, fuzz.createItemStack(), this.getWorld() ) ) if (details.isValidItemForSlot(x, fuzz.createItemStack(),
{ this.getWorld())) {
final IAEItemStack ais = this.inventory.extractItems( fuzz, Actionable.MODULATE, this.machineSrc ); final IAEItemStack ais = this.inventory.extractItems(fuzz,
final ItemStack is = ais == null ? ItemStack.EMPTY : ais.createItemStack(); Actionable.MODULATE, this.machineSrc);
final ItemStack is = ais == null ? ItemStack.EMPTY
: ais.createItemStack();
if( !is.isEmpty() ) if (!is.isEmpty()) {
{ this.postChange(AEItemStack.fromItemStack(is), this.machineSrc);
this.postChange( AEItemStack.fromItemStack( is ), this.machineSrc ); ic.setInventorySlotContents(x, is);
ic.setInventorySlotContents( x, is );
found = true; found = true;
break; break;
} }
} }
} }
} } else {
else final IAEItemStack ais = this.inventory.extractItems(input[x].copy(),
{ Actionable.MODULATE, this.machineSrc);
final IAEItemStack ais = this.inventory.extractItems( input[x].copy(), Actionable.MODULATE, this.machineSrc );
final ItemStack is = ais == null ? ItemStack.EMPTY : ais.createItemStack(); final ItemStack is = ais == null ? ItemStack.EMPTY : ais.createItemStack();
if( !is.isEmpty() ) if (!is.isEmpty()) {
{ this.postChange(input[x], this.machineSrc);
this.postChange( input[x], this.machineSrc ); ic.setInventorySlotContents(x, is);
ic.setInventorySlotContents( x, is ); if (is.getCount() == input[x].getStackSize()) {
if( is.getCount() == input[x].getStackSize() )
{
found = true; found = true;
continue; continue;
} }
} }
} }
if( !found ) if (!found) {
{
break; break;
} }
} }
@@ -828,6 +890,7 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
private void storeItems() private void storeItems()
{ {
Preconditions.checkState(isComplete, "CPU should be complete to prevent re-insertion when dumping items");
final IGrid g = this.getGrid(); final IGrid g = this.getGrid();
if( g == null ) if( g == null )
@@ -838,23 +901,24 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
final IStorageGrid sg = g.getCache( IStorageGrid.class ); final IStorageGrid sg = g.getCache( IStorageGrid.class );
final IMEInventory<IAEItemStack> ii = sg.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); final IMEInventory<IAEItemStack> ii = sg.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) );
for( IAEItemStack is : this.inventory.getItemList() ) IItemList<IAEItemStack> itemList = this.inventory.getItemList();
for( IAEItemStack is : itemList )
{ {
is = this.inventory.extractItems( is.copy(), Actionable.MODULATE, this.machineSrc ); this.postChange( is, this.machineSrc );
IAEItemStack remainder = ii.injectItems( is.copy(), Actionable.MODULATE, this.machineSrc );
if( is != null ) // The network was unable to receive all of the items, i.e. no or not enough storage space left
if( remainder != null )
{ {
this.postChange( is, this.machineSrc ); is.setStackSize( remainder.getStackSize() );
is = ii.injectItems( is, Actionable.MODULATE, this.machineSrc );
} }
else
if( is != null )
{ {
this.inventory.injectItems( is, Actionable.MODULATE, this.machineSrc ); is.reset();
} }
} }
if( this.inventory.getItemList().isEmpty() ) if( itemList.isEmpty() )
{ {
this.inventory = new MECraftingInventory(); this.inventory = new MECraftingInventory();
} }
@@ -939,14 +1003,13 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
@Override @Override
public boolean isBusy() public boolean isBusy()
{ {
final Iterator<Entry<ICraftingPatternDetails, TaskProgress>> i = this.tasks.entrySet().iterator();
while( i.hasNext() ) this.tasks.entrySet().removeIf(
taskProgressEntry -> taskProgressEntry.getValue().value <= 0 );
if( !this.waitingFor.isEmpty() || !this.tasks.isEmpty() )
{ {
if( i.next().getValue().value <= 0 ) this.updateElapsedTime();
{
i.remove();
}
} }
return !this.tasks.isEmpty() || !this.waitingFor.isEmpty(); return !this.tasks.isEmpty() || !this.waitingFor.isEmpty();
@@ -1338,12 +1401,16 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
this.remainingItemCount = itemCount; this.remainingItemCount = itemCount;
} }
private void updateElapsedTime( final IAEItemStack is ) private void updateRemainingItemCount( final IAEItemStack is )
{
this.remainingItemCount = this.getRemainingItemCount() - is.getStackSize();
}
private void updateElapsedTime()
{ {
final long nextStartTime = System.nanoTime(); final long nextStartTime = System.nanoTime();
this.elapsedTime = this.getElapsedTime() + nextStartTime - this.lastTime; this.elapsedTime = this.getElapsedTime() + nextStartTime - this.lastTime;
this.lastTime = nextStartTime; this.lastTime = nextStartTime;
this.remainingItemCount = this.getRemainingItemCount() - is.getStackSize();
} }
public long getElapsedTime() public long getElapsedTime()
@@ -123,4 +123,4 @@ public class GenericInterestManager<T>
this.iw = watcher; this.iw = watcher;
} }
} }
} }
@@ -28,8 +28,6 @@ import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map.Entry; import java.util.Map.Entry;
import com.google.common.collect.ImmutableList;
import appeng.api.config.AccessRestriction; import appeng.api.config.AccessRestriction;
import appeng.api.config.Actionable; import appeng.api.config.Actionable;
import appeng.api.networking.security.IActionSource; import appeng.api.networking.security.IActionSource;
@@ -85,11 +83,7 @@ public class MEMonitorHandler<T extends IAEStack<T>> implements IMEMonitor<T>
@Override @Override
public T injectItems( final T input, final Actionable mode, final IActionSource src ) public T injectItems( final T input, final Actionable mode, final IActionSource src )
{ {
if( mode == Actionable.SIMULATE ) return this.getHandler().injectItems( input, mode, src );
{
return this.getHandler().injectItems( input, mode, src );
}
return this.monitorDifference( input.copy(), this.getHandler().injectItems( input, mode, src ), false, src );
} }
protected IMEInventoryHandler<T> getHandler() protected IMEInventoryHandler<T> getHandler()
@@ -97,28 +91,7 @@ public class MEMonitorHandler<T extends IAEStack<T>> implements IMEMonitor<T>
return this.internalHandler; return this.internalHandler;
} }
private T monitorDifference( final T original, final T leftOvers, final boolean extraction, final IActionSource src ) public void postChangesToListeners( final Iterable<T> changes, final IActionSource src )
{
final T diff = original.copy();
if( extraction )
{
diff.setStackSize( leftOvers == null ? 0 : -leftOvers.getStackSize() );
}
else if( leftOvers != null )
{
diff.decStackSize( leftOvers.getStackSize() );
}
if( diff.getStackSize() != 0 )
{
this.postChangesToListeners( ImmutableList.of( diff ), src );
}
return leftOvers;
}
protected void postChangesToListeners( final Iterable<T> changes, final IActionSource src )
{ {
this.notifyListenersOfChange( changes, src ); this.notifyListenersOfChange( changes, src );
} }
@@ -150,11 +123,7 @@ public class MEMonitorHandler<T extends IAEStack<T>> implements IMEMonitor<T>
@Override @Override
public T extractItems( final T request, final Actionable mode, final IActionSource src ) public T extractItems( final T request, final Actionable mode, final IActionSource src )
{ {
if( mode == Actionable.SIMULATE ) return this.getHandler().extractItems( request, mode, src );
{
return this.getHandler().extractItems( request, mode, src );
}
return this.monitorDifference( request.copy(), this.getHandler().extractItems( request, mode, src ), true, src );
} }
@Override @Override
@@ -19,6 +19,7 @@
package appeng.me.helpers; package appeng.me.helpers;
import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
@@ -55,4 +56,24 @@ public class MachineSource implements IActionSource
return Optional.empty(); return Optional.empty();
} }
@Override
public boolean equals( Object o )
{
if( this == o )
{
return true;
}
if( o == null || getClass() != o.getClass() )
{
return false;
}
MachineSource that = (MachineSource) o;
return via.equals( that.via );
}
@Override
public int hashCode()
{
return Objects.hash( via );
}
} }
@@ -151,7 +151,7 @@ public abstract class AbstractCellInventory<T extends IAEStack<T>> implements IC
} }
// clean any old crusty stuff... // clean any old crusty stuff...
for( ; x < oldStoredItems && x < this.maxItemTypes; x++ ) for( ; x >= oldStoredItems && x < this.maxItemTypes; x++ )
{ {
this.tagCompound.removeTag( ITEM_SLOT_KEYS[x] ); this.tagCompound.removeTag( ITEM_SLOT_KEYS[x] );
this.tagCompound.removeTag( ITEM_SLOT_COUNT_KEYS[x] ); this.tagCompound.removeTag( ITEM_SLOT_COUNT_KEYS[x] );
@@ -277,6 +277,7 @@ public class BasicCellInventory<T extends IAEStack<T>> extends AbstractCellInven
} }
t.setStackSize( stackSize ); t.setStackSize( stackSize );
t.setCraftable( false );
if( stackSize > 0 ) if( stackSize > 0 )
{ {
@@ -19,15 +19,20 @@
package appeng.me.storage; package appeng.me.storage;
import appeng.core.features.registries.cell.CreativeCellHandler;
import appeng.me.GridAccessException;
import appeng.me.helpers.MachineSource;
import appeng.tile.storage.TileDrive;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import appeng.api.config.Actionable; import appeng.api.config.Actionable;
import appeng.api.implementations.tiles.IChestOrDrive;
import appeng.api.networking.security.IActionSource; import appeng.api.networking.security.IActionSource;
import appeng.api.storage.ICellHandler; import appeng.api.storage.ICellHandler;
import appeng.api.storage.ICellInventoryHandler; import appeng.api.storage.ICellInventoryHandler;
import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IAEStack;
import java.util.Collections;
public class DriveWatcher<T extends IAEStack<T>> extends MEInventoryHandler<T> public class DriveWatcher<T extends IAEStack<T>> extends MEInventoryHandler<T>
{ {
@@ -35,14 +40,16 @@ public class DriveWatcher<T extends IAEStack<T>> extends MEInventoryHandler<T>
private int oldStatus = 0; private int oldStatus = 0;
private final ItemStack is; private final ItemStack is;
private final ICellHandler handler; private final ICellHandler handler;
private final IChestOrDrive cord; private final TileDrive drive;
private IActionSource source;
public DriveWatcher( final ICellInventoryHandler<T> i, final ItemStack is, final ICellHandler han, final IChestOrDrive cod ) public DriveWatcher( final ICellInventoryHandler<T> i, final ItemStack is, final ICellHandler han, final TileDrive drive )
{ {
super( i, i.getChannel() ); super( i, i.getChannel() );
this.is = is; this.is = is;
this.handler = han; this.handler = han;
this.cord = cod; this.drive = drive;
this.source = new MachineSource( drive );
} }
public int getStatus() public int getStatus()
@@ -55,38 +62,58 @@ public class DriveWatcher<T extends IAEStack<T>> extends MEInventoryHandler<T>
{ {
final long size = input.getStackSize(); final long size = input.getStackSize();
final T a = super.injectItems( input, type, src ); final T remainder = super.injectItems( input, type, src );
if( type == Actionable.MODULATE && ( a == null || a.getStackSize() != size ) ) if( type == Actionable.MODULATE && ( remainder == null || remainder.getStackSize() != size ) )
{ {
final int newStatus = this.getStatus(); final int newStatus = this.getStatus();
if( newStatus != this.oldStatus ) if( newStatus != this.oldStatus )
{ {
this.cord.blinkCell( this.getSlot() ); this.drive.blinkCell( this.getSlot() );
this.oldStatus = newStatus; this.oldStatus = newStatus;
} }
if (this.drive.getProxy().isActive() && !(handler instanceof CreativeCellHandler))
{
try
{
this.drive.getProxy().getStorage().postAlterationOfStoredItems( this.getChannel(), Collections.singletonList( input.copy().setStackSize( input.getStackSize() - ( remainder == null ? 0 : remainder.getStackSize() ) ) ), this.source );
} catch ( GridAccessException e )
{
e.printStackTrace();
}
}
} }
return a; return remainder;
} }
@Override @Override
public T extractItems( final T request, final Actionable type, final IActionSource src ) public T extractItems( final T request, final Actionable type, final IActionSource src )
{ {
final T a = super.extractItems( request, type, src ); final T extractable = super.extractItems( request, type, src );
if( type == Actionable.MODULATE && a != null ) if( type == Actionable.MODULATE && extractable != null )
{ {
final int newStatus = this.getStatus(); final int newStatus = this.getStatus();
if( newStatus != this.oldStatus ) if( newStatus != this.oldStatus )
{ {
this.cord.blinkCell( this.getSlot() ); this.drive.blinkCell( this.getSlot() );
this.oldStatus = newStatus; this.oldStatus = newStatus;
} }
if (this.drive.getProxy().isActive() && !(handler instanceof CreativeCellHandler ))
{
try
{
this.drive.getProxy().getStorage().postAlterationOfStoredItems( this.getChannel(), Collections.singletonList( request.copy().setStackSize( -extractable.getStackSize() ) ), this.source );
} catch ( GridAccessException e )
{
e.printStackTrace();
}
}
} }
return a; return extractable;
} }
} }
@@ -19,14 +19,11 @@
package appeng.me.storage; package appeng.me.storage;
import java.util.ArrayList; import java.util.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ConcurrentSkipListMap;
import appeng.fluids.util.AEFluidStack;
import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.fluids.capability.IFluidHandler;
import net.minecraftforge.fluids.capability.IFluidTankProperties; import net.minecraftforge.fluids.capability.IFluidTankProperties;
@@ -48,16 +45,14 @@ import appeng.api.storage.data.IItemList;
public class MEMonitorIFluidHandler implements IMEMonitor<IAEFluidStack>, ITickingMonitor public class MEMonitorIFluidHandler implements IMEMonitor<IAEFluidStack>, ITickingMonitor
{ {
private final IFluidHandler handler; private final IFluidHandler handler;
private final IItemList<IAEFluidStack> list = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ).createList(); private IItemList<IAEFluidStack> cache = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ).createList();
private final HashMap<IMEMonitorHandlerReceiver<IAEFluidStack>, Object> listeners = new HashMap<>(); private final HashMap<IMEMonitorHandlerReceiver<IAEFluidStack>, Object> listeners = new HashMap<>();
private final NavigableMap<Integer, CachedFluidStack> memory;
private IActionSource mySource; private IActionSource mySource;
private StorageFilter mode = StorageFilter.EXTRACTABLE_ONLY; private StorageFilter mode = StorageFilter.EXTRACTABLE_ONLY;
public MEMonitorIFluidHandler( final IFluidHandler handler ) public MEMonitorIFluidHandler( final IFluidHandler handler )
{ {
this.handler = handler; this.handler = handler;
this.memory = new ConcurrentSkipListMap<>();
} }
@Override @Override
@@ -82,11 +77,6 @@ public class MEMonitorIFluidHandler implements IMEMonitor<IAEFluidStack>, ITicki
return input.copy(); return input.copy();
} }
if( type == Actionable.MODULATE )
{
this.onTick();
}
if( filled == input.getStackSize() ) if( filled == input.getStackSize() )
{ {
return null; return null;
@@ -94,6 +84,15 @@ public class MEMonitorIFluidHandler implements IMEMonitor<IAEFluidStack>, ITicki
final IAEFluidStack o = input.copy(); final IAEFluidStack o = input.copy();
o.setStackSize( input.getStackSize() - filled ); o.setStackSize( input.getStackSize() - filled );
if( type == Actionable.MODULATE )
{
IAEFluidStack added = o.copy();
this.cache.add( added );
this.postDifference( Collections.singletonList( added ) );
this.onTick();
}
return o; return o;
} }
@@ -107,13 +106,18 @@ public class MEMonitorIFluidHandler implements IMEMonitor<IAEFluidStack>, ITicki
return null; return null;
} }
if( type == Actionable.MODULATE )
{
this.onTick();
}
final IAEFluidStack o = request.copy(); final IAEFluidStack o = request.copy();
o.setStackSize( removed.amount ); o.setStackSize( removed.amount );
if( type == Actionable.MODULATE )
{
IAEFluidStack cachedStack = this.cache.findPrecise( request );
if( cachedStack != null )
{
cachedStack.decStackSize( o.getStackSize() );
this.postDifference( Collections.singletonList( o.copy().setStackSize( -o.getStackSize() ) ) );
}
}
return o; return o;
} }
@@ -126,111 +130,51 @@ public class MEMonitorIFluidHandler implements IMEMonitor<IAEFluidStack>, ITicki
@Override @Override
public TickRateModulation onTick() public TickRateModulation onTick()
{ {
final List<IAEFluidStack> changes = new ArrayList<>();
this.list.resetStatus();
int high = 0;
boolean changed = false; boolean changed = false;
final IFluidTankProperties[] props = this.handler.getTankProperties(); final List<IAEFluidStack> changes = new ArrayList<>();
for( int slot = 0; slot < this.handler.getTankProperties().length; ++slot ) final IFluidTankProperties[] tankProperties = this.handler.getTankProperties();
IItemList<IAEFluidStack> currentlyOnStorage = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ).createList();
for( IFluidTankProperties tankProperty : tankProperties )
{ {
final CachedFluidStack old = this.memory.get( slot ); if( this.mode == StorageFilter.EXTRACTABLE_ONLY && this.handler.drain( 1, false ) == null )
high = Math.max( high, slot );
final FluidStack newIS = !props[slot].canDrain() && this.getMode() == StorageFilter.EXTRACTABLE_ONLY ? null : props[slot].getContents();
final FluidStack oldIS = old == null ? null : old.fluidStack;
if( isDifferent( newIS, oldIS ) )
{ {
final CachedFluidStack cis = new CachedFluidStack( newIS ); continue;
this.memory.put( slot, cis );
if( old != null && old.aeStack != null )
{
old.aeStack.setStackSize( -old.aeStack.getStackSize() );
changes.add( old.aeStack );
}
if( cis.aeStack != null )
{
changes.add( cis.aeStack );
this.list.add( cis.aeStack );
}
changed = true;
} }
else currentlyOnStorage.add( AEFluidStack.fromFluidStack( tankProperty.getContents() ) );
}
for( final IAEFluidStack is : cache )
{
is.setStackSize( -is.getStackSize() );
}
for( final IAEFluidStack is : currentlyOnStorage )
{
cache.add( is );
}
for( final IAEFluidStack is : cache )
{
if( is.getStackSize() != 0 )
{ {
final int newSize = newIS == null ? 0 : newIS.amount; changes.add( is );
final int diff = newSize - ( oldIS == null ? 0 : oldIS.amount );
IAEFluidStack stack = null;
if( newIS != null )
{
stack = ( old == null || old.aeStack == null ? AEApi.instance()
.storage()
.getStorageChannel( IFluidStorageChannel.class )
.createStack( newIS ) : old.aeStack.copy() );
}
if( stack != null )
{
stack.setStackSize( newSize );
this.list.add( stack );
}
if( diff != 0 && stack != null )
{
final CachedFluidStack cis = new CachedFluidStack( newIS );
this.memory.put( slot, cis );
final IAEFluidStack a = stack.copy();
a.setStackSize( diff );
changes.add( a );
changed = true;
}
} }
} }
// detect dropped items; should fix non IISided Inventory Changes. cache = currentlyOnStorage;
final NavigableMap<Integer, CachedFluidStack> end = this.memory.tailMap( high, false );
if( !end.isEmpty() )
{
for( final CachedFluidStack cis : end.values() )
{
if( cis != null && cis.aeStack != null )
{
final IAEFluidStack a = cis.aeStack.copy();
a.setStackSize( -a.getStackSize() );
changes.add( a );
changed = true;
}
}
end.clear();
}
if( !changes.isEmpty() ) if( !changes.isEmpty() )
{ {
this.postDifference( changes ); this.postDifference( changes );
changed = true;
} }
return changed ? TickRateModulation.URGENT : TickRateModulation.SLOWER; return changed ? TickRateModulation.URGENT : TickRateModulation.SLOWER;
} }
private static boolean isDifferent( FluidStack a, FluidStack b )
{
if( a == b )
{
return false;
}
if( a == null || b == null )
{
return true;
}
return !a.getFluid().equals( b.getFluid() );
}
private void postDifference( final Iterable<IAEFluidStack> a ) private void postDifference( final Iterable<IAEFluidStack> a )
{ {
if( a != null ) if( a != null )
@@ -291,9 +235,9 @@ public class MEMonitorIFluidHandler implements IMEMonitor<IAEFluidStack>, ITicki
@Override @Override
public IItemList<IAEFluidStack> getAvailableItems( final IItemList out ) public IItemList<IAEFluidStack> getAvailableItems( final IItemList out )
{ {
for( final CachedFluidStack is : this.memory.values() ) for( final IAEFluidStack fs : cache )
{ {
out.addStorage( is.aeStack ); out.addStorage( fs );
} }
return out; return out;
@@ -302,7 +246,7 @@ public class MEMonitorIFluidHandler implements IMEMonitor<IAEFluidStack>, ITicki
@Override @Override
public IItemList<IAEFluidStack> getStorageList() public IItemList<IAEFluidStack> getStorageList()
{ {
return this.list; return this.cache;
} }
private StorageFilter getMode() private StorageFilter getMode()
@@ -326,24 +270,4 @@ public class MEMonitorIFluidHandler implements IMEMonitor<IAEFluidStack>, ITicki
this.mySource = mySource; this.mySource = mySource;
} }
private static class CachedFluidStack
{
private final FluidStack fluidStack;
private final IAEFluidStack aeStack;
CachedFluidStack( final FluidStack is )
{
if( is == null )
{
this.fluidStack = null;
this.aeStack = null;
}
else
{
this.fluidStack = is.copy();
this.aeStack = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ).createStack( is );
}
}
}
} }
@@ -19,12 +19,8 @@
package appeng.me.storage; package appeng.me.storage;
import java.util.ArrayList; import java.util.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ConcurrentSkipListMap;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
@@ -50,16 +46,15 @@ public class MEMonitorIInventory implements IMEMonitor<IAEItemStack>, ITickingMo
{ {
private final InventoryAdaptor adaptor; private final InventoryAdaptor adaptor;
private final IItemList<IAEItemStack> list = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); private IItemList<IAEItemStack> cache = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList();
private final HashMap<IMEMonitorHandlerReceiver<IAEItemStack>, Object> listeners = new HashMap<>(); private final HashMap<IMEMonitorHandlerReceiver<IAEItemStack>, Object> listeners = new HashMap<>();
private final NavigableMap<Integer, CachedItemStack> memory;
private IActionSource mySource; private IActionSource mySource;
private StorageFilter mode = StorageFilter.EXTRACTABLE_ONLY; private StorageFilter mode = StorageFilter.EXTRACTABLE_ONLY;
public MEMonitorIInventory( final InventoryAdaptor adaptor ) public MEMonitorIInventory( final InventoryAdaptor adaptor )
{ {
this.adaptor = adaptor; this.adaptor = adaptor;
this.memory = new ConcurrentSkipListMap<>();
} }
@Override @Override
@@ -88,11 +83,6 @@ public class MEMonitorIInventory implements IMEMonitor<IAEItemStack>, ITickingMo
out = this.adaptor.addItems( input.createItemStack() ); out = this.adaptor.addItems( input.createItemStack() );
} }
if( type == Actionable.MODULATE )
{
this.onTick();
}
if( out.isEmpty() ) if( out.isEmpty() )
{ {
return null; return null;
@@ -101,6 +91,15 @@ public class MEMonitorIInventory implements IMEMonitor<IAEItemStack>, ITickingMo
// better then doing construction from scratch :3 // better then doing construction from scratch :3
final IAEItemStack o = input.copy(); final IAEItemStack o = input.copy();
o.setStackSize( out.getCount() ); o.setStackSize( out.getCount() );
if( type == Actionable.MODULATE )
{
IAEItemStack added = o.copy();
this.cache.add( added );
this.postDifference( Collections.singletonList( added ) );
this.onTick();
}
return o; return o;
} }
@@ -129,6 +128,12 @@ public class MEMonitorIInventory implements IMEMonitor<IAEItemStack>, ITickingMo
if( type == Actionable.MODULATE ) if( type == Actionable.MODULATE )
{ {
IAEItemStack cachedStack = this.cache.findPrecise( request );
if( cachedStack != null )
{
cachedStack.decStackSize( o.getStackSize() );
this.postDifference( Collections.singletonList( o.copy().setStackSize( -o.getStackSize() ) ) );
}
this.onTick(); this.onTick();
} }
@@ -144,110 +149,52 @@ public class MEMonitorIInventory implements IMEMonitor<IAEItemStack>, ITickingMo
@Override @Override
public TickRateModulation onTick() public TickRateModulation onTick()
{ {
boolean changed = false;
final List<IAEItemStack> changes = new ArrayList<>(); final List<IAEItemStack> changes = new ArrayList<>();
this.list.resetStatus(); IItemList<IAEItemStack> currentlyOnStorage = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList();
int high = 0;
boolean changed = false; for( final ItemSlot is : adaptor )
for( final ItemSlot is : this.adaptor )
{ {
final CachedItemStack old = this.memory.get( is.getSlot() ); if( this.mode == StorageFilter.EXTRACTABLE_ONLY && !is.isExtractable() )
high = Math.max( high, is.getSlot() );
final ItemStack newIS = !is.isExtractable() && this.getMode() == StorageFilter.EXTRACTABLE_ONLY ? ItemStack.EMPTY : is.getItemStack();
final ItemStack oldIS = old == null ? ItemStack.EMPTY : old.itemStack;
if( this.isDifferent( newIS, oldIS ) )
{ {
final CachedItemStack cis = new CachedItemStack( is.getItemStack() ); continue;
this.memory.put( is.getSlot(), cis );
if( old != null && old.aeStack != null )
{
old.aeStack.setStackSize( -old.aeStack.getStackSize() );
changes.add( old.aeStack );
}
if( cis.aeStack != null )
{
changes.add( cis.aeStack );
this.list.add( cis.aeStack );
}
changed = true;
} }
else currentlyOnStorage.add( is.getAEItemStack() );
}
for( final IAEItemStack is : cache )
{
is.setStackSize( -is.getStackSize() );
}
for( final IAEItemStack is : currentlyOnStorage )
{
cache.add( is );
}
for( final IAEItemStack is : cache )
{
if( is.getStackSize() != 0 )
{ {
final int newSize = ( newIS.isEmpty() ? 0 : newIS.getCount() ); changes.add( is );
final int diff = newSize - ( oldIS.isEmpty() ? 0 : oldIS.getCount() );
final IAEItemStack stack = ( old == null || old.aeStack == null ? AEApi.instance()
.storage()
.getStorageChannel( IItemStorageChannel.class )
.createStack( newIS ) : old.aeStack.copy() );
if( stack != null )
{
stack.setStackSize( newSize );
this.list.add( stack );
}
if( diff != 0 && stack != null )
{
final CachedItemStack cis = new CachedItemStack( is.getItemStack() );
this.memory.put( is.getSlot(), cis );
final IAEItemStack a = stack.copy();
a.setStackSize( diff );
changes.add( a );
changed = true;
}
} }
} }
// detect dropped items; should fix non IISided Inventory Changes. cache = currentlyOnStorage;
final NavigableMap<Integer, CachedItemStack> end = this.memory.tailMap( high, false );
if( !end.isEmpty() )
{
for( final CachedItemStack cis : end.values() )
{
if( cis != null && cis.aeStack != null )
{
final IAEItemStack a = cis.aeStack.copy();
a.setStackSize( -a.getStackSize() );
changes.add( a );
changed = true;
}
}
end.clear();
}
if( !changes.isEmpty() ) if( !changes.isEmpty() )
{ {
this.postDifference( changes ); this.postDifference( changes );
changed = true;
} }
return changed ? TickRateModulation.URGENT : TickRateModulation.SLOWER; return changed ? TickRateModulation.URGENT : TickRateModulation.SLOWER;
} }
private boolean isDifferent( final ItemStack a, final ItemStack b )
{
if( a == b && b.isEmpty() )
{
return false;
}
if( ( a.isEmpty() && !b.isEmpty() ) || ( !a.isEmpty() && b.isEmpty() ) )
{
return true;
}
return !Platform.itemComparisons().isSameItem( a, b );
}
private void postDifference( final Iterable<IAEItemStack> a ) private void postDifference( final Iterable<IAEItemStack> a )
{ {
// AELog.info( a.getItemStack().getUnlocalizedName() + " @ " + a.getStackSize() );
if( a != null ) if( a != null )
{ {
final Iterator<Entry<IMEMonitorHandlerReceiver<IAEItemStack>, Object>> i = this.listeners.entrySet().iterator(); final Iterator<Entry<IMEMonitorHandlerReceiver<IAEItemStack>, Object>> i = this.listeners.entrySet().iterator();
@@ -306,9 +253,9 @@ public class MEMonitorIInventory implements IMEMonitor<IAEItemStack>, ITickingMo
@Override @Override
public IItemList<IAEItemStack> getAvailableItems( final IItemList out ) public IItemList<IAEItemStack> getAvailableItems( final IItemList out )
{ {
for( final CachedItemStack is : this.memory.values() ) for( IAEItemStack is : cache )
{ {
out.addStorage( is.aeStack ); out.addStorage( is );
} }
return out; return out;
@@ -317,7 +264,7 @@ public class MEMonitorIInventory implements IMEMonitor<IAEItemStack>, ITickingMo
@Override @Override
public IItemList<IAEItemStack> getStorageList() public IItemList<IAEItemStack> getStorageList()
{ {
return this.list; return this.cache;
} }
private StorageFilter getMode() private StorageFilter getMode()
@@ -341,24 +288,4 @@ public class MEMonitorIInventory implements IMEMonitor<IAEItemStack>, ITickingMo
this.mySource = mySource; this.mySource = mySource;
} }
private static class CachedItemStack
{
private final ItemStack itemStack;
private final IAEItemStack aeStack;
public CachedItemStack( final ItemStack is )
{
if( is.isEmpty() )
{
this.itemStack = ItemStack.EMPTY;
this.aeStack = null;
}
else
{
this.itemStack = is.copy();
this.aeStack = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createStack( is );
}
}
}
} }
@@ -72,7 +72,7 @@ public class MEMonitorPassThrough<T extends IAEStack<T>> extends MEPassThrough<T
final IItemList<T> after = this.getInternal() == null ? this.getWrappedChannel().createList() : this.getInternal() final IItemList<T> after = this.getInternal() == null ? this.getWrappedChannel().createList() : this.getInternal()
.getAvailableItems( new ItemListIgnoreCrafting( this.getWrappedChannel().createList() ) ); .getAvailableItems( new ItemListIgnoreCrafting( this.getWrappedChannel().createList() ) );
if( this.monitor != null ) if( this.monitor != null && this.listeners.size() > 0 )
{ {
this.monitor.addListener( this, this.monitor ); this.monitor.addListener( this, this.monitor );
} }
@@ -90,6 +90,13 @@ public class MEMonitorPassThrough<T extends IAEStack<T>> extends MEPassThrough<T
@Override @Override
public void addListener( final IMEMonitorHandlerReceiver<T> l, final Object verificationToken ) 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 ); this.listeners.put( l, verificationToken );
} }
@@ -164,4 +171,5 @@ public class MEMonitorPassThrough<T extends IAEStack<T>> extends MEPassThrough<T
{ {
this.changeSource = changeSource; this.changeSource = changeSource;
} }
} }
@@ -41,7 +41,7 @@ public class MEPassThrough<T extends IAEStack<T>> implements IMEInventoryHandler
this.setInternal( i ); this.setInternal( i );
} }
protected IMEInventory<T> getInternal() public IMEInventory<T> getInternal()
{ {
return this.internal; return this.internal;
} }
@@ -19,6 +19,8 @@
package appeng.me.storage; package appeng.me.storage;
import appeng.me.helpers.MEMonitorHandler;
import appeng.me.helpers.MachineSource;
import com.mojang.authlib.GameProfile; import com.mojang.authlib.GameProfile;
import appeng.api.AEApi; import appeng.api.AEApi;
@@ -35,16 +37,20 @@ import appeng.api.storage.data.IItemList;
import appeng.me.GridAccessException; import appeng.me.GridAccessException;
import appeng.tile.misc.TileSecurityStation; import appeng.tile.misc.TileSecurityStation;
import java.util.Collections;
public class SecurityStationInventory implements IMEInventoryHandler<IAEItemStack> public class SecurityStationInventory implements IMEInventoryHandler<IAEItemStack>
{ {
private final IItemList<IAEItemStack> storedItems = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); private final IItemList<IAEItemStack> storedItems = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList();
private final TileSecurityStation securityTile; private final TileSecurityStation securityTile;
private final MachineSource src;
public SecurityStationInventory( final TileSecurityStation ts ) public SecurityStationInventory( final TileSecurityStation ts )
{ {
this.securityTile = ts; this.securityTile = ts;
this.src = new MachineSource( securityTile );
} }
@Override @Override
@@ -61,6 +67,11 @@ public class SecurityStationInventory implements IMEInventoryHandler<IAEItemStac
return null; return null;
} }
if( securityTile.getProxy().isActive() )
{
( ( MEMonitorHandler<IAEItemStack> ) securityTile.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) ).postChangesToListeners( Collections.singletonList( input.copy() ), this.src );
}
this.getStoredItems().add( input ); this.getStoredItems().add( input );
this.securityTile.inventoryChanged(); this.securityTile.inventoryChanged();
return null; return null;
@@ -101,6 +112,11 @@ public class SecurityStationInventory implements IMEInventoryHandler<IAEItemStac
return output; return output;
} }
if( securityTile.getProxy().isActive() )
{
( ( MEMonitorHandler<IAEItemStack> ) securityTile.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) ).postChangesToListeners( Collections.singletonList( target.copy().setStackSize( -target.getStackSize() ) ), this.src );
}
target.setStackSize( 0 ); target.setStackSize( 0 );
this.securityTile.inventoryChanged(); this.securityTile.inventoryChanged();
return output; return output;
@@ -180,7 +180,10 @@ public class PartExportBus extends PartSharedItemBus implements ICraftingRequest
} }
else else
{ {
this.pushItemIntoTarget( destination, energy, inv, ais ); if( inv.getStorageList().findPrecise( ais ) != null )
{
this.pushItemIntoTarget( destination, energy, inv, ais );
}
} }
if( this.itemToSend == before && this.isCraftingEnabled() ) if( this.itemToSend == before && this.isCraftingEnabled() )
@@ -187,8 +187,9 @@ public class PartFormationPlane extends PartAbstractFormationPlane<IAEItemStack>
this.stateChanged(); this.stateChanged();
} }
@Override
@MENetworkEventSubscribe @MENetworkEventSubscribe
public void updateChannels( final MENetworkChannelsChanged changedChannels ) public void chanRender( final MENetworkChannelsChanged changedChannels )
{ {
this.stateChanged(); this.stateChanged();
} }
@@ -206,7 +207,7 @@ public class PartFormationPlane extends PartAbstractFormationPlane<IAEItemStack>
@Override @Override
public List<IMEInventoryHandler> getCellArray( final IStorageChannel channel ) public List<IMEInventoryHandler> getCellArray( final IStorageChannel channel )
{ {
if( this.getProxy().isActive() && channel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) if( channel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) )
{ {
final List<IMEInventoryHandler> handler = new ArrayList<>( 1 ); final List<IMEInventoryHandler> handler = new ArrayList<>( 1 );
handler.add( this.myHandler ); handler.add( this.myHandler );
@@ -283,12 +283,12 @@ public class PartImportBus extends PartSharedItemBus implements IInventoryDestin
final ItemStack simResult; final ItemStack simResult;
if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 )
{ {
simResult = myAdaptor.simulateSimilarRemove( toSend, itemStackToImport, fzMode, this ); simResult = myAdaptor.simulateSimilarRemove( toSend, itemStackToImport, fzMode, null );
itemAmountNotStorable = inv.injectItems( AEItemStack.fromItemStack( simResult ), Actionable.SIMULATE, this.source ); itemAmountNotStorable = inv.injectItems( AEItemStack.fromItemStack( simResult ), Actionable.SIMULATE, this.source );
} }
else else
{ {
simResult = myAdaptor.simulateRemove( toSend, itemStackToImport, this ); simResult = myAdaptor.simulateRemove( toSend, itemStackToImport, null );
itemAmountNotStorable = inv.injectItems( AEItemStack.fromItemStack( simResult ), Actionable.SIMULATE, this.source ); itemAmountNotStorable = inv.injectItems( AEItemStack.fromItemStack( simResult ), Actionable.SIMULATE, this.source );
} }
@@ -19,40 +19,9 @@
package appeng.parts.automation; package appeng.parts.automation;
import java.util.Random;
import appeng.me.Grid;
import appeng.me.GridNode;
import appeng.util.item.AEItemStack;
import it.unimi.dsi.fastutil.objects.Object2LongMap;
import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumHand;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.items.IItemHandler;
import appeng.api.AEApi; import appeng.api.AEApi;
import appeng.api.config.FuzzyMode; import appeng.api.config.*;
import appeng.api.config.LevelType; import appeng.api.networking.crafting.*;
import appeng.api.config.RedstoneMode;
import appeng.api.config.Settings;
import appeng.api.config.Upgrades;
import appeng.api.config.YesNo;
import appeng.api.networking.crafting.ICraftingGrid;
import appeng.api.networking.crafting.ICraftingPatternDetails;
import appeng.api.networking.crafting.ICraftingProvider;
import appeng.api.networking.crafting.ICraftingProviderHelper;
import appeng.api.networking.crafting.ICraftingWatcher;
import appeng.api.networking.crafting.ICraftingWatcherHost;
import appeng.api.networking.energy.IEnergyGrid; import appeng.api.networking.energy.IEnergyGrid;
import appeng.api.networking.energy.IEnergyWatcher; import appeng.api.networking.energy.IEnergyWatcher;
import appeng.api.networking.energy.IEnergyWatcherHost; import appeng.api.networking.energy.IEnergyWatcherHost;
@@ -81,10 +50,28 @@ import appeng.core.sync.GuiBridge;
import appeng.helpers.Reflected; import appeng.helpers.Reflected;
import appeng.items.parts.PartModels; import appeng.items.parts.PartModels;
import appeng.me.GridAccessException; import appeng.me.GridAccessException;
import appeng.me.cache.NetworkMonitor;
import appeng.parts.PartModel; import appeng.parts.PartModel;
import appeng.tile.inventory.AppEngInternalAEInventory; import appeng.tile.inventory.AppEngInternalAEInventory;
import appeng.util.Platform; import appeng.util.Platform;
import appeng.util.inv.InvOperation; import appeng.util.inv.InvOperation;
import appeng.util.item.OreHelper;
import appeng.util.item.OreReference;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumHand;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.items.IItemHandler;
import java.util.Optional;
import java.util.Random;
public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherHost, IStackWatcherHost, ICraftingWatcherHost, IMEMonitorHandlerReceiver<IAEItemStack>, ICraftingProvider public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherHost, IStackWatcherHost, ICraftingWatcherHost, IMEMonitorHandlerReceiver<IAEItemStack>, ICraftingProvider
@@ -123,9 +110,6 @@ public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherH
private double centerX; private double centerX;
private double centerY; private double centerY;
private double centerZ; 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 @Reflected
public PartLevelEmitter( final ItemStack is ) public PartLevelEmitter( final ItemStack is )
@@ -156,12 +140,6 @@ public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherH
} }
} }
@MENetworkEventSubscribe
public void powerChanged( final MENetworkPowerStatusChange c )
{
this.updateState();
}
private void updateState() private void updateState()
{ {
final boolean isOn = this.isLevelEmitterOn(); final boolean isOn = this.isLevelEmitterOn();
@@ -206,9 +184,25 @@ public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherH
return flipState ? this.reportingValue >= this.lastReportedValue + 1 : this.reportingValue < this.lastReportedValue + 1; return flipState ? this.reportingValue >= this.lastReportedValue + 1 : this.reportingValue < this.lastReportedValue + 1;
} }
@Override
@MENetworkEventSubscribe @MENetworkEventSubscribe
public void channelChanged( final MENetworkChannelsChanged c ) public void powerRender( final MENetworkPowerStatusChange powerEvent )
{ {
if (this.getProxy().isActive())
{
onListUpdate();
}
this.updateState();
}
@Override
@MENetworkEventSubscribe
public void chanRender( final MENetworkChannelsChanged c )
{
if (this.getProxy().isActive())
{
onListUpdate();
}
this.updateState(); this.updateState();
} }
@@ -323,90 +317,29 @@ public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherH
} }
private void updateReportingValue( final IMEMonitor<IAEItemStack> monitor ) 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 ); final IAEItemStack myStack = this.config.getAEStackInSlot( 0 );
GridNode node = (GridNode) (this.getGridNode()); if( myStack == null )
if( node != null )
{ {
if( monitor instanceof NetworkMonitor )
final Grid g = node.getInternalGrid();
if( myStack == null )
{ {
if( change != null ) this.lastReportedValue = ( (NetworkMonitor<IAEItemStack>) monitor ).getGridCurrentCount();
{
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 );
} }
}
else if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) else if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 )
{ {
final FuzzyMode fzMode = (FuzzyMode) this.getConfigManager().getSetting( Settings.FUZZY_MODE ); 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();
} );
}
}
fuzzyAEItemStackCount.computeIfAbsent( g, ( grid -> new Object2LongOpenHashMap<>() ) ); this.lastReportedValue = 0;
fuzzyAEItemStackCount.get( g ).computeIfAbsent( (AEItemStack) myStack, ( aLong -> { monitor.getStorageList().findFuzzy( myStack, fzMode ).forEach( iaeItemStack -> lastReportedValue += iaeItemStack.getStackSize() );
this.lastReportedValue = 0; }
monitor.getStorageList().findFuzzy( myStack, fzMode ).forEach( iaeItemStack -> lastReportedValue += iaeItemStack.getStackSize() ); else
return ( lastReportedValue ); {
} ) ); this.lastReportedValue = 0;
IAEItemStack precise = monitor.getStorageList().findPrecise( myStack );
this.lastReportedValue = fuzzyAEItemStackCount.get( g ).get( myStack ); if( precise != null ) lastReportedValue = precise.getStackSize();
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.updateState(); this.updateState();
} }
@@ -419,12 +352,23 @@ public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherH
} }
@Override @Override
public void onStackChange( final IItemList o, final IAEStack fullStack, final IAEStack diffStack, final IActionSource src, final IStorageChannel chan ) public void onStackChange( IItemList<?> o, IAEStack<?> fullStack, IAEStack<?> diffStack, IActionSource src, IStorageChannel<?> chan )
{ {
if( chan == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) && fullStack.equals( this.config.getAEStackInSlot( 0 ) ) && this if( chan == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) )
.getInstalledUpgrades( Upgrades.FUZZY ) == 0 )
{ {
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(); this.updateState();
} }
} }
@@ -459,7 +403,7 @@ public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherH
@Override @Override
public void postChange( final IBaseMonitor<IAEItemStack> monitor, final Iterable<IAEItemStack> change, final IActionSource actionSource ) 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 @Override
@@ -552,6 +496,7 @@ public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherH
public void upgradesChanged() public void upgradesChanged()
{ {
this.configureWatchers(); this.configureWatchers();
this.updateState();
} }
@Override @Override
@@ -636,9 +581,4 @@ public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherH
} }
} }
public static void wipeCache(){
fuzzyAEItemStackCount.clear();
preciseAEItemStackCount.clear();
gridItemCount.clear();
}
} }
@@ -19,10 +19,20 @@
package appeng.parts.automation; package appeng.parts.automation;
import javax.annotation.Nonnull;
import appeng.api.AEApi;
import appeng.container.slot.SlotRestrictedInput;
import appeng.core.Api;
import appeng.helpers.DualityInterface;
import appeng.util.inv.ItemHandlerIterator;
import net.minecraft.client.Minecraft;
import net.minecraft.init.Items; import net.minecraft.init.Items;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandler;
import appeng.api.config.Upgrades; import appeng.api.config.Upgrades;
@@ -33,6 +43,9 @@ import appeng.util.inv.IAEAppEngInventory;
import appeng.util.inv.InvOperation; import appeng.util.inv.InvOperation;
import appeng.util.inv.filter.IAEItemFilter; import appeng.util.inv.filter.IAEItemFilter;
import java.util.ArrayList;
import java.util.List;
public abstract class UpgradeInventory extends AppEngInternalInventory implements IAEAppEngInventory public abstract class UpgradeInventory extends AppEngInternalInventory implements IAEAppEngInventory
{ {
@@ -45,6 +58,7 @@ public abstract class UpgradeInventory extends AppEngInternalInventory implement
private int capacityUpgrades = 0; private int capacityUpgrades = 0;
private int inverterUpgrades = 0; private int inverterUpgrades = 0;
private int craftingUpgrades = 0; private int craftingUpgrades = 0;
private int patternExpansionUpgrades = 0;
public UpgradeInventory( final IAEAppEngInventory parent, final int s ) public UpgradeInventory( final IAEAppEngInventory parent, final int s )
{ {
@@ -81,6 +95,8 @@ public abstract class UpgradeInventory extends AppEngInternalInventory implement
return this.inverterUpgrades; return this.inverterUpgrades;
case CRAFTING: case CRAFTING:
return this.craftingUpgrades; return this.craftingUpgrades;
case PATTERN_EXPANSION:
return this.patternExpansionUpgrades;
default: default:
return 0; return 0;
} }
@@ -91,7 +107,7 @@ public abstract class UpgradeInventory extends AppEngInternalInventory implement
private void updateUpgradeInfo() private void updateUpgradeInfo()
{ {
this.cached = true; this.cached = true;
this.inverterUpgrades = this.capacityUpgrades = this.redstoneUpgrades = this.speedUpgrades = this.fuzzyUpgrades = this.craftingUpgrades = 0; this.patternExpansionUpgrades = this.inverterUpgrades = this.capacityUpgrades = this.redstoneUpgrades = this.speedUpgrades = this.fuzzyUpgrades = this.craftingUpgrades = 0;
for( final ItemStack is : this ) for( final ItemStack is : this )
{ {
@@ -121,6 +137,9 @@ public abstract class UpgradeInventory extends AppEngInternalInventory implement
case CRAFTING: case CRAFTING:
this.craftingUpgrades++; this.craftingUpgrades++;
break; break;
case PATTERN_EXPANSION:
this.patternExpansionUpgrades++;
break;
default: default:
break; break;
} }
@@ -132,6 +151,7 @@ public abstract class UpgradeInventory extends AppEngInternalInventory implement
this.speedUpgrades = Math.min( this.speedUpgrades, this.getMaxInstalled( Upgrades.SPEED ) ); this.speedUpgrades = Math.min( this.speedUpgrades, this.getMaxInstalled( Upgrades.SPEED ) );
this.inverterUpgrades = Math.min( this.inverterUpgrades, this.getMaxInstalled( Upgrades.INVERTER ) ); this.inverterUpgrades = Math.min( this.inverterUpgrades, this.getMaxInstalled( Upgrades.INVERTER ) );
this.craftingUpgrades = Math.min( this.craftingUpgrades, this.getMaxInstalled( Upgrades.CRAFTING ) ); this.craftingUpgrades = Math.min( this.craftingUpgrades, this.getMaxInstalled( Upgrades.CRAFTING ) );
this.patternExpansionUpgrades = Math.min( this.patternExpansionUpgrades, this.getMaxInstalled( Upgrades.PATTERN_EXPANSION ) );
} }
@Override @Override
@@ -160,6 +180,13 @@ public abstract class UpgradeInventory extends AppEngInternalInventory implement
} }
} }
@Nonnull
@Override
public ItemStack extractItem( int slot, int amount, boolean simulate )
{
return super.extractItem( slot, amount, simulate );
}
private class UpgradeInvFilter implements IAEItemFilter private class UpgradeInvFilter implements IAEItemFilter
{ {
@@ -19,17 +19,12 @@
package appeng.parts.misc; package appeng.parts.misc;
import java.util.*; import javax.annotation.Nullable;
import appeng.api.AEApi;
import appeng.api.config.AccessRestriction;
import appeng.api.config.Actionable;
import appeng.api.config.Settings; import appeng.api.config.Settings;
import appeng.api.config.StorageFilter; import appeng.api.config.StorageFilter;
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 appeng.api.AEApi;
import appeng.api.config.Actionable;
import appeng.api.networking.security.IActionSource; import appeng.api.networking.security.IActionSource;
import appeng.api.networking.storage.IBaseMonitor; import appeng.api.networking.storage.IBaseMonitor;
import appeng.api.networking.ticking.TickRateModulation; import appeng.api.networking.ticking.TickRateModulation;
@@ -39,11 +34,19 @@ import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList; import appeng.api.storage.data.IItemList;
import appeng.core.AELog; import appeng.core.AELog;
import appeng.me.GridAccessException;
import appeng.me.helpers.IGridProxyable; import appeng.me.helpers.IGridProxyable;
import appeng.me.storage.ITickingMonitor; import appeng.me.storage.ITickingMonitor;
import appeng.util.Platform; import appeng.util.inv.ItemHandlerIterator;
import appeng.util.inv.ItemSlot;
import appeng.util.item.AEItemStack; import appeng.util.item.AEItemStack;
import org.apache.commons.lang3.tuple.Pair; import com.google.common.primitives.Ints;
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 java.util.*;
/** /**
@@ -57,6 +60,9 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
private final IGridProxyable proxyable; private final IGridProxyable proxyable;
private final InventoryCache cache; private final InventoryCache cache;
private StorageFilter mode; private StorageFilter mode;
private AccessRestriction access;
private ItemStack stackCache = null;
ItemHandlerAdapter( IItemHandler itemHandler, IGridProxyable proxy ) ItemHandlerAdapter( IItemHandler itemHandler, IGridProxyable proxy )
{ {
@@ -66,35 +72,45 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
{ {
PartStorageBus partStorageBus = (PartStorageBus) this.proxyable; PartStorageBus partStorageBus = (PartStorageBus) this.proxyable;
this.mode = ( (StorageFilter) partStorageBus.getConfigManager().getSetting( Settings.STORAGE_FILTER ) ); this.mode = ( (StorageFilter) partStorageBus.getConfigManager().getSetting( Settings.STORAGE_FILTER ) );
this.access = ( (AccessRestriction) partStorageBus.getConfigManager().getSetting( Settings.ACCESS ) );
} }
this.cache = new InventoryCache( this.itemHandler, this.mode ); this.cache = new InventoryCache( this.itemHandler, this.mode );
this.cache.update();
} }
@Override @Override
public IAEItemStack injectItems( IAEItemStack iox, Actionable type, IActionSource src ) public IAEItemStack injectItems( IAEItemStack iox, Actionable type, IActionSource src )
{ {
// Try to reuse the cached stack
@Nullable ItemStack currentCached = stackCache;
stackCache = null;
ItemStack orgInput;
int slotCount = this.itemHandler.getSlots();
if( currentCached != null && iox.isSameType( currentCached ) )
{
// Cache is suitable, just update the count
orgInput = currentCached;
currentCached.setCount( Ints.saturatedCast( iox.getStackSize() ) );
}
else
{
// We need a new stack :-(
orgInput = iox.createItemStack();
}
ItemStack orgInput = iox.createItemStack();
ItemStack remaining = orgInput; ItemStack remaining = orgInput;
int slotCount = this.itemHandler.getSlots();
boolean simulate = ( type == Actionable.SIMULATE );
List<Pair<Integer, Integer>> injectedList = new ArrayList<>();
// This uses a brute force approach and tries to jam it in every slot the inventory exposes.
for( int i = 0; i < slotCount && !remaining.isEmpty(); i++ ) for( int i = 0; i < slotCount && !remaining.isEmpty(); i++ )
{ {
int countPre = remaining.getCount(); remaining = this.itemHandler.insertItem( i, remaining, type == Actionable.SIMULATE );
remaining = this.itemHandler.insertItem( i, remaining, simulate ); }
int countPos = remaining.getCount();
if( remaining.isEmpty() ) // Store the stack in the cache for next time.
{ if( !remaining.isEmpty() && remaining != orgInput )
injectedList.add( Pair.of( i, countPre ) ); {
break; stackCache = remaining;
}
else if( countPos < countPre )
{
injectedList.add( Pair.of( i, countPre - countPos ) );
}
} }
// At this point, we still have some items left... // At this point, we still have some items left...
@@ -106,30 +122,17 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
if( type == Actionable.MODULATE ) if( type == Actionable.MODULATE )
{ {
if( this.cache.cachedAeStacks.length == 0 ) IAEItemStack added = iox.copy().setStackSize( iox.getStackSize() - remaining.getCount() );
this.cache.currentlyCached.add( added );
this.postDifference( Collections.singletonList( added ) );
try
{ {
this.cache.update(); this.proxyable.getProxy().getTick().alertDevice( this.proxyable.getProxy().getNode() );
} }
else catch( GridAccessException ex )
{ {
for( Pair<Integer, Integer> pair : injectedList ) // meh
{
if( pair.getKey() >= this.cache.cachedAeStacks.length )
{
this.cache.update();
break;
}
if( this.cache.cachedAeStacks[pair.getKey()] == null )
{
this.cache.cachedAeStacks[pair.getKey()] = iox.copy().setStackSize( pair.getValue() );
}
else
{
this.cache.cachedAeStacks[pair.getKey()].incStackSize( pair.getValue() );
}
}
} }
} }
return AEItemStack.fromItemStack( remaining ); return AEItemStack.fromItemStack( remaining );
@@ -138,21 +141,17 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
@Override @Override
public IAEItemStack extractItems( IAEItemStack request, Actionable mode, IActionSource src ) public IAEItemStack extractItems( IAEItemStack request, Actionable mode, IActionSource src )
{ {
ItemStack requestedItemStack = request.createItemStack(); int remainingSize = Ints.saturatedCast( request.getStackSize() );
int remainingSize = requestedItemStack.getCount();
// Use this to gather the requested items // Use this to gather the requested items
ItemStack gathered = ItemStack.EMPTY; ItemStack gathered = ItemStack.EMPTY;
final boolean simulate = ( mode == Actionable.SIMULATE ); final boolean simulate = ( mode == Actionable.SIMULATE );
List<Pair<Integer, Integer>> extractedList = new ArrayList<>();
for ( int i = 0; i < this.itemHandler.getSlots(); i++ ) for ( int i = 0; i < this.itemHandler.getSlots(); i++ )
{ {
ItemStack stackInInventorySlot = this.itemHandler.getStackInSlot( i ); ItemStack stackInInventorySlot = this.itemHandler.getStackInSlot( i );
if( !Platform.itemComparisons().isSameItem( stackInInventorySlot, requestedItemStack ) ) if( !request.isSameType( stackInInventorySlot ) )
{ {
continue; continue;
} }
@@ -191,16 +190,10 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
} }
remainingCurrentSlot -= extracted.getCount(); remainingCurrentSlot -= extracted.getCount();
} }
} } while ( !extracted.isEmpty() && remainingCurrentSlot > 0 );
while ( !extracted.isEmpty() && remainingCurrentSlot > 0 );
remainingSize -= stackSizeCurrentSlot - remainingCurrentSlot; remainingSize -= stackSizeCurrentSlot - remainingCurrentSlot;
if (!gathered.isEmpty())
{
extractedList.add( Pair.of( i, gathered.getCount() ) );
}
// Done? // Done?
if( remainingSize <= 0 ) if( remainingSize <= 0 )
{ {
@@ -210,29 +203,26 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
if( !gathered.isEmpty() ) if( !gathered.isEmpty() )
{ {
IAEItemStack gatheredAEItemStack = AEItemStack.fromItemStack( gathered );
if( mode == Actionable.MODULATE ) if( mode == Actionable.MODULATE )
{ {
if( this.cache.cachedAeStacks.length == 0 ) IAEItemStack cachedStack = this.cache.currentlyCached.findPrecise( request );
if( cachedStack != null )
{ {
this.cache.update(); cachedStack.decStackSize( gatheredAEItemStack.getStackSize() );
this.postDifference( Collections.singletonList( gatheredAEItemStack.copy().setStackSize( -gatheredAEItemStack.getStackSize() ) ) );
} }
else try
{ {
for( Pair<Integer, Integer> pair : extractedList ) this.proxyable.getProxy().getTick().alertDevice( this.proxyable.getProxy().getNode() );
{ }
if( this.cache.cachedAeStacks[pair.getKey()] != null ) catch( GridAccessException ex )
{ {
this.cache.cachedAeStacks[pair.getKey()].decStackSize( pair.getValue() ); // meh
if( this.cache.cachedAeStacks[pair.getKey()].getStackSize() == 0 )
{
this.cache.cachedAeStacks[pair.getKey()] = null;
}
}
}
} }
} }
return AEItemStack.fromItemStack( gathered ); return gatheredAEItemStack;
} }
return null; return null;
@@ -242,7 +232,7 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
public TickRateModulation onTick() public TickRateModulation onTick()
{ {
List<IAEItemStack> changes = this.cache.update(); List<IAEItemStack> changes = this.cache.update();
if( !changes.isEmpty() ) if( !changes.isEmpty() && access.hasPermission( AccessRestriction.READ ) )
{ {
this.postDifference( changes ); this.postDifference( changes );
return TickRateModulation.URGENT; return TickRateModulation.URGENT;
@@ -286,7 +276,7 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
private void postDifference( Iterable<IAEItemStack> a ) private void postDifference( Iterable<IAEItemStack> a )
{ {
final Iterator<Map.Entry<IMEMonitorHandlerReceiver<IAEItemStack>, Object>> i = this.listeners.entrySet().iterator(); final Iterator<Map.Entry<IMEMonitorHandlerReceiver<IAEItemStack>, Object>> i = this.listeners.entrySet().iterator();
while( i.hasNext() ) while ( i.hasNext() )
{ {
final Map.Entry<IMEMonitorHandlerReceiver<IAEItemStack>, Object> l = i.next(); final Map.Entry<IMEMonitorHandlerReceiver<IAEItemStack>, Object> l = i.next();
final IMEMonitorHandlerReceiver<IAEItemStack> key = l.getKey(); final IMEMonitorHandlerReceiver<IAEItemStack> key = l.getKey();
@@ -301,11 +291,11 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
} }
} }
private static class InventoryCache private static class InventoryCache implements Iterable<ItemSlot>
{ {
private IAEItemStack[] cachedAeStacks = new IAEItemStack[0];
private final IItemHandler itemHandler; private final IItemHandler itemHandler;
private final StorageFilter mode; private final StorageFilter mode;
IItemList<IAEItemStack> currentlyCached = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList();
public InventoryCache( IItemHandler itemHandler, StorageFilter mode ) public InventoryCache( IItemHandler itemHandler, StorageFilter mode )
{ {
@@ -315,106 +305,58 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
public IItemList<IAEItemStack> getAvailableItems( IItemList<IAEItemStack> out ) public IItemList<IAEItemStack> getAvailableItems( IItemList<IAEItemStack> out )
{ {
Arrays.stream( this.cachedAeStacks ).forEach( out::add ); currentlyCached.iterator().forEachRemaining( out::add );
return out; return out;
} }
private StorageFilter getMode()
{
return this.mode;
}
public List<IAEItemStack> update() public List<IAEItemStack> update()
{ {
final List<IAEItemStack> changes = new ArrayList<>(); final List<IAEItemStack> changes = new ArrayList<>();
final int slots = this.itemHandler.getSlots();
// Make room for new slots IItemList<IAEItemStack> currentlyOnStorage = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList();
if( slots > this.cachedAeStacks.length )
{
this.cachedAeStacks = Arrays.copyOf( this.cachedAeStacks, slots );
}
for( int slot = 0; slot < slots; slot++ ) for( final ItemSlot is : this )
{ {
// Save the old stuff if( this.mode == StorageFilter.EXTRACTABLE_ONLY && !is.isExtractable() )
final IAEItemStack oldAeIS = this.cachedAeStacks[slot];
ItemStack newIS = this.itemHandler.getStackInSlot( slot );
if( this.mode == StorageFilter.EXTRACTABLE_ONLY && !newIS.isEmpty() )
{ {
if( this.itemHandler.extractItem( slot, 1, true ).isEmpty() ) continue;
{
newIS = ItemStack.EMPTY;
}
} }
this.handlePossibleSlotChanges( slot, oldAeIS, newIS, changes ); currentlyOnStorage.add( is.getAEItemStack() );
} }
// Handle cases where the number of slots actually is lower now than before for ( final IAEItemStack is : currentlyCached )
if( slots < this.cachedAeStacks.length )
{ {
for( int slot = slots; slot < this.cachedAeStacks.length; slot++ ) is.setStackSize( -is.getStackSize() );
{
final IAEItemStack aeStack = this.cachedAeStacks[slot];
if( aeStack != null )
{
final IAEItemStack a = aeStack.copy();
a.setStackSize( -a.getStackSize() );
changes.add( a );
}
}
// Reduce the cache size
this.cachedAeStacks = Arrays.copyOf( this.cachedAeStacks, slots );
} }
for ( final IAEItemStack is : currentlyOnStorage )
{
currentlyCached.add( is );
}
for ( final IAEItemStack is : currentlyCached )
{
if( is.getStackSize() != 0 )
{
changes.add( is );
}
}
currentlyCached = currentlyOnStorage;
return changes; return changes;
} }
private void handlePossibleSlotChanges( int slot, IAEItemStack oldAeIS, ItemStack newIS, List<IAEItemStack> changes ) @Override
public Iterator<ItemSlot> iterator()
{ {
if( oldAeIS != null && oldAeIS.isSameType( newIS ) ) return new ItemHandlerIterator( this.itemHandler );
{
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] );
}
}
} }
} }
@@ -1,32 +1,32 @@
package appeng.parts.misc; package appeng.parts.misc;
import java.util.*; import javax.annotation.Nullable;
import java.util.stream.Collectors;
import appeng.api.storage.IStorageChannel;
import appeng.core.AELog;
import com.jaquadro.minecraft.storagedrawers.api.capabilities.IItemRepository;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import net.minecraft.item.ItemStack;
import appeng.api.AEApi; import appeng.api.AEApi;
import appeng.api.config.AccessRestriction;
import appeng.api.config.Actionable; import appeng.api.config.Actionable;
import appeng.api.config.Settings;
import appeng.api.networking.security.IActionSource; import appeng.api.networking.security.IActionSource;
import appeng.api.networking.storage.IBaseMonitor; import appeng.api.networking.storage.IBaseMonitor;
import appeng.api.networking.ticking.TickRateModulation; import appeng.api.networking.ticking.TickRateModulation;
import appeng.api.storage.IMEInventory; import appeng.api.storage.IMEInventory;
import appeng.api.storage.IMEMonitorHandlerReceiver; import appeng.api.storage.IMEMonitorHandlerReceiver;
import appeng.api.storage.IStorageChannel;
import appeng.api.storage.channels.IItemStorageChannel; import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList; import appeng.api.storage.data.IItemList;
import appeng.core.AELog;
import appeng.me.GridAccessException; import appeng.me.GridAccessException;
import appeng.me.helpers.IGridProxyable; import appeng.me.helpers.IGridProxyable;
import appeng.me.storage.ITickingMonitor; import appeng.me.storage.ITickingMonitor;
import appeng.util.item.AEItemStack; import appeng.util.item.AEItemStack;
import com.google.common.primitives.Ints;
import com.jaquadro.minecraft.storagedrawers.api.capabilities.IItemRepository;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import net.minecraft.item.ItemStack;
import java.util.*;
import javax.annotation.Nonnull;
/** /**
* Wraps an Item Repository in such a way that it can be used as an IMEInventory for items. * Wraps an Item Repository in such a way that it can be used as an IMEInventory for items.
@@ -40,24 +40,49 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
private final IItemRepository itemRepository; private final IItemRepository itemRepository;
private final IGridProxyable proxyable; private final IGridProxyable proxyable;
private final InventoryCache cache; private final InventoryCache cache;
private AccessRestriction access;
private ItemStack stackCache;
ItemRepositoryAdapter( IItemRepository itemRepository, IGridProxyable proxy ) ItemRepositoryAdapter( IItemRepository itemRepository, IGridProxyable proxy )
{ {
this.itemRepository = itemRepository; this.itemRepository = itemRepository;
this.proxyable = proxy; this.proxyable = proxy;
this.cache = new InventoryCache( this.itemRepository ); this.cache = new InventoryCache( this.itemRepository );
if( this.proxyable instanceof PartStorageBus )
{
PartStorageBus partStorageBus = (PartStorageBus) this.proxyable;
this.access = ( (AccessRestriction) partStorageBus.getConfigManager().getSetting( Settings.ACCESS ) );
}
this.cache.update();
} }
@Override @Override
public IAEItemStack injectItems( IAEItemStack iox, Actionable type, IActionSource src ) public IAEItemStack injectItems( IAEItemStack iox, Actionable type, IActionSource src )
{ {
ItemStack orgInput = iox.createItemStack(); // Try to reuse the cached stack
ItemStack remaining = orgInput; @Nullable ItemStack currentCached = stackCache;
stackCache = null;
boolean simulate = ( type == Actionable.SIMULATE ); ItemStack orgInput;
if( currentCached != null && iox.isSameType( currentCached ) )
{
// Cache is suitable, just update the count
orgInput = currentCached;
currentCached.setCount( Ints.saturatedCast( iox.getStackSize() ) );
}
else
{
// We need a new stack :-(
orgInput = iox.createItemStack();
}
ItemStack remaining = this.itemRepository.insertItem( orgInput, type == Actionable.SIMULATE );
remaining = this.itemRepository.insertItem( remaining, simulate ); // Store the stack in the cache for next time.
if( !remaining.isEmpty() && remaining != orgInput )
{
stackCache = remaining;
}
// At this point, we still have some items left... // At this point, we still have some items left...
if( remaining == orgInput ) if( remaining == orgInput )
@@ -68,6 +93,9 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
if( type == Actionable.MODULATE ) if( type == Actionable.MODULATE )
{ {
IAEItemStack added = iox.copy().setStackSize( iox.getStackSize() - remaining.getCount() );
this.cache.currentlyCached.add( added );
this.postDifference( Collections.singletonList( added ) );
try try
{ {
this.proxyable.getProxy().getTick().alertDevice( this.proxyable.getProxy().getNode() ); this.proxyable.getProxy().getTick().alertDevice( this.proxyable.getProxy().getNode() );
@@ -85,12 +113,11 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
@Override @Override
public IAEItemStack extractItems( IAEItemStack request, Actionable mode, IActionSource src ) public IAEItemStack extractItems( IAEItemStack request, Actionable mode, IActionSource src )
{ {
ItemStack requestedItemStack = request.getDefinition(); int remainingSize = Ints.saturatedCast( request.getStackSize() );
int remainingSize = (int) Math.min( Integer.MAX_VALUE, request.getStackSize());
final boolean simulate = ( mode == Actionable.SIMULATE ); final boolean simulate = ( mode == Actionable.SIMULATE );
ItemStack extracted = this.itemRepository.extractItem( requestedItemStack, remainingSize, simulate ); ItemStack extracted = this.itemRepository.extractItem( request.getDefinition(), remainingSize, simulate );
if( extracted.getCount() > remainingSize ) if( extracted.getCount() > remainingSize )
{ {
@@ -103,8 +130,15 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
if( !extracted.isEmpty() ) if( !extracted.isEmpty() )
{ {
IAEItemStack extractedAEItemStack = AEItemStack.fromItemStack( extracted );
if( mode == Actionable.MODULATE ) if( mode == Actionable.MODULATE )
{ {
IAEItemStack cachedStack = this.cache.currentlyCached.findPrecise( request );
if (cachedStack != null)
{
cachedStack.decStackSize( extractedAEItemStack.getStackSize() );
this.postDifference( Collections.singletonList( extractedAEItemStack.copy().setStackSize( -extractedAEItemStack.getStackSize() ) ) );
}
try try
{ {
this.proxyable.getProxy().getTick().alertDevice( this.proxyable.getProxy().getNode() ); this.proxyable.getProxy().getTick().alertDevice( this.proxyable.getProxy().getNode() );
@@ -114,7 +148,7 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
// meh // meh
} }
} }
return AEItemStack.fromItemStack( extracted ); return extractedAEItemStack;
} }
return null; return null;
} }
@@ -146,7 +180,7 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
private void postDifference( Iterable<IAEItemStack> a ) private void postDifference( Iterable<IAEItemStack> a )
{ {
final Iterator<Map.Entry<IMEMonitorHandlerReceiver<IAEItemStack>, Object>> i = this.listeners.entrySet().iterator(); final Iterator<Map.Entry<IMEMonitorHandlerReceiver<IAEItemStack>, Object>> i = this.listeners.entrySet().iterator();
while( i.hasNext() ) while ( i.hasNext() )
{ {
final Map.Entry<IMEMonitorHandlerReceiver<IAEItemStack>, Object> l = i.next(); final Map.Entry<IMEMonitorHandlerReceiver<IAEItemStack>, Object> l = i.next();
final IMEMonitorHandlerReceiver<IAEItemStack> key = l.getKey(); final IMEMonitorHandlerReceiver<IAEItemStack> key = l.getKey();
@@ -164,17 +198,15 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
@Override @Override
public TickRateModulation onTick() public TickRateModulation onTick()
{ {
List<IAEItemStack> changes = this.cache.update();
if( !changes.isEmpty() && access.hasPermission( AccessRestriction.READ ) )
{ {
List<IAEItemStack> changes = this.cache.update(); this.postDifference( changes );
if( !changes.isEmpty() ) return TickRateModulation.URGENT;
{ }
this.postDifference( changes ); else
return TickRateModulation.URGENT; {
} return TickRateModulation.SLOWER;
else
{
return TickRateModulation.SLOWER;
}
} }
} }
@@ -186,7 +218,7 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
private static class InventoryCache 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; private final IItemRepository iItemRepository;
public InventoryCache( IItemRepository iItemRepository ) public InventoryCache( IItemRepository iItemRepository )
@@ -196,7 +228,7 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
public IItemList<IAEItemStack> getAvailableItems( IItemList<IAEItemStack> out ) public IItemList<IAEItemStack> getAvailableItems( IItemList<IAEItemStack> out )
{ {
Arrays.stream( this.cachedAeStacks ).forEach( out::add ); currentlyCached.iterator().forEachRemaining( out::add );
return out; return out;
} }
@@ -204,94 +236,31 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
{ {
final List<IAEItemStack> changes = new ArrayList<>(); 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(); for ( final IAEItemStack is : currentlyCached )
// Make room for new slots
if( size > this.cachedAeStacks.length )
{ {
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 currentlyCached.add( is );
final IAEItemStack oldAeIS = this.cachedAeStacks[x];
final IAEItemStack newIS = out.get( x );
this.handlePossibleSlotChanges( x, oldAeIS, newIS, changes );
} }
// Handle cases where the number of slots actually is lower now than before for ( final IAEItemStack is : currentlyCached )
if( size < this.cachedAeStacks.length )
{ {
for( int x = 0; x < this.cachedAeStacks.length; x++ ) if( is.getStackSize() != 0 )
{ {
final IAEItemStack aeStack = this.cachedAeStacks[x]; changes.add( is );
if( aeStack != null )
{
final IAEItemStack a = aeStack.copy();
a.setStackSize( -a.getStackSize() );
changes.add( a );
}
} }
// Reduce the cache size
this.cachedAeStacks = Arrays.copyOf( this.cachedAeStacks, size );
} }
currentlyCached = currentlyOnStorage;
return changes; 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] );
}
}
} }
} }
@@ -95,14 +95,16 @@ public class PartInterface extends PartBasicState implements IGridTickable, ISto
super( is ); super( is );
} }
@Override
@MENetworkEventSubscribe @MENetworkEventSubscribe
public void stateChange( final MENetworkChannelsChanged c ) public void chanRender( final MENetworkChannelsChanged c )
{ {
this.duality.notifyNeighbors(); this.duality.notifyNeighbors();
} }
@Override
@MENetworkEventSubscribe @MENetworkEventSubscribe
public void stateChange( final MENetworkPowerStatusChange c ) public void powerRender( final MENetworkPowerStatusChange c )
{ {
this.duality.notifyNeighbors(); this.duality.notifyNeighbors();
} }
@@ -22,8 +22,14 @@ package appeng.parts.misc;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import appeng.api.config.AccessRestriction;
import appeng.fluids.parts.PartFluidInterface;
import appeng.fluids.tile.TileFluidInterface;
import appeng.tile.misc.TileInterface;
import appeng.tile.networking.TileCableBus;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess; import net.minecraft.world.IBlockAccess;
@@ -55,6 +61,8 @@ public abstract class PartSharedStorageBus extends PartUpgradeable implements IG
{ {
private boolean wasActive = false; private boolean wasActive = false;
private int priority = 0; private int priority = 0;
protected boolean accessChanged;
protected boolean readOncePass;
public PartSharedStorageBus( ItemStack is ) public PartSharedStorageBus( ItemStack is )
{ {
@@ -79,8 +87,9 @@ public abstract class PartSharedStorageBus extends PartUpgradeable implements IG
} }
} }
@Override
@MENetworkEventSubscribe @MENetworkEventSubscribe
public void updateChannels( final MENetworkChannelsChanged changedChannels ) public void chanRender( final MENetworkChannelsChanged changedChannels )
{ {
this.updateStatus(); this.updateStatus();
} }
@@ -146,6 +155,10 @@ public abstract class PartSharedStorageBus extends PartUpgradeable implements IG
@Override @Override
public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue )
{ {
if( settingName.name().equals( "ACCESS" ) )
{
this.accessChanged = true;
}
this.resetCache( true ); this.resetCache( true );
this.getHost().markForSave(); this.getHost().markForSave();
} }
@@ -155,7 +168,27 @@ public abstract class PartSharedStorageBus extends PartUpgradeable implements IG
{ {
if( pos.offset( this.getSide().getFacing() ).equals( neighbor ) ) if( pos.offset( this.getSide().getFacing() ).equals( neighbor ) )
{ {
this.resetCache( false );
final TileEntity te = w.getTileEntity( neighbor );
// In case the TE was destroyed, we have to do a full reset immediately.
if( te instanceof TileCableBus )
{
if( ( (TileCableBus) te ).getPart( this.getSide().getOpposite() ) instanceof PartFluidInterface )
{
this.resetCache( true );
this.resetCache();
}
}
else if( te == null || te instanceof TileFluidInterface )
{
this.resetCache( true );
this.resetCache();
}
else
{
this.resetCache( false );
}
} }
} }
@@ -164,6 +197,7 @@ public abstract class PartSharedStorageBus extends PartUpgradeable implements IG
{ {
super.readFromNBT( data ); super.readFromNBT( data );
this.priority = data.getInteger( "priority" ); this.priority = data.getInteger( "priority" );
this.accessChanged = false;
} }
@Override @Override
@@ -23,6 +23,11 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import appeng.api.networking.storage.IStorageGrid;
import appeng.me.cache.GridStorageCache;
import appeng.tile.misc.TileInterface;
import appeng.tile.networking.TileCableBus;
import appeng.util.ConfigManager;
import com.jaquadro.minecraft.storagedrawers.api.capabilities.IItemRepository; import com.jaquadro.minecraft.storagedrawers.api.capabilities.IItemRepository;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
@@ -86,7 +91,6 @@ import appeng.me.GridAccessException;
import appeng.me.helpers.MachineSource; import appeng.me.helpers.MachineSource;
import appeng.me.storage.ITickingMonitor; import appeng.me.storage.ITickingMonitor;
import appeng.me.storage.MEInventoryHandler; import appeng.me.storage.MEInventoryHandler;
import appeng.me.storage.MEMonitorIInventory;
import appeng.parts.PartModel; import appeng.parts.PartModel;
import appeng.parts.automation.PartUpgradeable; import appeng.parts.automation.PartUpgradeable;
import appeng.tile.inventory.AppEngInternalAEInventory; import appeng.tile.inventory.AppEngInternalAEInventory;
@@ -121,6 +125,8 @@ public class PartStorageBus extends PartUpgradeable implements IGridTickable, IC
private int handlerHash = 0; private int handlerHash = 0;
private boolean wasActive = false; private boolean wasActive = false;
private byte resetCacheLogic = 0; private byte resetCacheLogic = 0;
private boolean accessChanged;
private boolean readOncePass;
@Reflected @Reflected
public PartStorageBus( final ItemStack is ) public PartStorageBus( final ItemStack is )
@@ -157,8 +163,9 @@ public class PartStorageBus extends PartUpgradeable implements IGridTickable, IC
} }
} }
@Override
@MENetworkEventSubscribe @MENetworkEventSubscribe
public void updateChannels( final MENetworkChannelsChanged changedChannels ) public void chanRender( final MENetworkChannelsChanged changedChannels )
{ {
this.updateStatus(); this.updateStatus();
} }
@@ -172,6 +179,10 @@ public class PartStorageBus extends PartUpgradeable implements IGridTickable, IC
@Override @Override
public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue )
{ {
if( settingName.name().equals( "ACCESS" ) )
{
this.accessChanged = true;
}
this.resetCache( true ); this.resetCache( true );
this.getHost().markForSave(); this.getHost().markForSave();
} }
@@ -200,6 +211,7 @@ public class PartStorageBus extends PartUpgradeable implements IGridTickable, IC
super.readFromNBT( data ); super.readFromNBT( data );
this.Config.readFromNBT( data, "config" ); this.Config.readFromNBT( data, "config" );
this.priority = data.getInteger( "priority" ); this.priority = data.getInteger( "priority" );
this.accessChanged = false;
} }
@Override @Override
@@ -234,7 +246,7 @@ public class PartStorageBus extends PartUpgradeable implements IGridTickable, IC
{ {
this.resetCacheLogic = 2; this.resetCacheLogic = 2;
} }
else else if( this.resetCacheLogic < 2 )
{ {
this.resetCacheLogic = 1; this.resetCacheLogic = 1;
} }
@@ -258,14 +270,29 @@ public class PartStorageBus extends PartUpgradeable implements IGridTickable, IC
@Override @Override
public void postChange( final IBaseMonitor<IAEItemStack> monitor, final Iterable<IAEItemStack> change, final IActionSource source ) 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 ) ) if( this.getProxy().isActive() )
{ {
AccessRestriction currentAccess = (AccessRestriction) ( (ConfigManager) this.getConfigManager() ).getSetting( Settings.ACCESS );
if( readOncePass )
{
readOncePass = false;
try
{
this.getProxy().getStorage().postAlterationOfStoredItems( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ), change, source );
}
catch( final GridAccessException e )
{
// :(
}
return;
}
if( !currentAccess.hasPermission( AccessRestriction.READ ) )
{
return;
}
try try
{ {
if( this.getProxy().isActive() ) this.getProxy().getStorage().postAlterationOfStoredItems( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ), change, source );
{
this.getProxy().getStorage().postAlterationOfStoredItems( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ), change, this.mySrc );
}
} }
catch( final GridAccessException e ) catch( final GridAccessException e )
{ {
@@ -293,10 +320,19 @@ public class PartStorageBus extends PartUpgradeable implements IGridTickable, IC
{ {
if( pos.offset( this.getSide().getFacing() ).equals( neighbor ) ) if( pos.offset( this.getSide().getFacing() ).equals( neighbor ) )
{ {
final TileEntity te = w.getTileEntity( neighbor ); final TileEntity te = w.getTileEntity( neighbor );
// In case the TE was destroyed, we have to do a full reset immediately. // In case the TE was destroyed, we have to do a full reset immediately.
if( te == null ) if( te instanceof TileCableBus )
{
if( ( (TileCableBus) te ).getPart( this.getSide().getOpposite() ) instanceof PartInterface )
{
this.resetCache( true );
this.resetCache();
}
}
else if( te == null || te instanceof TileInterface )
{ {
this.resetCache( true ); this.resetCache( true );
this.resetCache(); this.resetCache();
@@ -351,11 +387,28 @@ public class PartStorageBus extends PartUpgradeable implements IGridTickable, IC
final boolean fullReset = this.resetCacheLogic == 2; final boolean fullReset = this.resetCacheLogic == 2;
this.resetCacheLogic = 0; this.resetCacheLogic = 0;
final IMEInventory<IAEItemStack> in = this.getInternalHandler(); final MEInventoryHandler<IAEItemStack> in = this.getInternalHandler();
IItemList<IAEItemStack> before = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); IItemList<IAEItemStack> before = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList();
if( in != null ) if( in != null )
{ {
before = in.getAvailableItems( before ); if( accessChanged )
{
AccessRestriction currentAccess = (AccessRestriction) ( (ConfigManager) this.getConfigManager() ).getSetting( Settings.ACCESS );
AccessRestriction oldAccess = (AccessRestriction) ( (ConfigManager) this.getConfigManager() ).getOldSetting( Settings.ACCESS );
if( oldAccess.hasPermission( AccessRestriction.READ ) && !currentAccess.hasPermission( AccessRestriction.READ ) )
{
readOncePass = true;
}
in.setBaseAccess( oldAccess );
before = in.getAvailableItems( before );
in.setBaseAccess( currentAccess );
accessChanged = false;
}
else
{
before = in.getAvailableItems( before );
}
} }
this.cached = false; this.cached = false;
@@ -364,11 +417,12 @@ public class PartStorageBus extends PartUpgradeable implements IGridTickable, IC
this.handlerHash = 0; this.handlerHash = 0;
} }
final IMEInventory<IAEItemStack> out = this.getInternalHandler(); final MEInventoryHandler<IAEItemStack> out = this.getInternalHandler();
IItemList<IAEItemStack> after = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList();
if( in != out ) if( in != out )
{ {
IItemList<IAEItemStack> after = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList();
if( out != null ) if( out != null )
{ {
after = out.getAvailableItems( after ); after = out.getAvailableItems( after );
@@ -434,16 +488,6 @@ public class PartStorageBus extends PartUpgradeable implements IGridTickable, IC
return Objects.hash( target, target.getCapability( Capabilities.STORAGE_MONITORABLE_ACCESSOR, targetSide ) ); return Objects.hash( target, target.getCapability( Capabilities.STORAGE_MONITORABLE_ACCESSOR, targetSide ) );
} }
if (ITEM_REPOSITORY_CAPABILITY != null && target.hasCapability( ITEM_REPOSITORY_CAPABILITY, targetSide ))
{
final IItemRepository handlerRepo = target.getCapability( ITEM_REPOSITORY_CAPABILITY, targetSide );
if( handlerRepo != null )
{
return Objects.hash( target, handlerRepo, handlerRepo.getAllItems().size() );
}
}
final IItemHandler itemHandler = target.getCapability( CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, targetSide ); final IItemHandler itemHandler = target.getCapability( CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, targetSide );
if( itemHandler != null ) if( itemHandler != null )
@@ -475,21 +519,19 @@ public class PartStorageBus extends PartUpgradeable implements IGridTickable, IC
this.handlerHash = newHandlerHash; this.handlerHash = newHandlerHash;
this.handler = null; this.handler = null;
if( this.monitor != null )
{
( (IBaseMonitor<IAEItemStack>) monitor ).removeListener( this );
}
this.monitor = null; this.monitor = null;
if( target != null ) if( target != null )
{ {
IMEInventory<IAEItemStack> inv = this.getInventoryWrapper( target ); IMEInventory<IAEItemStack> inv = this.getInventoryWrapper( target );
if( inv instanceof MEMonitorIInventory )
{
final MEMonitorIInventory h = (MEMonitorIInventory) inv;
h.setMode( (StorageFilter) this.getConfigManager().getSetting( Settings.STORAGE_FILTER ) );
}
if( inv instanceof ITickingMonitor ) if( inv instanceof ITickingMonitor )
{ {
this.monitor = (ITickingMonitor) inv; this.monitor = (ITickingMonitor) inv;
this.monitor.setActionSource( new MachineSource( this ) ); this.monitor.setActionSource( mySrc );
this.monitor.setMode( (StorageFilter) this.getConfigManager().getSetting( Settings.STORAGE_FILTER ) ); this.monitor.setMode( (StorageFilter) this.getConfigManager().getSetting( Settings.STORAGE_FILTER ) );
} }
@@ -528,7 +570,10 @@ public class PartStorageBus extends PartUpgradeable implements IGridTickable, IC
if( inv instanceof IBaseMonitor ) if( inv instanceof IBaseMonitor )
{ {
( (IBaseMonitor<IAEItemStack>) inv ).addListener( this, this.handler ); if( ( (AccessRestriction) ( (ConfigManager) this.getConfigManager() ).getSetting( Settings.ACCESS ) ).hasPermission( AccessRestriction.READ ) )
{
( (IBaseMonitor<IAEItemStack>) inv ).addListener( this, this.handler );
}
} }
} }
} }
@@ -557,7 +602,7 @@ public class PartStorageBus extends PartUpgradeable implements IGridTickable, IC
try try
{ {
// force grid to update handlers... // force grid to update handlers...
this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); (( GridStorageCache ) this.getProxy().getGrid().getCache( IStorageGrid.class )).cellUpdate( null );
} }
catch( final GridAccessException e ) catch( final GridAccessException e )
{ {
@@ -598,7 +643,7 @@ public class PartStorageBus extends PartUpgradeable implements IGridTickable, IC
{ {
if( channel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) 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 ) if( out != null )
{ {
return Collections.singletonList( out ); return Collections.singletonList( out );
@@ -19,11 +19,12 @@
package appeng.parts.p2p; package appeng.parts.p2p;
import java.util.List; import java.util.*;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import appeng.me.cache.helpers.TunnelCollection;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.Capability;
@@ -42,6 +43,7 @@ public class PartP2PFEPower extends PartP2PTunnel<PartP2PFEPower>
private static final IEnergyStorage NULL_ENERGY_STORAGE = new NullEnergyStorage(); private static final IEnergyStorage NULL_ENERGY_STORAGE = new NullEnergyStorage();
private final IEnergyStorage inputHandler = new InputEnergyStorage(); private final IEnergyStorage inputHandler = new InputEnergyStorage();
private final IEnergyStorage outputHandler = new OutputEnergyStorage(); private final IEnergyStorage outputHandler = new OutputEnergyStorage();
private final Queue<PartP2PFEPower> outputs = new ArrayDeque<>();
public PartP2PFEPower( ItemStack is ) public PartP2PFEPower( ItemStack is )
{ {
@@ -108,6 +110,8 @@ public class PartP2PFEPower extends PartP2PTunnel<PartP2PFEPower>
private class InputEnergyStorage implements IEnergyStorage private class InputEnergyStorage implements IEnergyStorage
{ {
private boolean iteratingOutputs;
@Override @Override
public int extractEnergy( int maxExtract, boolean simulate ) public int extractEnergy( int maxExtract, boolean simulate )
{ {
@@ -131,8 +135,14 @@ public class PartP2PFEPower extends PartP2PTunnel<PartP2PFEPower>
final int amountPerOutput = maxReceive / outputTunnels; final int amountPerOutput = maxReceive / outputTunnels;
int overflow = amountPerOutput == 0 ? maxReceive : maxReceive % amountPerOutput; int overflow = amountPerOutput == 0 ? maxReceive : maxReceive % amountPerOutput;
for( PartP2PFEPower target : PartP2PFEPower.this.getOutputs() ) if (outputs.isEmpty())
{ {
for ( PartP2PFEPower o : PartP2PFEPower.this.getOutputs())
outputs.add( o );
}
while ( !outputs.isEmpty() ) {
PartP2PFEPower target = outputs.poll();
final IEnergyStorage output = target.getAttachedEnergyStorage(); final IEnergyStorage output = target.getAttachedEnergyStorage();
final int toSend = amountPerOutput + overflow; final int toSend = amountPerOutput + overflow;
final int received = output.receiveEnergy( toSend, simulate ); final int received = output.receiveEnergy( toSend, simulate );
@@ -83,10 +83,19 @@ public class PartP2PFluids extends PartP2PTunnel<PartP2PFluids> implements IFlui
if( this.isOutput() ) if( this.isOutput() )
{ {
final PartP2PFluids in = this.getInput(); try
if( in != null )
{ {
in.onTunnelNetworkChange(); for( PartP2PFluids in : this.getInputs() )
{
if( in != null )
{
in.onTunnelNetworkChange();
}
}
}
catch( GridAccessException e )
{
e.printStackTrace();
} }
} }
} }
@@ -124,13 +133,21 @@ public class PartP2PFluids extends PartP2PTunnel<PartP2PFluids> implements IFlui
{ {
if( !this.isOutput() ) if( !this.isOutput() )
{ {
final PartP2PFluids tun = this.getInput(); try
if( tun != null )
{ {
return ACTIVE_TANK; for( PartP2PFluids tun : this.getInputs() )
{
if( tun != null )
{
return ACTIVE_TANK;
}
}
}
catch( GridAccessException e )
{
e.printStackTrace();
} }
} }
return INACTIVE_TANK; return INACTIVE_TANK;
} }
@@ -74,10 +74,19 @@ public class PartP2PItems extends PartP2PTunnel<PartP2PItems> implements IItemHa
public void onNeighborChanged( IBlockAccess w, BlockPos pos, BlockPos neighbor ) public void onNeighborChanged( IBlockAccess w, BlockPos pos, BlockPos neighbor )
{ {
this.cachedInv = null; this.cachedInv = null;
final PartP2PItems input = this.getInput(); try
if( input != null && this.isOutput() )
{ {
input.onTunnelNetworkChange(); for( PartP2PItems input : this.getInputs() )
{
if( input != null && this.isOutput() )
{
input.onTunnelNetworkChange();
}
}
}
catch( GridAccessException e )
{
e.printStackTrace();
} }
} }
@@ -222,10 +231,19 @@ public class PartP2PItems extends PartP2PTunnel<PartP2PItems> implements IItemHa
} }
else else
{ {
final PartP2PItems input = this.getInput(); try
if( input != null )
{ {
input.getHost().notifyNeighbors(); for( PartP2PItems input : this.getInputs() )
{
if( input != null )
{
input.getHost().notifyNeighbors();
}
}
}
catch( GridAccessException e )
{
e.printStackTrace();
} }
} }
} }
@@ -196,14 +196,23 @@ public class PartP2PLight extends PartP2PTunnel<PartP2PLight> implements IGridTi
{ {
if( this.isOutput() ) if( this.isOutput() )
{ {
final PartP2PLight src = this.getInput(); try
if( src != null && src.getProxy().isActive() )
{ {
this.setLightLevel( src.lastValue ); for( PartP2PLight src : this.getInputs() )
{
if( src != null && src.getProxy().isActive() )
{
this.setLightLevel( src.lastValue );
}
else
{
this.getHost().markForUpdate();
}
}
} }
else catch( GridAccessException e )
{ {
this.getHost().markForUpdate(); e.printStackTrace();
} }
} }
else else
@@ -70,10 +70,19 @@ public class PartP2PRedstone extends PartP2PTunnel<PartP2PRedstone>
{ {
if( this.isOutput() ) if( this.isOutput() )
{ {
final PartP2PRedstone in = this.getInput(); try
if( in != null )
{ {
this.putInput( in.power ); for( PartP2PRedstone in : this.getInputs() )
{
if( in != null )
{
this.putInput( in.power );
}
}
}
catch( GridAccessException e )
{
e.printStackTrace();
} }
} }
} }
@@ -53,6 +53,7 @@ import appeng.me.cache.P2PCache;
import appeng.me.cache.helpers.TunnelCollection; import appeng.me.cache.helpers.TunnelCollection;
import appeng.parts.PartBasicState; import appeng.parts.PartBasicState;
import appeng.util.Platform; import appeng.util.Platform;
import org.lwjgl.input.Keyboard;
public abstract class PartP2PTunnel<T extends PartP2PTunnel> extends PartBasicState public abstract class PartP2PTunnel<T extends PartP2PTunnel> extends PartBasicState
@@ -77,26 +78,13 @@ public abstract class PartP2PTunnel<T extends PartP2PTunnel> extends PartBasicSt
return null; return null;
} }
public T getInput() public TunnelCollection<T> getInputs() throws GridAccessException
{ {
if( this.getFrequency() == 0 ) if( this.getProxy().isActive() && this.getFrequency() != 0 )
{ {
return null; return (TunnelCollection<T>) this.getProxy().getP2P().getInputs( this.getFrequency(), this.getClass() );
} }
return new TunnelCollection( new ArrayList(), this.getClass() );
try
{
final PartP2PTunnel tunnel = this.getProxy().getP2P().getInput( this.getFrequency() );
if( this.getClass().isInstance( tunnel ) )
{
return (T) tunnel;
}
}
catch( final GridAccessException e )
{
// :P
}
return null;
} }
public TunnelCollection<T> getOutputs() throws GridAccessException public TunnelCollection<T> getOutputs() throws GridAccessException
@@ -211,14 +199,28 @@ public abstract class PartP2PTunnel<T extends PartP2PTunnel> extends PartBasicSt
final IPart testPart = ( (IPartItem) newType.getItem() ).createPartFromItemStack( newType ); final IPart testPart = ( (IPartItem) newType.getItem() ).createPartFromItemStack( newType );
if( testPart instanceof PartP2PTunnel ) if( testPart instanceof PartP2PTunnel )
{ {
try
{
this.getProxy().getP2P().removeTunnel( this, this.getFrequency() );
}
catch( GridAccessException e )
{
e.printStackTrace();
}
this.getHost().removePart( this.getSide(), true ); this.getHost().removePart( this.getSide(), true );
final AEPartLocation dir = this.getHost().addPart( newType, this.getSide(), player, hand ); final AEPartLocation dir = this.getHost().addPart( newType, this.getSide(), player, hand );
final IPart newBus = this.getHost().getPart( dir ); final IPart newBus = this.getHost().getPart( dir );
if( newBus instanceof PartP2PTunnel ) if( newBus instanceof PartP2PTunnel )
{ {
final PartP2PTunnel newTunnel = (PartP2PTunnel) newBus; final PartP2PTunnel newTunnel = (PartP2PTunnel) newBus;
newTunnel.setOutput( true ); if( !Keyboard.isKeyDown( Keyboard.KEY_LCONTROL ) && !Keyboard.isKeyDown( Keyboard.KEY_RCONTROL ) )
{
newTunnel.setOutput( true );
}
try try
{ {
@@ -295,7 +297,17 @@ public abstract class PartP2PTunnel<T extends PartP2PTunnel> extends PartBasicSt
final boolean oldOutput = this.isOutput(); final boolean oldOutput = this.isOutput();
final short myFreq = this.getFrequency(); final short myFreq = this.getFrequency();
try
{
this.getProxy().getP2P().removeTunnel( this, this.getFrequency() );
}
catch( GridAccessException e )
{
e.printStackTrace();
}
this.getHost().removePart( this.getSide(), false ); this.getHost().removePart( this.getSide(), false );
final AEPartLocation dir = this.getHost().addPart( newType, this.getSide(), player, hand ); final AEPartLocation dir = this.getHost().addPart( newType, this.getSide(), player, hand );
final IPart newBus = this.getHost().getPart( dir ); final IPart newBus = this.getHost().getPart( dir );
@@ -303,7 +315,6 @@ public abstract class PartP2PTunnel<T extends PartP2PTunnel> extends PartBasicSt
{ {
final PartP2PTunnel newTunnel = (PartP2PTunnel) newBus; final PartP2PTunnel newTunnel = (PartP2PTunnel) newBus;
newTunnel.setOutput( oldOutput ); newTunnel.setOutput( oldOutput );
newTunnel.onTunnelNetworkChange();
try try
{ {
@@ -314,9 +325,10 @@ public abstract class PartP2PTunnel<T extends PartP2PTunnel> extends PartBasicSt
{ {
// :P // :P
} }
newTunnel.onTunnelNetworkChange();
} }
Platform.notifyBlocksOfNeighbors( this.getTile().getWorld(), this.getTile().getPos() );
return true; return true;
} }
} }
@@ -350,9 +362,38 @@ public abstract class PartP2PTunnel<T extends PartP2PTunnel> extends PartBasicSt
if( needsNewFrequency ) if( needsNewFrequency )
{ {
newFreq = this.getProxy().getP2P().newFrequency(); newFreq = this.getProxy().getP2P().newFrequency();
}
this.getProxy().getP2P().updateFreq( this, newFreq ); final ItemStack newType = this.getHost().getPart( this.getSide() ).getItemStack( PartItemStack.WRENCH );
try
{
this.getProxy().getP2P().removeTunnel( this, this.getFrequency() );
}
catch( GridAccessException e )
{
e.printStackTrace();
}
this.getHost().removePart( this.getSide(), false );
final AEPartLocation dir = this.getHost().addPart( newType, this.getSide(), player, hand );
final IPart newBus = this.getHost().getPart( dir );
if( newBus instanceof PartP2PTunnel )
{
final PartP2PTunnel newTunnel = (PartP2PTunnel) newBus;
newTunnel.setOutput( false );
newTunnel.getProxy().getP2P().updateFreq( newTunnel, newFreq );
newTunnel.onTunnelNetworkChange();
}
}
else
{
this.getProxy().getP2P().updateFreq( this, newFreq );
this.onTunnelNetworkChange();
}
Platform.notifyBlocksOfNeighbors( this.getTile().getWorld(), this.getTile().getPos() );
} }
catch( final GridAccessException e ) catch( final GridAccessException e )
{ {
@@ -365,10 +406,17 @@ public abstract class PartP2PTunnel<T extends PartP2PTunnel> extends PartBasicSt
final String type = p2pItem.getUnlocalizedName(); final String type = p2pItem.getUnlocalizedName();
p2pItem.writeToNBT( data ); p2pItem.writeToNBT( data );
data.setShort( "freq", this.getFrequency() ); if( needsNewFrequency )
{
data.setShort( "freq", newFreq );
}
else
{
data.setShort( "freq", this.getFrequency() );
}
final AEColor[] colors = Platform.p2p().toColors( this.getFrequency() ); final AEColor[] colors = Platform.p2p().toColors( this.getFrequency() );
final int[] colorCode = new int[] { final int[] colorCode = new int[]{
colors[0].ordinal(), colors[0].ordinal(), colors[1].ordinal(), colors[1].ordinal(), colors[0].ordinal(), colors[0].ordinal(), colors[1].ordinal(), colors[1].ordinal(),
colors[2].ordinal(), colors[2].ordinal(), colors[3].ordinal(), colors[3].ordinal(), colors[2].ordinal(), colors[2].ordinal(), colors[3].ordinal(), colors[3].ordinal(),
}; };
@@ -395,7 +443,6 @@ public abstract class PartP2PTunnel<T extends PartP2PTunnel> extends PartBasicSt
public void onTunnelNetworkChange() public void onTunnelNetworkChange()
{ {
} }
protected void queueTunnelDrain( final PowerUnits unit, final double f ) protected void queueTunnelDrain( final PowerUnits unit, final double f )
@@ -21,10 +21,14 @@ package appeng.parts.reporting;
import java.io.IOException; 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.networking.security.IActionSource;
import appeng.api.storage.channels.IFluidStorageChannel; import appeng.api.storage.channels.IFluidStorageChannel;
import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IAEFluidStack;
import appeng.api.storage.data.IItemList;
import appeng.fluids.util.AEFluidStack; import appeng.fluids.util.AEFluidStack;
import appeng.util.item.AEStack;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.GlStateManager;
@@ -43,7 +47,6 @@ import net.minecraftforge.fml.relauncher.SideOnly;
import appeng.api.AEApi; import appeng.api.AEApi;
import appeng.api.implementations.parts.IPartStorageMonitor; import appeng.api.implementations.parts.IPartStorageMonitor;
import appeng.api.networking.security.IActionSource;
import appeng.api.networking.storage.IStackWatcher; import appeng.api.networking.storage.IStackWatcher;
import appeng.api.networking.storage.IStackWatcherHost; import appeng.api.networking.storage.IStackWatcherHost;
import appeng.api.parts.IPartModel; import appeng.api.parts.IPartModel;
@@ -52,7 +55,6 @@ import appeng.api.storage.IStorageChannel;
import appeng.api.storage.channels.IItemStorageChannel; import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IAEStack;
import appeng.api.storage.data.IItemList;
import appeng.client.render.TesrRenderHelper; import appeng.client.render.TesrRenderHelper;
import appeng.core.localization.PlayerMessages; import appeng.core.localization.PlayerMessages;
import appeng.helpers.Reflected; import appeng.helpers.Reflected;
@@ -80,6 +82,7 @@ public abstract class AbstractPartMonitor extends AbstractPartDisplay implements
private IAEItemStack configuredItem; private IAEItemStack configuredItem;
private IAEFluidStack configuredFluid; private IAEFluidStack configuredFluid;
private long configuredAmount;
private String lastHumanReadableText; private String lastHumanReadableText;
private boolean isLocked; private boolean isLocked;
private IStackWatcher myWatcher; private IStackWatcher myWatcher;
@@ -206,14 +209,21 @@ public abstract class AbstractPartMonitor extends AbstractPartDisplay implements
fluidInTank = fluidHandlerItem.drain( Integer.MAX_VALUE, false ); fluidInTank = fluidHandlerItem.drain( Integer.MAX_VALUE, false );
} }
if (fluidInTank == null) if( fluidInTank == null )
{ {
this.configuredFluid = null; this.configuredFluid = null;
this.configuredItem = AEItemStack.fromItemStack( eq ); if( !eq.isEmpty() )
{
this.configuredItem = AEItemStack.fromItemStack( eq ).setStackSize( 0 );
}
else
{
this.configuredItem = null;
}
} }
else if( fluidInTank.amount > 0 ) else if( fluidInTank.amount > 0 )
{ {
this.configuredFluid = AEFluidStack.fromFluidStack( fluidInTank ); this.configuredFluid = AEFluidStack.fromFluidStack( fluidInTank ).setStackSize( 0 );
this.configuredItem = null; this.configuredItem = null;
} }
@@ -297,30 +307,31 @@ public abstract class AbstractPartMonitor extends AbstractPartDisplay implements
private <T extends IAEStack<T>> void updateReportingValue ( final IMEMonitor<T> monitor ) private <T extends IAEStack<T>> void updateReportingValue ( final IMEMonitor<T> monitor )
{ {
if( this.configuredItem != null) if( this.configuredItem != null)
{ {
final IAEItemStack result = (IAEItemStack) monitor.getStorageList().findPrecise( (T) this.configuredItem ); final IAEItemStack result = (IAEItemStack) monitor.getStorageList().findPrecise( (T) this.configuredItem );
if( result == null ) if( result == null )
{ {
this.configuredItem.setStackSize( 0 ); this.configuredAmount = 0;
} }
else else
{ {
this.configuredItem.setStackSize( result.getStackSize() ); this.configuredAmount = result.getStackSize();
} }
this.configuredItem.setStackSize( this.configuredAmount );
} }
else if( this.configuredFluid != null) else if( this.configuredFluid != null)
{ {
final IAEFluidStack result = (IAEFluidStack) monitor.getStorageList().findPrecise( (T) this.configuredFluid ); final IAEFluidStack result = (IAEFluidStack) monitor.getStorageList().findPrecise( (T) this.configuredFluid );
if( result == null ) if( result == null )
{ {
this.configuredFluid.setStackSize( 0 ); this.configuredAmount = 0;
} }
else else
{ {
this.configuredFluid.setStackSize( result.getStackSize() ); this.configuredAmount = result.getStackSize();
} }
this.configuredFluid.setStackSize( this.configuredAmount );
} }
} }
@@ -385,49 +396,38 @@ public abstract class AbstractPartMonitor extends AbstractPartDisplay implements
this.configureWatchers(); this.configureWatchers();
} }
@Override @MENetworkEventSubscribe
public void onStackChange( final IItemList o, final IAEStack fullStack, final IAEStack diffStack, final IActionSource src, final IStorageChannel chan ) public void powerStatusChange( final MENetworkPowerStatusChange ev )
{ {
if( this.getProxy().isPowered() )
{
this.configureWatchers();
}
}
@MENetworkEventSubscribe
public void channelChanged( final MENetworkChannelsChanged c )
{
if( this.getProxy().isPowered() )
{
this.configureWatchers();
}
}
@Override
public void onStackChange( IItemList<?> o, IAEStack<?> fullStack, IAEStack<?> diffStack, IActionSource src, IStorageChannel<?> chan )
{
this.configuredAmount = fullStack.getStackSize();
if( this.configuredItem != null ) if( this.configuredItem != null )
{ {
if( fullStack == null ) this.configuredItem.setStackSize( this.configuredAmount );
{
this.configuredItem.setStackSize( 0 );
}
else
{
this.configuredItem.setStackSize( fullStack.getStackSize() );
}
final long stackSize = this.configuredItem.getStackSize();
final String humanReadableText = NUMBER_CONVERTER.toWideReadableForm( stackSize );
if( !humanReadableText.equals( this.lastHumanReadableText ) )
{
this.lastHumanReadableText = humanReadableText;
this.getHost().markForUpdate();
}
} }
else if( this.configuredFluid != null ) else if( this.configuredFluid != null )
{ {
if( fullStack == null ) this.configuredFluid.setStackSize( this.configuredAmount );
{
this.configuredFluid.setStackSize( 0 );
}
else
{
this.configuredFluid.setStackSize( fullStack.getStackSize() );
}
final long stackSize = this.configuredFluid.getStackSize() / 1000;
final String humanReadableText = NUMBER_CONVERTER.toWideReadableForm( stackSize ) + "B";
if( !humanReadableText.equals( this.lastHumanReadableText ) )
{
this.lastHumanReadableText = humanReadableText;
this.getHost().markForUpdate();
}
} }
this.getHost().markForUpdate();
} }
@Override @Override
@@ -137,14 +137,10 @@ public class PartConversionMonitor extends AbstractPartMonitor
{ {
this.insertItem( player, hand, false ); this.insertItem( player, hand, false );
} }
} }
//If its a fluid container, grab its fluidstack. if its empty pass its itemstack; //If its a fluid container, grab its fluidstack. if its empty pass its itemstack;
if (eq.isEmpty()){
return super.onPartActivate( player, hand, pos );
}
if( fluidInTank != null && fluidInTank.amount > 0 ) if( fluidInTank != null && fluidInTank.amount > 0 )
{ {
if( getDisplayed() instanceof IAEItemStack || getDisplayed() == null ) if( getDisplayed() instanceof IAEItemStack || getDisplayed() == null )
@@ -155,23 +151,16 @@ public class PartConversionMonitor extends AbstractPartMonitor
{ {
this.drainFluidContainer( player, hand ); this.drainFluidContainer( player, hand );
} }
else { else
{
return super.onPartActivate( player, hand, pos ); return super.onPartActivate( player, hand, pos );
} }
} }
else else if( this.getDisplayed() != null && this.getDisplayed().equals( player.getHeldItem( hand ) ) )
{ {
if( getDisplayed() instanceof IAEFluidStack || getDisplayed() == null ) this.insertItem( player, hand, false );
{
return super.onPartActivate( player, hand, pos );
}
if( ( (IAEItemStack) this.getDisplayed() ).equals( eq ) )
{
this.insertItem( player, hand, false );
}
} }
return super.onPartActivate( player, hand, pos );
return true;
} }
@Override @Override
@@ -192,7 +181,6 @@ public class PartConversionMonitor extends AbstractPartMonitor
return false; return false;
} }
ItemStack eq = player.getHeldItem( hand );
if( this.getDisplayed() != null && this.getDisplayed() instanceof IAEItemStack ) if( this.getDisplayed() != null && this.getDisplayed() instanceof IAEItemStack )
{ {
this.extractItem( player, ( (IAEItemStack) this.getDisplayed() ).getDefinition().getMaxStackSize() ); this.extractItem( player, ( (IAEItemStack) this.getDisplayed() ).getDefinition().getMaxStackSize() );
@@ -282,7 +270,7 @@ public class PartConversionMonitor extends AbstractPartMonitor
{ {
if (!(this.getDisplayed() instanceof IAEItemStack)) if (!(this.getDisplayed() instanceof IAEItemStack))
return; return;
final IAEItemStack input = (IAEItemStack) this.getDisplayed(); final IAEItemStack input = (IAEItemStack) this.getDisplayed().copy();
if( input != null ) if( input != null )
{ {
try try
@@ -123,7 +123,7 @@ public class AppEngInternalInventory extends ItemStackHandler implements Iterabl
ItemStack oldStack = this.previousStack; ItemStack oldStack = this.previousStack;
InvOperation op = InvOperation.SET; InvOperation op = InvOperation.SET;
if( newStack.isEmpty() || oldStack.isEmpty() || ItemStack.areItemsEqual( newStack, oldStack ) ) if( newStack.isEmpty() || oldStack.isEmpty() || ( oldStack.getCount() < oldStack.getMaxStackSize() && oldStack.getCount() < this.getSlotLimit( slot ) && ItemStack.areItemsEqual( newStack, oldStack ) ) )
{ {
if( newStack.getCount() > oldStack.getCount() ) if( newStack.getCount() > oldStack.getCount() )
{ {
@@ -206,7 +206,7 @@ public class AppEngInternalInventory extends ItemStackHandler implements Iterabl
this.enableClientEvents = enableClientEvents; this.enableClientEvents = enableClientEvents;
} }
private IAEAppEngInventory getTileEntity() public IAEAppEngInventory getTileEntity()
{ {
return this.te; return this.te;
} }
@@ -164,6 +164,7 @@ public class TileInterface extends AENetworkInvTile implements IGridTickable, II
super.onReady(); super.onReady();
this.duality.initialize(); this.duality.initialize();
this.getProxy().setIdlePowerUsage( Math.pow( 4, ( this.getInstalledUpgrades( Upgrades.PATTERN_EXPANSION ) ) ) );
} }
@Override @Override
@@ -155,7 +155,7 @@ public class TileEnergyCell extends AENetworkTile implements IAEPowerStorage
return 0; return 0;
} }
if( this.internalCurrentPower < 0.01 && amt > 0.01 ) if( this.internalCurrentPower < 0.01 && amt > 0 )
{ {
this.getProxy().getNode().getGrid().postEvent( new MENetworkPowerStorage( this, PowerEventType.PROVIDE_POWER ) ); this.getProxy().getNode().getGrid().postEvent( new MENetworkPowerStorage( this, PowerEventType.PROVIDE_POWER ) );
} }
@@ -217,7 +217,7 @@ public class TileEnergyCell extends AENetworkTile implements IAEPowerStorage
final boolean wasFull = this.internalCurrentPower >= this.getInternalMaxPower() - 0.001; final boolean wasFull = this.internalCurrentPower >= this.getInternalMaxPower() - 0.001;
if( wasFull && amt > 0.001 ) if( wasFull && amt > 0 )
{ {
try try
{ {
@@ -26,6 +26,8 @@ import java.util.List;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import appeng.me.storage.BasicCellInventoryHandler;
import appeng.me.storage.CreativeCellInventory;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
@@ -494,12 +496,14 @@ public class TileChest extends AENetworkPowerTile implements IMEChest, ITerminal
try try
{ {
this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() );
final IStorageGrid gs = this.getProxy().getStorage(); if( this.getProxy().isActive() )
Platform.postChanges( gs, removed, added, this.mySrc ); {
final IStorageGrid gs = this.getProxy().getStorage();
Platform.postChanges( gs, removed, added, this.mySrc );
}
} }
catch( final GridAccessException ignored ) catch( final GridAccessException ignored )
{ {
} }
// update the neighbors // update the neighbors
@@ -554,14 +558,10 @@ public class TileChest extends AENetworkPowerTile implements IMEChest, ITerminal
@Override @Override
public List<IMEInventoryHandler> getCellArray( final IStorageChannel channel ) public List<IMEInventoryHandler> getCellArray( final IStorageChannel channel )
{ {
if( this.getProxy().isActive() ) this.updateHandler();
if( this.cellHandler != null && this.cellHandler.getChannel() == channel )
{ {
this.updateHandler(); return Collections.singletonList( this.cellHandler );
if( this.cellHandler != null && this.cellHandler.getChannel() == channel )
{
return Collections.singletonList( this.cellHandler );
}
} }
return Collections.emptyList(); return Collections.emptyList();
} }
@@ -692,21 +692,16 @@ public class TileChest extends AENetworkPowerTile implements IMEChest, ITerminal
@Override @Override
public void postChange( final IBaseMonitor<T> monitor, final Iterable<T> change, final IActionSource source ) public void postChange( final IBaseMonitor<T> monitor, final Iterable<T> change, final IActionSource source )
{ {
if( source == TileChest.this.mySrc || source.machine().map( machine -> machine == TileChest.this ).orElse( false ) ) try
{ {
try if( TileChest.this.getProxy().isActive() )
{ {
if( TileChest.this.getProxy().isActive() ) TileChest.this.getProxy().getStorage().postAlterationOfStoredItems( this.chan, change, TileChest.this.mySrc );
{
TileChest.this.getProxy().getStorage().postAlterationOfStoredItems( this.chan, change, TileChest.this.mySrc );
}
}
catch( final GridAccessException e )
{
// :(
} }
} catch ( final GridAccessException e )
{
// :(
} }
TileChest.this.blinkCell( 0 ); TileChest.this.blinkCell( 0 );
} }
@@ -742,7 +737,15 @@ public class TileChest extends AENetworkPowerTile implements IMEChest, ITerminal
{ {
return input; return input;
} }
return super.injectItems( input, mode, src ); T injected = super.injectItems( input, mode, src );
if (mode == Actionable.MODULATE && ( injected == null || injected.getStackSize() != input.getStackSize() ))
{
if( TileChest.this.getProxy().isActive() && this.getInternalHandler().getCellInv() != null )
{
TileChest.this.cellHandler.postChangesToListeners(Collections.singletonList( input.copy().setStackSize( input.getStackSize() - ( injected == null ? 0 : injected.getStackSize() ) ) ), TileChest.this.mySrc );
}
}
return injected;
} }
private boolean securityCheck( final EntityPlayer player, final SecurityPermissions requiredPermission ) private boolean securityCheck( final EntityPlayer player, final SecurityPermissions requiredPermission )
@@ -786,7 +789,15 @@ public class TileChest extends AENetworkPowerTile implements IMEChest, ITerminal
{ {
return null; return null;
} }
return super.extractItems( request, mode, src ); T extracted = super.extractItems( request, mode, src );
if( mode == Actionable.MODULATE && extracted != null )
{
if( TileChest.this.getProxy().isActive() && this.getInternalHandler().getCellInv() != null )
{
TileChest.this.cellHandler.postChangesToListeners(Collections.singletonList( request.copy().setStackSize( -extracted.getStackSize() ) ), TileChest.this.mySrc );
}
}
return extracted;
} }
} }
@@ -264,9 +264,11 @@ public class TileDrive extends AENetworkInvTile implements IChestOrDrive, IPrior
try try
{ {
this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() );
if( this.getProxy().isActive() )
final IStorageGrid gs = this.getProxy().getStorage(); {
Platform.postChanges( gs, removed, added, this.mySrc ); final IStorageGrid gs = this.getProxy().getStorage();
Platform.postChanges( gs, removed, added, this.mySrc );
}
} }
catch( final GridAccessException ignored ) catch( final GridAccessException ignored )
{ {
@@ -334,13 +336,8 @@ public class TileDrive extends AENetworkInvTile implements IChestOrDrive, IPrior
@Override @Override
public List<IMEInventoryHandler> getCellArray( final IStorageChannel channel ) public List<IMEInventoryHandler> getCellArray( final IStorageChannel channel )
{ {
if( this.getProxy().isActive() ) this.updateState();
{ return this.inventoryHandlers.get( channel );
this.updateState();
return this.inventoryHandlers.get( channel );
}
return Collections.emptyList();
} }
@Override @Override
@@ -418,13 +418,16 @@ public class TileIOPort extends AENetworkInvTile implements IUpgradeableHost, IC
if( possible > 0 ) if( possible > 0 )
{ {
possible = Math.min( possible, itemsToMove ); IAEStack injectable = s.copy();
s.setStackSize( possible );
final IAEStack extracted = src.extractItems( s, Actionable.MODULATE, this.mySrc ); possible = Math.min( possible, itemsToMove );
injectable.setStackSize( possible );
final IAEStack extracted = src.extractItems( injectable, Actionable.MODULATE, this.mySrc );
if( extracted != null ) if( extracted != null )
{ {
possible = extracted.getStackSize(); possible = extracted.getStackSize();
extracted.setCraftable( false );
final IAEStack failed = Platform.poweredInsert( energy, destination, extracted, this.mySrc ); final IAEStack failed = Platform.poweredInsert( energy, destination, extracted, this.mySrc );
if( failed != null ) if( failed != null )
@@ -499,8 +502,9 @@ public class TileIOPort extends AENetworkInvTile implements IUpgradeableHost, IC
final IAEStack test = myList.getFirstItem(); final IAEStack test = myList.getFirstItem();
if( test != null ) if( test != null )
{ {
test.setStackSize( 1 ); IAEStack testCopy = test.copy();
return src.injectItems( test, Actionable.SIMULATE, this.mySrc ) != null; testCopy.setStackSize( 1 );
return src.injectItems( testCopy, Actionable.SIMULATE, this.mySrc ) != null;
} }
return false; return false;
} }
@@ -36,6 +36,7 @@ public final class ConfigManager implements IConfigManager
{ {
private final Map<Settings, Enum<?>> settings = new EnumMap<>( Settings.class ); private final Map<Settings, Enum<?>> settings = new EnumMap<>( Settings.class );
private final IConfigManagerHost target; private final IConfigManagerHost target;
private Map<Settings, Enum<?>> oldSettings = new EnumMap<>( Settings.class );
public ConfigManager( final IConfigManagerHost tile ) public ConfigManager( final IConfigManagerHost tile )
{ {
@@ -72,10 +73,15 @@ public final class ConfigManager implements IConfigManager
{ {
final Enum<?> oldValue = this.getSetting( settingName ); final Enum<?> oldValue = this.getSetting( settingName );
this.settings.put( settingName, newValue ); this.settings.put( settingName, newValue );
this.oldSettings.put( settingName, oldValue );
this.target.updateSetting( this, settingName, newValue ); this.target.updateSetting( this, settingName, newValue );
return oldValue; return oldValue;
} }
public Enum<?> getOldSetting(final Settings settingName){
return this.oldSettings.get( settingName );
}
/** /**
* save all settings using config manager. * save all settings using config manager.
* *
+7 -5
View File
@@ -1246,18 +1246,20 @@ public class Platform
if( itemToAdd < input.getStackSize() ) if( itemToAdd < input.getStackSize() )
{ {
final long original = input.getStackSize(); final long original = input.getStackSize();
final T leftover = input.copy();
final T split = input.copy(); final T split = input.copy();
split.decStackSize( itemToAdd );
input.setStackSize( itemToAdd ); leftover.decStackSize(itemToAdd);
split.add( cell.injectItems( input, Actionable.MODULATE, src ) ); split.setStackSize(itemToAdd);
leftover.add(cell.injectItems(split, Actionable.MODULATE, src));
src.player().ifPresent( player -> src.player().ifPresent( player ->
{ {
final long diff = original - split.getStackSize(); final long diff = original - leftover.getStackSize();
Stats.ItemsInserted.addToPlayer( player, (int) diff ); Stats.ItemsInserted.addToPlayer( player, (int) diff );
} ); } );
return split; return leftover;
} }
final T ret = cell.injectItems( input, Actionable.MODULATE, src ); final T ret = cell.injectItems( input, Actionable.MODULATE, src );
@@ -56,6 +56,6 @@ public class ReadOnlyCollection<T> implements IReadOnlyCollection<T>
@Override @Override
public boolean contains( final Object node ) public boolean contains( final Object node )
{ {
return this.c.contains( node ); return this.c.contains( (T) node );
} }
} }
@@ -52,7 +52,7 @@ public class ItemHandlerIterator implements Iterator<ItemSlot>
{ {
throw new NoSuchElementException(); throw new NoSuchElementException();
} }
this.itemSlot.setExtractable( !this.itemHandler.extractItem( this.slot, 1, true ).isEmpty() ); this.itemSlot.setExtractable( !this.itemHandler.extractItem( this.slot, Integer.MAX_VALUE, true ).isEmpty() );
this.itemSlot.setItemStack( this.itemHandler.getStackInSlot( this.slot ) ); this.itemSlot.setItemStack( this.itemHandler.getStackInSlot( this.slot ) );
this.itemSlot.setSlot( this.slot ); this.itemSlot.setSlot( this.slot );
this.slot++; this.slot++;
+227 -281
View File
@@ -1,6 +1,6 @@
/* /*
* This file is part of Applied Energistics 2. * This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved. * Copyright (c) 2013 - 2020, AlgorithmX2, All rights reserved.
* *
* Applied Energistics 2 is free software: you can redistribute it and/or modify * Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by * it under the terms of the GNU Lesser General Public License as published by
@@ -18,7 +18,6 @@
package appeng.util.item; package appeng.util.item;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
@@ -27,347 +26,294 @@ import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.network.ByteBufUtils; import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.fml.relauncher.SideOnly;
import net.minecraftforge.items.ItemHandlerHelper; import net.minecraftforge.items.ItemHandlerHelper;
import appeng.api.AEApi;
import appeng.api.config.FuzzyMode; import appeng.api.config.FuzzyMode;
import appeng.api.storage.IStorageChannel; import appeng.api.storage.IStorageChannel;
import appeng.api.storage.channels.IItemStorageChannel; import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IAEItemStack;
import appeng.core.Api;
import appeng.util.Platform; import appeng.util.Platform;
public final class AEItemStack extends AEStack<IAEItemStack> implements IAEItemStack {
private static final String NBT_STACKSIZE = "Cnt";
private static final String NBT_REQUESTABLE = "Req";
private static final String NBT_CRAFTABLE = "Craft";
public final class AEItemStack extends AEStack<IAEItemStack> implements IAEItemStack private final AESharedItemStack sharedStack;
{ private Optional<OreReference> oreReference;
private AESharedItemStack sharedStack;
private Optional<OreReference> oreReference;
@SideOnly( Side.CLIENT ) @SideOnly(Side.CLIENT)
private String displayName; private String displayName;
@SideOnly( Side.CLIENT ) @SideOnly(Side.CLIENT)
private List<String> tooltip; private List<String> tooltip;
@SideOnly( Side.CLIENT )
private ResourceLocation uniqueID;
private AEItemStack( final AEItemStack is ) private AEItemStack(final AEItemStack is) {
{ this.setStackSize(is.getStackSize());
this.setStackSize( is.getStackSize() ); this.setCraftable(is.isCraftable());
this.setCraftable( is.isCraftable() ); this.setCountRequestable(is.getCountRequestable());
this.setCountRequestable( is.getCountRequestable() ); this.sharedStack = is.sharedStack;
this.sharedStack = is.sharedStack; this.oreReference = is.oreReference;
this.oreReference = is.oreReference; }
}
private AEItemStack( final AESharedItemStack is, long size ) private AEItemStack(final AESharedItemStack is, long size) {
{ this.sharedStack = is;
this.sharedStack = is; this.setStackSize(size);
this.setStackSize( size ); this.setCraftable(false);
this.setCraftable( false ); this.setCountRequestable(0);
this.setCountRequestable( 0 ); this.oreReference = OreHelper.INSTANCE.getOre( is.getDefinition() );
this.oreReference = OreHelper.INSTANCE.getOre( is.getDefinition() ); }
}
@Nullable @Nullable
public static AEItemStack fromItemStack( @Nonnull final ItemStack stack ) public static AEItemStack fromItemStack(@Nonnull final ItemStack stack) {
{ if (stack.isEmpty()) {
if( stack.isEmpty() ) return null;
{ }
return null;
}
return new AEItemStack( AEItemStackRegistry.getRegisteredStack( stack ), stack.getCount() ); return new AEItemStack(AEItemStackRegistry.getRegisteredStack(stack), stack.getCount());
} }
public static IAEItemStack fromNBT( final NBTTagCompound i ) public static IAEItemStack fromNBT( final NBTTagCompound i )
{ {
if( i == null ) if( i == null )
{ {
return null; return null;
} }
final ItemStack itemstack = new ItemStack( i ); final ItemStack itemstack = new ItemStack( i );
if( itemstack.isEmpty() ) if( itemstack.isEmpty() )
{ {
return null; return null;
} }
final AEItemStack item = AEItemStack.fromItemStack( itemstack ); final AEItemStack item = AEItemStack.fromItemStack( itemstack );
item.setStackSize( i.getLong( "Cnt" ) );
item.setCountRequestable( i.getLong( "Req" ) );
item.setCraftable( i.getBoolean( "Craft" ) );
return item;
}
@Override item.setStackSize(i.getLong(NBT_STACKSIZE));
public void writeToNBT( final NBTTagCompound i ) item.setCountRequestable(i.getLong(NBT_REQUESTABLE));
{ item.setCraftable(i.getBoolean(NBT_CRAFTABLE));
this.getDefinition().writeToNBT( i ); return item;
i.setLong( "Cnt", this.getStackSize() ); }
i.setLong( "Req", this.getCountRequestable() );
i.setBoolean( "Craft", this.isCraftable() );
}
public static AEItemStack fromPacket( final ByteBuf data ) @Override
{ public void writeToNBT(final NBTTagCompound i) {
final byte mask = data.readByte(); this.getDefinition().writeToNBT( i );
final byte stackType = (byte) ( ( mask & 0x0C ) >> 2 );
final byte countReqType = (byte) ( ( mask & 0x30 ) >> 4 );
final boolean isCraftable = ( mask & 0x40 ) > 0;
final ItemStack itemstack = new ItemStack( ByteBufUtils.readTag( data ) ); i.setLong(NBT_STACKSIZE, this.getStackSize());
final long stackSize = getPacketValue( stackType, data ); i.setLong(NBT_REQUESTABLE, this.getCountRequestable());
final long countRequestable = getPacketValue( countReqType, data ); i.setBoolean(NBT_CRAFTABLE, this.isCraftable());
}
if( itemstack.isEmpty() ) public static AEItemStack fromPacket( final ByteBuf data )
{ {
return null; final byte mask = data.readByte();
} final byte stackType = (byte) ( ( mask & 0x0C ) >> 2 );
final byte countReqType = (byte) ( ( mask & 0x30 ) >> 4 );
final boolean isCraftable = ( mask & 0x40 ) > 0;
final AEItemStack item = new AEItemStack( AEItemStackRegistry.getRegisteredStack( itemstack ), stackSize ); final ItemStack itemstack = new ItemStack( ByteBufUtils.readTag( data ) );
item.setCountRequestable( countRequestable ); final long stackSize = getPacketValue( stackType, data );
item.setCraftable( isCraftable ); final long countRequestable = getPacketValue( countReqType, data );
return item;
}
@Override if( itemstack.isEmpty() )
public void writeToPacket( final ByteBuf i ) {
{ return null;
final byte mask = (byte) ( ( this.getType( this.getStackSize() ) << 2 ) | ( this }
.getType( this.getCountRequestable() ) << 4 ) | ( (byte) ( this.isCraftable() ? 1 : 0 ) << 6 ) | ( this.hasTagCompound() ? 1 : 0 ) << 7 );
i.writeByte( mask ); final AEItemStack item = new AEItemStack( AEItemStackRegistry.getRegisteredStack( itemstack ), stackSize );
ByteBufUtils.writeTag( i, this.getDefinition().serializeNBT() ); item.setCountRequestable( countRequestable );
this.putPacketValue( i, this.getStackSize() ); item.setCraftable( isCraftable );
this.putPacketValue( i, this.getCountRequestable() ); return item;
} }
@Override @Override
public void add( final IAEItemStack option ) public void writeToPacket( final ByteBuf i )
{ {
if( option == null ) final byte mask = (byte) ( ( this.getType( this.getStackSize() ) << 2 ) | ( this
{ .getType( this.getCountRequestable() ) << 4 ) | ( (byte) ( this.isCraftable() ? 1 : 0 ) << 6 ) | ( this.hasTagCompound() ? 1 : 0 ) << 7 );
return;
}
this.incStackSize( option.getStackSize() ); i.writeByte( mask );
this.setCountRequestable( this.getCountRequestable() + option.getCountRequestable() ); ByteBufUtils.writeTag( i, this.getDefinition().serializeNBT() );
this.setCraftable( this.isCraftable() || option.isCraftable() ); this.putPacketValue( i, this.getStackSize() );
} this.putPacketValue( i, this.getCountRequestable() );
}
@Override @Override
public boolean fuzzyComparison( final IAEItemStack other, final FuzzyMode mode ) public void add(final IAEItemStack option) {
{ if (option == null) {
if( mode == FuzzyMode.IGNORE_ALL && OreHelper.INSTANCE.sameOre( this, other ) ) return;
{ }
return true;
}
final ItemStack itemStack = this.getDefinition(); this.incStackSize(option.getStackSize());
final ItemStack otherStack = other.getDefinition(); this.setCountRequestable(this.getCountRequestable() + option.getCountRequestable());
this.setCraftable(this.isCraftable() || option.isCraftable());
}
return this.fuzzyItemStackComparison( itemStack, otherStack, mode ); @Override
} public boolean fuzzyComparison(final IAEItemStack other, final FuzzyMode mode) {
final ItemStack itemStack = this.getDefinition();
final ItemStack otherStack = other.getDefinition();
@Override return this.fuzzyItemStackComparison(itemStack, otherStack, mode);
public IAEItemStack copy() }
{
return new AEItemStack( this );
}
@Override @Override
public boolean isItem() public IAEItemStack copy() {
{ return new AEItemStack(this);
return true; }
}
@Override @Override
public boolean isFluid() public boolean isItem()
{ {
return false; return true;
} }
@Override @Override
public IStorageChannel<IAEItemStack> getChannel() public boolean isFluid()
{ {
return AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ); return false;
} }
@Override @Override
public ItemStack createItemStack() public IStorageChannel<IAEItemStack> getChannel() {
{ return Api.INSTANCE.storage().getStorageChannel(IItemStorageChannel.class);
return ItemHandlerHelper.copyStackWithSize( this.getDefinition(), (int) Math.min( Integer.MAX_VALUE, this.getStackSize() ) ); }
}
@Override @Override
public Item getItem() public ItemStack createItemStack() {
{ return ItemHandlerHelper.copyStackWithSize(this.getDefinition(),
return this.getDefinition().getItem(); (int) Math.min(Integer.MAX_VALUE, this.getStackSize()));
} }
@Override @Override
public int getItemDamage() public Item getItem() {
{ return this.getDefinition().getItem();
return this.sharedStack.getItemDamage(); }
}
@Override @Override
public boolean sameOre( final IAEItemStack is ) public int getItemDamage() {
{ return this.sharedStack.getItemDamage();
return OreHelper.INSTANCE.sameOre( this, is ); }
}
@Override @Override
public boolean isSameType( final IAEItemStack otherStack ) public boolean sameOre( final IAEItemStack is )
{ {
if( otherStack == null ) return OreHelper.INSTANCE.sameOre( this, is );
{ }
return false;
}
return Objects.equals( this.sharedStack, ( (AEItemStack) otherStack ).sharedStack ); @Override
} public boolean isSameType(final IAEItemStack otherStack) {
if (otherStack == null) {
return false;
}
@Override return Objects.equals(this.sharedStack, ((AEItemStack) otherStack).sharedStack);
public boolean isSameType( final ItemStack otherStack ) }
{
if( otherStack.isEmpty() )
{
return false;
}
int oldSize = otherStack.getCount();
otherStack.setCount( 1 ); @Override
boolean ret = ItemStack.areItemStacksEqual( this.getDefinition(), otherStack ); public boolean isSameType(final ItemStack otherStack) {
otherStack.setCount( oldSize ); if (otherStack.isEmpty()) {
return false;
}
int oldSize = otherStack.getCount();
return ret; otherStack.setCount(1);
} boolean ret = ItemStack.areItemStacksEqual(this.getDefinition(), otherStack);
otherStack.setCount(oldSize);
@Override return ret;
public int hashCode() }
{
return this.sharedStack.hashCode();
}
@Override @Override
public boolean equals( final Object ia ) public int hashCode() {
{ return this.sharedStack.hashCode();
if( ia instanceof AEItemStack ) }
{
return this.isSameType( (AEItemStack) ia );
}
else if( ia instanceof ItemStack )
{
return this.isSameType( (ItemStack) ia );
}
return false;
}
@Override @Override
public String toString() public boolean equals(final Object ia) {
{ if (ia instanceof AEItemStack) {
return this.getStackSize() + "x" + this.getDefinition().getItem().getUnlocalizedName() + "@" + this.getDefinition().getItemDamage(); return this.isSameType((AEItemStack) ia);
} } else if (ia instanceof ItemStack) {
// this actually breaks the equals contract (being equals to unrelated classes)
return equals((ItemStack) ia);
}
return false;
}
@SideOnly( Side.CLIENT ) @Override
public List<String> getToolTip() public boolean equals(final ItemStack is) {
{ return this.isSameType(is);
if( this.tooltip == null ) }
{
this.tooltip = Platform.getTooltip( this.asItemStackRepresentation() );
}
return this.tooltip;
}
@SideOnly( Side.CLIENT ) @Override
public String getDisplayName() public String toString() {
{ return this.getStackSize() + "x" + this.getDefinition().getItem().getRegistryName();
if( this.displayName == null ) }
{
this.displayName = Platform.getItemDisplayName( this.asItemStackRepresentation() );
}
return this.displayName;
}
@SideOnly( Side.CLIENT ) @SideOnly(Side.CLIENT)
public String getModID() public List<String> getToolTip() {
{ if (this.tooltip == null) {
if( this.uniqueID == null ) this.tooltip = Platform.getTooltip(this.asItemStackRepresentation());
{ }
this.uniqueID = Item.REGISTRY.getNameForObject( this.getDefinition().getItem() ); return this.tooltip;
} }
if( this.uniqueID == null ) @SideOnly(Side.CLIENT)
{ public String getDisplayName() {
return "** Null"; if (this.displayName == null) {
} this.displayName = Platform.getItemDisplayName(this.asItemStackRepresentation());
}
return this.displayName;
}
return this.uniqueID.getResourceDomain() == null ? "** Null" : this.uniqueID.getResourceDomain(); @SideOnly(Side.CLIENT)
} public String getModID() {
return this.getDefinition().getItem().getRegistryName().getResourceDomain();
}
public Optional<OreReference> getOre() public Optional<OreReference> getOre()
{ {
return this.oreReference; return this.oreReference;
} }
@Override @Override
public boolean hasTagCompound() public boolean hasTagCompound() {
{ return this.getDefinition().hasTagCompound();
return this.getDefinition().hasTagCompound(); }
}
@Override @Override
public ItemStack asItemStackRepresentation() public ItemStack asItemStackRepresentation() {
{ return this.getDefinition().copy();
return this.getDefinition().copy(); }
}
@Override @Override
public ItemStack getDefinition() public ItemStack getDefinition() {
{ return this.sharedStack.getDefinition();
return this.sharedStack.getDefinition(); }
}
AESharedItemStack getSharedStack() AESharedItemStack getSharedStack() {
{ return this.sharedStack;
return this.sharedStack; }
}
private boolean fuzzyItemStackComparison( ItemStack a, ItemStack b, FuzzyMode mode ) private boolean fuzzyItemStackComparison(ItemStack a, ItemStack b, FuzzyMode mode) {
{ if (a.getItem() == b.getItem() && a.getItem().isDamageable()) {
if( a.getItem() == b.getItem() ) if (mode == FuzzyMode.IGNORE_ALL) {
{ return true;
if( a.getItem().isDamageable() ) } else if (mode == FuzzyMode.PERCENT_99) {
{ return a.getItemDamage() > 1 == b.getItemDamage() > 1;
if( mode == FuzzyMode.IGNORE_ALL ) } else {
{ final float percentDamageOfA = (float) a.getItemDamage() / a.getMaxDamage();
return true; final float percentDamageOfB = (float) b.getItemDamage() / b.getMaxDamage();
}
else if( mode == FuzzyMode.PERCENT_99 )
{
return ( a.getItemDamage() > 1 ) == ( b.getItemDamage() > 1 );
}
else
{
final float percentDamageOfA = (float) a.getItemDamage() / (float) a.getMaxDamage();
final float percentDamageOfB = (float) b.getItemDamage() / (float) b.getMaxDamage();
return ( percentDamageOfA > mode.breakPoint ) == ( percentDamageOfB > mode.breakPoint ); return percentDamageOfA > mode.breakPoint == percentDamageOfB > mode.breakPoint;
} }
} }
return a.getMetadata() == b.getMetadata();
}
return false;
}
return false;
}
} }
@@ -23,7 +23,6 @@
package appeng.util.item; package appeng.util.item;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.util.WeakHashMap; import java.util.WeakHashMap;
@@ -31,56 +30,34 @@ import javax.annotation.Nonnull;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import appeng.util.Platform; public final class AEItemStackRegistry {
private static final WeakHashMap<AESharedItemStack, WeakReference<AESharedItemStack>> REGISTRY = new WeakHashMap<>();
private AEItemStackRegistry() {
}
public final class AEItemStackRegistry static synchronized AESharedItemStack getRegisteredStack(final @Nonnull ItemStack itemStack) {
{ if (itemStack.isEmpty()) {
private static final WeakHashMap<AESharedItemStack, WeakReference<AESharedItemStack>> SERVER_REGISTRY = new WeakHashMap<>(); throw new IllegalArgumentException("stack cannot be empty");
private static final WeakHashMap<AESharedItemStack, WeakReference<AESharedItemStack>> CLIENT_REGISTRY = new WeakHashMap<>(); }
private AEItemStackRegistry() int oldStackSize = itemStack.getCount();
{ itemStack.setCount(1);
}
private static WeakHashMap<AESharedItemStack, WeakReference<AESharedItemStack>> registry() AESharedItemStack search = new AESharedItemStack(itemStack);
{ WeakReference<AESharedItemStack> weak = REGISTRY.get(search);
if( Platform.isClient() ) AESharedItemStack ret = null;
{
return CLIENT_REGISTRY;
}
else
{
return SERVER_REGISTRY;
}
}
static synchronized AESharedItemStack getRegisteredStack( final @Nonnull ItemStack itemStack ) if (weak != null) {
{ ret = weak.get();
if( itemStack.isEmpty() ) }
{
throw new IllegalArgumentException( "stack cannot be empty" );
}
int oldStackSize = itemStack.getCount(); if (ret == null) {
itemStack.setCount( 1 ); ret = new AESharedItemStack(itemStack.copy());
REGISTRY.put(ret, new WeakReference<>(ret));
}
itemStack.setCount(oldStackSize);
AESharedItemStack search = new AESharedItemStack( itemStack ); return ret;
WeakReference<AESharedItemStack> weak = registry().get( search ); }
AESharedItemStack ret = null;
if( weak != null )
{
ret = weak.get();
}
if( ret == null )
{
ret = new AESharedItemStack( itemStack.copy() );
registry().put( ret, new WeakReference<>( ret ) );
}
itemStack.setCount( oldStackSize );
return ret;
}
} }

Some files were not shown because too many files have changed in this diff Show More