Lots more moved

This commit is contained in:
Sebastian Hartte
2020-07-04 21:03:30 +02:00
parent 5982f094ec
commit 1478e4c378
444 changed files with 4693 additions and 5235 deletions
@@ -0,0 +1,277 @@
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved.
*
* 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
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.parts.misc;
import java.util.EnumSet;
import java.util.List;
import alexiil.mc.lib.attributes.AttributeList;
import alexiil.mc.lib.attributes.item.FixedItemInv;
import com.google.common.collect.ImmutableSet;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.CraftingInventory;
import net.minecraft.screen.ScreenHandlerType;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.util.math.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.Vec3d;
import appeng.api.AEApi;
import appeng.api.config.Actionable;
import appeng.api.config.Upgrades;
import appeng.api.networking.IGridNode;
import appeng.api.networking.crafting.ICraftingLink;
import appeng.api.networking.crafting.ICraftingPatternDetails;
import appeng.api.networking.crafting.ICraftingProviderHelper;
import appeng.api.networking.events.MENetworkChannelsChanged;
import appeng.api.networking.events.MENetworkEventSubscribe;
import appeng.api.networking.events.MENetworkPowerStatusChange;
import appeng.api.networking.ticking.IGridTickable;
import appeng.api.networking.ticking.TickRateModulation;
import appeng.api.networking.ticking.TickingRequest;
import appeng.api.parts.IPartCollisionHelper;
import appeng.api.parts.IPartModel;
import appeng.api.storage.IMEMonitor;
import appeng.api.storage.IStorageChannel;
import appeng.api.storage.IStorageMonitorable;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IAEStack;
import appeng.api.util.AECableType;
import appeng.api.util.IConfigManager;
import appeng.container.ContainerLocator;
import appeng.container.ContainerOpener;
import appeng.container.implementations.InterfaceContainer;
import appeng.core.AppEng;
import appeng.helpers.DualityInterface;
import appeng.helpers.IInterfaceHost;
import appeng.helpers.IPriorityHost;
import appeng.items.parts.PartModels;
import appeng.parts.BasicStatePart;
import appeng.parts.PartModel;
import appeng.util.Platform;
import appeng.util.inv.IAEAppEngInventory;
import appeng.util.inv.IInventoryDestination;
import appeng.util.inv.InvOperation;
public class InterfacePart extends BasicStatePart implements IGridTickable, IStorageMonitorable, IInventoryDestination,
IInterfaceHost, IAEAppEngInventory, IPriorityHost {
public static final Identifier MODEL_BASE = new Identifier(AppEng.MOD_ID, "part/interface_base");
@PartModels
public static final PartModel MODELS_OFF = new PartModel(MODEL_BASE,
new Identifier(AppEng.MOD_ID, "part/interface_off"));
@PartModels
public static final PartModel MODELS_ON = new PartModel(MODEL_BASE,
new Identifier(AppEng.MOD_ID, "part/interface_on"));
@PartModels
public static final PartModel MODELS_HAS_CHANNEL = new PartModel(MODEL_BASE,
new Identifier(AppEng.MOD_ID, "part/interface_has_channel"));
private final DualityInterface duality = new DualityInterface(this.getProxy(), this);
public InterfacePart(final ItemStack is) {
super(is);
}
@MENetworkEventSubscribe
public void stateChange(final MENetworkChannelsChanged c) {
this.duality.notifyNeighbors();
}
@MENetworkEventSubscribe
public void stateChange(final MENetworkPowerStatusChange c) {
this.duality.notifyNeighbors();
}
@Override
public void getBoxes(final IPartCollisionHelper bch) {
bch.addBox(2, 2, 14, 14, 14, 16);
bch.addBox(5, 5, 12, 11, 11, 14);
}
@Override
public int getInstalledUpgrades(final Upgrades u) {
return this.duality.getInstalledUpgrades(u);
}
@Override
public void gridChanged() {
this.duality.gridChanged();
}
@Override
public void readFromNBT(final CompoundTag data) {
super.readFromNBT(data);
this.duality.readFromNBT(data);
}
@Override
public void writeToNBT(final CompoundTag data) {
super.writeToNBT(data);
this.duality.writeToNBT(data);
}
@Override
public void addToWorld() {
super.addToWorld();
this.duality.initialize();
}
@Override
public void getDrops(final List<ItemStack> drops, final boolean wrenched) {
this.duality.addDrops(drops);
}
@Override
public float getCableConnectionLength(AECableType cable) {
return 4;
}
@Override
public IConfigManager getConfigManager() {
return this.duality.getConfigManager();
}
@Override
public FixedItemInv getInventoryByName(final String name) {
return this.duality.getInventoryByName(name);
}
@Override
public boolean onPartActivate(final PlayerEntity p, final Hand hand, final Vec3d pos) {
if (Platform.isServer()) {
ContainerOpener.openContainer(InterfaceContainer.TYPE, p, ContainerLocator.forPart(this));
}
return true;
}
@Override
public boolean canInsert(final ItemStack stack) {
return this.duality.canInsert(stack);
}
@Override
public <T extends IAEStack<T>> IMEMonitor<T> getInventory(IStorageChannel<T> channel) {
return this.duality.getInventory(channel);
}
@Override
public TickingRequest getTickingRequest(final IGridNode node) {
return this.duality.getTickingRequest(node);
}
@Override
public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) {
return this.duality.tickingRequest(node, ticksSinceLastCall);
}
@Override
public void onChangeInventory(final FixedItemInv inv, final int slot, final InvOperation mc,
final ItemStack removedStack, final ItemStack newStack) {
this.duality.onChangeInventory(inv, slot, mc, removedStack, newStack);
}
@Override
public DualityInterface getInterfaceDuality() {
return this.duality;
}
@Override
public EnumSet<Direction> getTargets() {
return EnumSet.of(this.getSide().getFacing());
}
@Override
public BlockEntity getBlockEntity() {
return super.getHost().getTile();
}
@Override
public boolean pushPattern(final ICraftingPatternDetails patternDetails, final CraftingInventory table) {
return this.duality.pushPattern(patternDetails, table);
}
@Override
public boolean isBusy() {
return this.duality.isBusy();
}
@Override
public void provideCrafting(final ICraftingProviderHelper craftingTracker) {
this.duality.provideCrafting(craftingTracker);
}
@Override
public ImmutableSet<ICraftingLink> getRequestedJobs() {
return this.duality.getRequestedJobs();
}
@Override
public IAEItemStack injectCraftedItems(final ICraftingLink link, final IAEItemStack items, final Actionable mode) {
return this.duality.injectCraftedItems(link, items, mode);
}
@Override
public void jobStateChange(final ICraftingLink link) {
this.duality.jobStateChange(link);
}
@Override
public int getPriority() {
return this.duality.getPriority();
}
@Override
public void setPriority(final int newValue) {
this.duality.setPriority(newValue);
}
@Override
public IPartModel getStaticModels() {
if (this.isActive() && this.isPowered()) {
return MODELS_HAS_CHANNEL;
} else if (this.isPowered()) {
return MODELS_ON;
} else {
return MODELS_OFF;
}
}
@Override
public void addAllAttributes(AttributeList<?> to) {
this.duality.addAllAttributes(to);
}
@Override
public ItemStack getItemStackRepresentation() {
return AEApi.instance().definitions().parts().iface().maybeStack(1).orElse(ItemStack.EMPTY);
}
@Override
public ScreenHandlerType<?> getContainerType() {
return InterfaceContainer.TYPE;
}
}
@@ -0,0 +1,317 @@
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved.
*
* 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
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.parts.misc;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import alexiil.mc.lib.attributes.Simulation;
import alexiil.mc.lib.attributes.item.FixedItemInv;
import net.minecraft.item.ItemStack;
import appeng.api.AEApi;
import appeng.api.config.Actionable;
import appeng.api.networking.security.IActionSource;
import appeng.api.networking.storage.IBaseMonitor;
import appeng.api.networking.ticking.TickRateModulation;
import appeng.api.storage.IMEInventory;
import appeng.api.storage.IMEMonitorHandlerReceiver;
import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList;
import appeng.core.AELog;
import appeng.me.GridAccessException;
import appeng.me.helpers.IGridProxyable;
import appeng.me.storage.ITickingMonitor;
import appeng.util.Platform;
import appeng.util.item.AEItemStack;
/**
* Wraps an Item Handler in such a way that it can be used as an IMEInventory
* for items.
*/
class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAEItemStack>, ITickingMonitor {
private final Map<IMEMonitorHandlerReceiver<IAEItemStack>, Object> listeners = new HashMap<>();
private IActionSource mySource;
private final FixedItemInv itemHandler;
private final IGridProxyable proxyable;
private final InventoryCache cache;
ItemHandlerAdapter(FixedItemInv itemHandler, IGridProxyable proxy) {
this.itemHandler = itemHandler;
this.proxyable = proxy;
this.cache = new InventoryCache(this.itemHandler);
}
@Override
public IAEItemStack injectItems(IAEItemStack iox, Actionable type, IActionSource src) {
ItemStack orgInput = iox.createItemStack();
ItemStack remaining = orgInput;
int slotCount = this.itemHandler.getSlotCount();
boolean simulate = (type == Actionable.SIMULATE);
// 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++) {
remaining = this.itemHandler.getSlot(i).attemptInsertion(remaining, simulate ? Simulation.SIMULATE : Simulation.ACTION);
}
// At this point, we still have some items left...
if (remaining == orgInput) {
// The stack remained unmodified, target inventory is full
return iox;
}
if (type == Actionable.MODULATE) {
try {
this.proxyable.getProxy().getTick().alertDevice(this.proxyable.getProxy().getNode());
} catch (GridAccessException ex) {
// meh
}
}
return AEItemStack.fromItemStack(remaining);
}
// FIXME FABRIC: this really needs to be rewritten to use the other interface types and not do slot iterations
@Override
public IAEItemStack extractItems(IAEItemStack request, Actionable mode, IActionSource src) {
ItemStack requestedItemStack = request.createItemStack();
int remainingSize = requestedItemStack.getCount();
// Use this to gather the requested items
ItemStack gathered = ItemStack.EMPTY;
final boolean simulate = (mode == Actionable.SIMULATE);
for (int i = 0; i < this.itemHandler.getSlotCount(); i++) {
ItemStack stackInInventorySlot = this.itemHandler.getInvStack(i);
if (!Platform.itemComparisons().isSameItem(stackInInventorySlot, requestedItemStack)) {
continue;
}
ItemStack extracted;
int stackSizeCurrentSlot = stackInInventorySlot.getCount();
int remainingCurrentSlot = Math.min(remainingSize, stackSizeCurrentSlot);
// We have to loop here because according to the docs, the handler shouldn't
// return a stack with size >
// maxSize, even if we request more. So even if it returns a valid stack, it
// might have more stuff.
do {
extracted = this.itemHandler.getSlot(i).attemptAnyExtraction(remainingCurrentSlot, simulate ? Simulation.SIMULATE : Simulation.ACTION);
if (!extracted.isEmpty()) {
if (extracted.getCount() > remainingCurrentSlot) {
// Something broke. It should never return more than we requested...
// We're going to silently eat the remainder
AELog.warn(
"Mod that provided item handler %s is broken. Returned %s items while only requesting %d.",
this.itemHandler.getClass().getName(), extracted.toString(), remainingCurrentSlot);
extracted.setCount(remainingCurrentSlot);
}
// We're just gonna use the first stack we get our hands on as the template for
// the rest.
// In case some stupid itemhandler (aka forge) returns an internal state we have
// to do a second
// expensive copy again.
if (gathered.isEmpty()) {
gathered = extracted.copy();
} else {
gathered.increment(extracted.getCount());
}
remainingCurrentSlot -= extracted.getCount();
}
} while (!extracted.isEmpty() && remainingCurrentSlot > 0);
remainingSize -= stackSizeCurrentSlot - remainingCurrentSlot;
// Done?
if (remainingSize <= 0) {
break;
}
}
if (!gathered.isEmpty()) {
if (mode == Actionable.MODULATE) {
try {
this.proxyable.getProxy().getTick().alertDevice(this.proxyable.getProxy().getNode());
} catch (GridAccessException ex) {
// meh
}
}
return AEItemStack.fromItemStack(gathered);
}
return null;
}
@Override
public TickRateModulation onTick() {
List<IAEItemStack> changes = this.cache.update();
if (!changes.isEmpty()) {
this.postDifference(changes);
return TickRateModulation.URGENT;
} else {
return TickRateModulation.SLOWER;
}
}
@Override
public void setActionSource(final IActionSource mySource) {
this.mySource = mySource;
}
@Override
public IItemList<IAEItemStack> getAvailableItems(IItemList<IAEItemStack> out) {
return this.cache.getAvailableItems(out);
}
@Override
public IItemStorageChannel getChannel() {
return AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class);
}
@Override
public void addListener(final IMEMonitorHandlerReceiver<IAEItemStack> l, final Object verificationToken) {
this.listeners.put(l, verificationToken);
}
@Override
public void removeListener(final IMEMonitorHandlerReceiver<IAEItemStack> l) {
this.listeners.remove(l);
}
private void postDifference(Iterable<IAEItemStack> a) {
final Iterator<Map.Entry<IMEMonitorHandlerReceiver<IAEItemStack>, Object>> i = this.listeners.entrySet()
.iterator();
while (i.hasNext()) {
final Map.Entry<IMEMonitorHandlerReceiver<IAEItemStack>, Object> l = i.next();
final IMEMonitorHandlerReceiver<IAEItemStack> key = l.getKey();
if (key.isValid(l.getValue())) {
key.postChange(this, a, this.mySource);
} else {
i.remove();
}
}
}
private static class InventoryCache {
private IAEItemStack[] cachedAeStacks = new IAEItemStack[0];
private final FixedItemInv itemHandler;
public InventoryCache(FixedItemInv itemHandler) {
this.itemHandler = itemHandler;
}
public IItemList<IAEItemStack> getAvailableItems(IItemList<IAEItemStack> out) {
Arrays.stream(this.cachedAeStacks).forEach(out::add);
return out;
}
public List<IAEItemStack> update() {
final List<IAEItemStack> changes = new ArrayList<>();
final int slots = this.itemHandler.getSlotCount();
// Make room for new slots
if (slots > this.cachedAeStacks.length) {
this.cachedAeStacks = Arrays.copyOf(this.cachedAeStacks, slots);
}
for (int slot = 0; slot < slots; slot++) {
// Save the old stuff
final IAEItemStack oldAeIS = this.cachedAeStacks[slot];
final ItemStack newIS = this.itemHandler.getInvStack(slot);
this.handlePossibleSlotChanges(slot, oldAeIS, newIS, changes);
}
// Handle cases where the number of slots actually is lower now than before
if (slots < this.cachedAeStacks.length) {
for (int slot = slots; slot < this.cachedAeStacks.length; slot++) {
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);
}
return changes;
}
private void handlePossibleSlotChanges(int slot, IAEItemStack oldAeIS, ItemStack newIS,
List<IAEItemStack> changes) {
if (oldAeIS != null && oldAeIS.isSameType(newIS)) {
this.handleStackSizeChanged(slot, oldAeIS, newIS, changes);
} else {
this.handleItemChanged(slot, oldAeIS, newIS, changes);
}
}
private void handleStackSizeChanged(int slot, IAEItemStack oldAeIS, ItemStack newIS,
List<IAEItemStack> changes) {
// Still the same item, but amount might have changed
final long diff = newIS.getCount() - oldAeIS.getStackSize();
if (diff != 0) {
final IAEItemStack stack = oldAeIS.copy();
stack.setStackSize(newIS.getCount());
this.cachedAeStacks[slot] = stack;
final IAEItemStack a = stack.copy();
a.setStackSize(diff);
changes.add(a);
}
}
private void handleItemChanged(int slot, IAEItemStack oldAeIS, ItemStack newIS, List<IAEItemStack> changes) {
// Completely different item
this.cachedAeStacks[slot] = AEItemStack.fromItemStack(newIS);
// If we had a stack previously in this slot, notify the network about its
// disappearance
if (oldAeIS != null) {
oldAeIS.setStackSize(-oldAeIS.getStackSize());
changes.add(oldAeIS);
}
// Notify the network about the new stack. Note that this is null if newIS was
// null
if (this.cachedAeStacks[slot] != null) {
changes.add(this.cachedAeStacks[slot]);
}
}
}
}
@@ -0,0 +1,171 @@
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2018, AlgorithmX2, All rights reserved.
*
* 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
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.parts.misc;
import java.util.Collections;
import java.util.List;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.BlockView;
import appeng.api.AEApi;
import appeng.api.config.Settings;
import appeng.api.networking.events.MENetworkCellArrayUpdate;
import appeng.api.networking.events.MENetworkChannelsChanged;
import appeng.api.networking.events.MENetworkEventSubscribe;
import appeng.api.networking.events.MENetworkPowerStatusChange;
import appeng.api.networking.ticking.IGridTickable;
import appeng.api.parts.IPartCollisionHelper;
import appeng.api.storage.IMEInventoryHandler;
import appeng.api.storage.IStorageChannel;
import appeng.api.storage.cells.ICellContainer;
import appeng.api.storage.cells.ICellInventory;
import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.util.AECableType;
import appeng.api.util.IConfigManager;
import appeng.helpers.IPriorityHost;
import appeng.me.GridAccessException;
import appeng.parts.automation.UpgradeablePart;
/**
* @author BrockWS
* @version rv6 - 22/05/2018
* @since rv6 22/05/2018
*/
public abstract class SharedStorageBusPart extends UpgradeablePart
implements IGridTickable, ICellContainer, IPriorityHost {
private boolean wasActive = false;
private int priority = 0;
public SharedStorageBusPart(ItemStack is) {
super(is);
}
protected void updateStatus() {
final boolean currentActive = this.getProxy().isActive();
if (this.wasActive != currentActive) {
this.wasActive = currentActive;
try {
this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate());
this.getHost().markForUpdate();
} catch (final GridAccessException ignore) {
// :P
}
}
}
@MENetworkEventSubscribe
public void updateChannels(final MENetworkChannelsChanged changedChannels) {
this.updateStatus();
}
/**
* Helper method to get this parts storage channel
*
* @return Storage channel
*/
public IStorageChannel getStorageChannel() {
return AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class);
}
protected abstract void resetCache();
protected abstract void resetCache(boolean fullReset);
@Override
public List<IMEInventoryHandler> getCellArray(final IStorageChannel channel) {
return Collections.emptyList();
}
@Override
public void blinkCell(int slot) {
}
@Override
public void saveChanges(ICellInventory<?> cellInventory) {
}
@Override
public int getPriority() {
return this.priority;
}
@Override
public void setPriority(final int newValue) {
this.priority = newValue;
this.getHost().markForSave();
this.resetCache(true);
}
@Override
@MENetworkEventSubscribe
public void powerRender(final MENetworkPowerStatusChange c) {
this.updateStatus();
}
@Override
public void upgradesChanged() {
super.upgradesChanged();
this.resetCache(true);
}
@Override
public void updateSetting(final IConfigManager manager, final Settings settingName, final Enum<?> newValue) {
this.resetCache(true);
this.getHost().markForSave();
}
@Override
public void onneighborUpdate(BlockView w, BlockPos pos, BlockPos neighbor) {
if (pos.offset(this.getSide().getFacing()).equals(neighbor)) {
this.resetCache(false);
}
}
@Override
public void readFromNBT(final CompoundTag data) {
super.readFromNBT(data);
this.priority = data.getInt("priority");
}
@Override
public void writeToNBT(final CompoundTag data) {
super.writeToNBT(data);
data.putInt("priority", this.priority);
}
@Override
public void getBoxes(final IPartCollisionHelper bch) {
bch.addBox(3, 3, 15, 13, 13, 16);
bch.addBox(2, 2, 14, 14, 14, 15);
bch.addBox(5, 5, 12, 11, 11, 14);
}
@Override
protected int getUpgradeSlots() {
return 5;
}
@Override
public float getCableConnectionLength(AECableType cable) {
return 4;
}
}
@@ -0,0 +1,568 @@
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2015, AlgorithmX2, All rights reserved.
*
* 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
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.parts.misc;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import alexiil.mc.lib.attributes.Attributes;
import alexiil.mc.lib.attributes.item.ItemAttributes;
import appeng.attributes.MEAttributes;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.screen.ScreenHandlerType;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.BlockView;
import alexiil.mc.lib.attributes.item.FixedItemInv;
import appeng.api.AEApi;
import appeng.api.config.AccessRestriction;
import appeng.api.config.FuzzyMode;
import appeng.api.config.IncludeExclude;
import appeng.api.config.Settings;
import appeng.api.config.StorageFilter;
import appeng.api.config.Upgrades;
import appeng.api.networking.IGridNode;
import appeng.api.networking.events.MENetworkCellArrayUpdate;
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.networking.storage.IBaseMonitor;
import appeng.api.networking.ticking.IGridTickable;
import appeng.api.networking.ticking.ITickManager;
import appeng.api.networking.ticking.TickRateModulation;
import appeng.api.networking.ticking.TickingRequest;
import appeng.api.parts.IPartCollisionHelper;
import appeng.api.parts.IPartHost;
import appeng.api.parts.IPartModel;
import appeng.api.storage.IMEInventory;
import appeng.api.storage.IMEInventoryHandler;
import appeng.api.storage.IMEMonitorHandlerReceiver;
import appeng.api.storage.IStorageChannel;
import appeng.api.storage.IStorageMonitorable;
import appeng.api.storage.IStorageMonitorableAccessor;
import appeng.api.storage.cells.ICellContainer;
import appeng.api.storage.cells.ICellInventory;
import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList;
import appeng.api.util.AECableType;
import appeng.api.util.AEPartLocation;
import appeng.api.util.IConfigManager;
import appeng.container.ContainerLocator;
import appeng.container.ContainerOpener;
import appeng.container.implementations.StorageBusContainer;
import appeng.core.AppEng;
import appeng.core.settings.TickRates;
import appeng.helpers.IInterfaceHost;
import appeng.helpers.IPriorityHost;
import appeng.items.parts.PartModels;
import appeng.me.GridAccessException;
import appeng.me.helpers.MachineSource;
import appeng.me.storage.ITickingMonitor;
import appeng.me.storage.MEInventoryHandler;
import appeng.me.storage.MEMonitorIInventory;
import appeng.parts.PartModel;
import appeng.parts.automation.UpgradeablePart;
import appeng.tile.inventory.AppEngInternalAEInventory;
import appeng.util.Platform;
import appeng.util.inv.InvOperation;
import appeng.util.prioritylist.FuzzyPriorityList;
import appeng.util.prioritylist.PrecisePriorityList;
public class StorageBusPart extends UpgradeablePart
implements IGridTickable, ICellContainer, IMEMonitorHandlerReceiver<IAEItemStack>, IPriorityHost {
public static final Identifier MODEL_BASE = new Identifier(AppEng.MOD_ID, "part/storage_bus_base");
@PartModels
public static final IPartModel MODELS_OFF = new PartModel(MODEL_BASE,
new Identifier(AppEng.MOD_ID, "part/storage_bus_off"));
@PartModels
public static final IPartModel MODELS_ON = new PartModel(MODEL_BASE,
new Identifier(AppEng.MOD_ID, "part/storage_bus_on"));
@PartModels
public static final IPartModel MODELS_HAS_CHANNEL = new PartModel(MODEL_BASE,
new Identifier(AppEng.MOD_ID, "part/storage_bus_has_channel"));
private final IActionSource mySrc;
private final AppEngInternalAEInventory Config = new AppEngInternalAEInventory(this, 63);
private int priority = 0;
private boolean cached = false;
private ITickingMonitor monitor = null;
private MEInventoryHandler<IAEItemStack> handler = null;
private int handlerHash = 0;
private boolean wasActive = false;
private byte resetCacheLogic = 0;
public StorageBusPart(final ItemStack is) {
super(is);
this.getConfigManager().registerSetting(Settings.ACCESS, AccessRestriction.READ_WRITE);
this.getConfigManager().registerSetting(Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL);
this.getConfigManager().registerSetting(Settings.STORAGE_FILTER, StorageFilter.EXTRACTABLE_ONLY);
this.mySrc = new MachineSource(this);
}
@Override
@MENetworkEventSubscribe
public void powerRender(final MENetworkPowerStatusChange c) {
this.updateStatus();
}
private void updateStatus() {
final boolean currentActive = this.getProxy().isActive();
if (this.wasActive != currentActive) {
this.wasActive = currentActive;
try {
this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate());
this.getHost().markForUpdate();
} catch (final GridAccessException e) {
// :P
}
}
}
@MENetworkEventSubscribe
public void updateChannels(final MENetworkChannelsChanged changedChannels) {
this.updateStatus();
}
@Override
protected int getUpgradeSlots() {
return 5;
}
@Override
public void updateSetting(final IConfigManager manager, final Settings settingName, final Enum<?> newValue) {
this.resetCache(true);
this.getHost().markForSave();
}
@Override
public void onChangeInventory(final FixedItemInv inv, final int slot, final InvOperation mc,
final ItemStack removedStack, final ItemStack newStack) {
super.onChangeInventory(inv, slot, mc, removedStack, newStack);
if (inv == this.Config) {
this.resetCache(true);
}
}
@Override
public void upgradesChanged() {
super.upgradesChanged();
this.resetCache(true);
}
@Override
public void readFromNBT(final CompoundTag data) {
super.readFromNBT(data);
this.Config.readFromNBT(data, "config");
this.priority = data.getInt("priority");
}
@Override
public void writeToNBT(final CompoundTag data) {
super.writeToNBT(data);
this.Config.writeToNBT(data, "config");
data.putInt("priority", this.priority);
}
@Override
public FixedItemInv getInventoryByName(final String name) {
if (name.equals("config")) {
return this.Config;
}
return super.getInventoryByName(name);
}
private void resetCache(final boolean fullReset) {
if (this.getHost() == null || this.getHost().getTile() == null || this.getHost().getTile().getWorld() == null
|| this.getHost().getTile().getWorld().isClient) {
return;
}
if (fullReset) {
this.resetCacheLogic = 2;
} else {
this.resetCacheLogic = 1;
}
try {
this.getProxy().getTick().alertDevice(this.getProxy().getNode());
} catch (final GridAccessException e) {
// :P
}
}
@Override
public boolean isValid(final Object verificationToken) {
return this.handler == verificationToken;
}
@Override
public void postChange(final IBaseMonitor<IAEItemStack> monitor, final Iterable<IAEItemStack> change,
final IActionSource source) {
try {
if (this.getProxy().isActive()) {
this.getProxy().getStorage().postAlterationOfStoredItems(
AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class), change, this.mySrc);
}
} catch (final GridAccessException e) {
// :(
}
}
@Override
public void onListUpdate() {
// not used here.
}
@Override
public void getBoxes(final IPartCollisionHelper bch) {
bch.addBox(3, 3, 15, 13, 13, 16);
bch.addBox(2, 2, 14, 14, 14, 15);
bch.addBox(5, 5, 12, 11, 11, 14);
}
@Override
public void onneighborUpdate(BlockView w, BlockPos pos, BlockPos neighbor) {
if (pos.offset(this.getSide().getFacing()).equals(neighbor)) {
final BlockEntity te = w.getBlockEntity(neighbor);
// In case the TE was destroyed, we have to do a full reset immediately.
if (te == null) {
this.resetCache(true);
this.resetCache();
} else {
this.resetCache(false);
}
}
}
@Override
public float getCableConnectionLength(AECableType cable) {
return 4;
}
@Override
public boolean onPartActivate(final PlayerEntity player, final Hand hand, final Vec3d pos) {
if (Platform.isServer()) {
ContainerOpener.openContainer(StorageBusContainer.TYPE, player, ContainerLocator.forPart(this));
}
return true;
}
@Override
public TickingRequest getTickingRequest(final IGridNode node) {
return new TickingRequest(TickRates.StorageBus.getMin(), TickRates.StorageBus.getMax(), this.monitor == null,
true);
}
@Override
public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) {
if (this.resetCacheLogic != 0) {
this.resetCache();
}
if (this.monitor != null) {
return this.monitor.onTick();
}
return TickRateModulation.SLEEP;
}
private void resetCache() {
final boolean fullReset = this.resetCacheLogic == 2;
this.resetCacheLogic = 0;
final IMEInventory<IAEItemStack> in = this.getInternalHandler();
IItemList<IAEItemStack> before = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)
.createList();
if (in != null) {
before = in.getAvailableItems(before);
}
this.cached = false;
if (fullReset) {
this.handlerHash = 0;
}
final IMEInventory<IAEItemStack> out = this.getInternalHandler();
if (in != out) {
IItemList<IAEItemStack> after = AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)
.createList();
if (out != null) {
after = out.getAvailableItems(after);
}
Platform.postListChanges(before, after, this, this.mySrc);
}
}
private IMEInventory<IAEItemStack> getInventoryWrapper(BlockEntity target) {
Direction targetSide = this.getSide().getFacing().getOpposite();
// Prioritize a handler to directly link to another ME network
IStorageMonitorableAccessor accessor = getMeAccessor(target, targetSide);
if (accessor != null) {
IStorageMonitorable inventory = accessor.getInventory(this.mySrc);
if (inventory != null) {
return inventory.getInventory(AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class));
}
// So this could / can be a design decision. If the tile does support our custom
// capability,
// but it does not return an inventory for the action source, we do NOT fall
// back to using
// IItemHandler's, as that might circumvent the security setings, and might also
// cause
// performance issues.
return null;
}
// Check via cap for IItemHandler
FixedItemInv handlerExt = getFixedItemInv(target, targetSide);
if (handlerExt != null) {
return new ItemHandlerAdapter(handlerExt, this);
}
return null;
}
// TODO, LazyOptionals are cacheable this might need changing?
private int createHandlerHash(BlockEntity target) {
if (target == null) {
return 0;
}
final Direction targetSide = this.getSide().getFacing().getOpposite();
IStorageMonitorableAccessor accessor = getMeAccessor(target, targetSide);
if (accessor != null) {
return Objects.hash(target, accessor);
}
FixedItemInv itemHandler = getFixedItemInv(target, targetSide);
if (itemHandler != null) {
return Objects.hash(target, itemHandler, itemHandler.getSlotCount());
}
return 0;
}
private FixedItemInv getFixedItemInv(BlockEntity target, Direction targetSide) {
return MEAttributes.getFirstAttributeOnSide(ItemAttributes.FIXED_INV, target, targetSide);
}
private IStorageMonitorableAccessor getMeAccessor(BlockEntity target, Direction targetSide) {
return MEAttributes.getFirstAttributeOnSide(MEAttributes.STORAGE_MONITORABLE_ACCESSOR, target, targetSide);
}
public MEInventoryHandler<IAEItemStack> getInternalHandler() {
if (this.cached) {
return this.handler;
}
final boolean wasSleeping = this.monitor == null;
this.cached = true;
final BlockEntity self = this.getHost().getTile();
final BlockEntity target = self.getWorld().getBlockEntity(self.getPos().offset(this.getSide().getFacing()));
final int newHandlerHash = this.createHandlerHash(target);
if (newHandlerHash != 0 && newHandlerHash == this.handlerHash) {
return this.handler;
}
this.handlerHash = newHandlerHash;
this.handler = null;
this.monitor = null;
if (target != null) {
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) {
this.monitor = (ITickingMonitor) inv;
this.monitor.setActionSource(new MachineSource(this));
}
if (inv != null) {
this.checkInterfaceVsStorageBus(target, this.getSide().getOpposite());
this.handler = new MEInventoryHandler<IAEItemStack>(inv,
AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class));
this.handler.setBaseAccess((AccessRestriction) this.getConfigManager().getSetting(Settings.ACCESS));
this.handler.setWhitelist(this.getInstalledUpgrades(Upgrades.INVERTER) > 0 ? IncludeExclude.BLACKLIST
: IncludeExclude.WHITELIST);
this.handler.setPriority(this.priority);
final IItemList<IAEItemStack> priorityList = AEApi.instance().storage()
.getStorageChannel(IItemStorageChannel.class).createList();
final int slotsToUse = 18 + this.getInstalledUpgrades(Upgrades.CAPACITY) * 9;
for (int x = 0; x < this.Config.getSlotCount() && x < slotsToUse; x++) {
final IAEItemStack is = this.Config.getAEStackInSlot(x);
if (is != null) {
priorityList.add(is);
}
}
if (this.getInstalledUpgrades(Upgrades.FUZZY) > 0) {
this.handler.setPartitionList(new FuzzyPriorityList<IAEItemStack>(priorityList,
(FuzzyMode) this.getConfigManager().getSetting(Settings.FUZZY_MODE)));
} else {
this.handler.setPartitionList(new PrecisePriorityList<IAEItemStack>(priorityList));
}
if (inv instanceof IBaseMonitor) {
((IBaseMonitor<IAEItemStack>) inv).addListener(this, this.handler);
}
}
}
// update sleep state...
if (wasSleeping != (this.monitor == null)) {
try {
final ITickManager tm = this.getProxy().getTick();
if (this.monitor == null) {
tm.sleepDevice(this.getProxy().getNode());
} else {
tm.wakeDevice(this.getProxy().getNode());
}
} catch (final GridAccessException e) {
// :(
}
}
try {
// force grid to update handlers...
this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate());
} catch (final GridAccessException e) {
// :3
}
return this.handler;
}
private void checkInterfaceVsStorageBus(final BlockEntity target, final AEPartLocation side) {
IInterfaceHost achievement = null;
if (target instanceof IInterfaceHost) {
achievement = (IInterfaceHost) target;
}
if (target instanceof IPartHost) {
final Object part = ((IPartHost) target).getPart(side);
if (part instanceof IInterfaceHost) {
achievement = (IInterfaceHost) part;
}
}
if (achievement != null && achievement.getActionableNode() != null) {
// Platform.increaseStat( achievement.getActionableNode().getPlayerID(),
// Achievements.Recursive.getAchievement()
// );
// Platform.increaseStat( getActionableNode().getPlayerID(),
// Achievements.Recursive.getAchievement() );
}
}
@Override
public List<IMEInventoryHandler> getCellArray(final IStorageChannel channel) {
if (channel == AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)) {
final IMEInventoryHandler<IAEItemStack> out = this.getProxy().isActive() ? this.getInternalHandler() : null;
if (out != null) {
return Collections.singletonList(out);
}
}
return Collections.emptyList();
}
@Override
public int getPriority() {
return this.priority;
}
@Override
public void setPriority(final int newValue) {
this.priority = newValue;
this.getHost().markForSave();
this.resetCache(true);
}
@Override
public void blinkCell(final int slot) {
}
// TODO: BC PIPE INTEGRATION
/*
* @Override
*
* @Method( iname = IntegrationType.BuildCraftTransport ) public ConnectOverride
* overridePipeConnection( PipeType type, ForgeDirection with ) { return type ==
* PipeType.ITEM && with == this.getSide() ? ConnectOverride.CONNECT :
* ConnectOverride.DISCONNECT; }
*/
@Override
public void saveChanges(final ICellInventory<?> cellInventory) {
// nope!
}
@Override
public IPartModel getStaticModels() {
if (this.isActive() && this.isPowered()) {
return MODELS_HAS_CHANNEL;
} else if (this.isPowered()) {
return MODELS_ON;
} else {
return MODELS_OFF;
}
}
@Override
public ItemStack getItemStackRepresentation() {
return AEApi.instance().definitions().parts().storageBus().maybeStack(1).orElse(ItemStack.EMPTY);
}
@Override
public ScreenHandlerType<?> getContainerType() {
return StorageBusContainer.TYPE;
}
}