Major API cleanup for corporea. Closes #3173

This commit is contained in:
Vincent Lee committed 2020-04-03 16:48:07 -05:00
1 parent 272ef5bbab
commit 4a63807d09
32 files changed
+679 -430

No files matched your search

@@ -46,6 +46,8 @@ import java.util.Map;
import java.util.function.Function;
public final class BotaniaAPI {
public static final String NO_MOD_MESSAGE = "Botania not present";
public static int apiVersion() {
return 94;
}
@@ -8,74 +8,40 @@
*/
package vazkii.botania.api.corporea;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import net.minecraft.entity.Entity;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.LazyValue;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import org.apache.logging.log4j.LogManager;
import vazkii.botania.api.BotaniaAPI;
import java.util.ArrayList;
import java.util.HashMap;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.function.Function;
import static vazkii.botania.api.corporea.CorporeaRequestDefaultMatchers.*;
public interface CorporeaHelper {
LazyValue<CorporeaHelper> INSTANCE = new LazyValue<>(() -> {
try {
return (CorporeaHelper) Class.forName("vazkii.botania.common.impl.CorporeaHelperImpl").newInstance();
} catch (ReflectiveOperationException e) {
LogManager.getLogger().warn("Unable to find CorporeaHelperImpl, using a dummy");
return new CorporeaHelper() {};
}
});
public final class CorporeaHelper {
private static final List<InvWithLocation> empty = ImmutableList.of();
private static final WeakHashMap<List<ICorporeaSpark>, List<InvWithLocation>> cachedNetworks = new WeakHashMap<>();
/**
* How many items were matched in the last request. If java had "out" params like C# this wouldn't be needed :V
*/
public static int lastRequestMatches = 0;
/**
* How many items were extracted in the last request.
*/
public static int lastRequestExtractions = 0;
static CorporeaHelper instance() {
return INSTANCE.getValue();
}
/**
* Gets a list of all the inventories on this spark network. This list is cached for use once every tick,
* and if something changes during that tick it'll still have the first result.
*/
public static List<InvWithLocation> getInventoriesOnNetwork(ICorporeaSpark spark) {
ICorporeaSpark master = spark.getMaster();
if (master == null) {
return empty;
}
List<ICorporeaSpark> network = master.getConnections();
if (cachedNetworks.containsKey(network)) {
List<InvWithLocation> cache = cachedNetworks.get(network);
if (cache != null) {
return cache;
}
}
List<InvWithLocation> inventories = new ArrayList<>();
if (network != null) {
for (ICorporeaSpark otherSpark : network) {
if (otherSpark != null) {
InvWithLocation inv = otherSpark.getSparkInventory();
if (inv != null) {
inventories.add(inv);
}
}
}
}
cachedNetworks.put(network, inventories);
return inventories;
default List<InvWithLocation> getInventoriesOnNetwork(ICorporeaSpark spark) {
return Collections.emptyList();
}
/**
@@ -83,9 +49,8 @@ public final class CorporeaHelper {
* The higher level functions that use a List< IInventory > or a Map< IInventory, Integer > should be
* called instead if the context for those exists to avoid having to get the values again.
*/
public static int getCountInNetwork(ICorporeaRequestMatcher matcher, ICorporeaSpark spark) {
List<InvWithLocation> inventories = getInventoriesOnNetwork(spark);
return getCountInNetwork(matcher, inventories);
default int getCountInNetwork(ICorporeaRequestMatcher matcher, ICorporeaSpark spark) {
return 0;
}
/**
@@ -93,22 +58,15 @@ public final class CorporeaHelper {
* The higher level function that use a Map< IInventory, Integer > should be
* called instead if the context for this exists to avoid having to get the value again.
*/
public static int getCountInNetwork(ICorporeaRequestMatcher matcher, List<InvWithLocation> inventories) {
Map<InvWithLocation, Integer> map = getInventoriesWithMatchInNetwork(matcher, inventories);
return getCountInNetwork(matcher, map);
default int getCountInNetwork(ICorporeaRequestMatcher matcher, List<InvWithLocation> inventories) {
return 0;
}
/**
* Gets the amount of available items in the network of the type passed in, checking NBT or not.
*/
public static int getCountInNetwork(ICorporeaRequestMatcher matcher, Map<InvWithLocation, Integer> inventories) {
int count = 0;
for (int value : inventories.values()) {
count += value;
}
return count;
default int getCountInNetwork(ICorporeaRequestMatcher matcher, Map<InvWithLocation, Integer> inventories) {
return 0;
}
/**
@@ -116,9 +74,8 @@ public final class CorporeaHelper {
* The higher level function that use a List< IInventory > should be
* called instead if the context for this exists to avoid having to get the value again.
*/
public static Map<InvWithLocation, Integer> getInventoriesWithMatchInNetwork(ICorporeaRequestMatcher matcher, ICorporeaSpark spark) {
List<InvWithLocation> inventories = getInventoriesOnNetwork(spark);
return getInventoriesWithMatchInNetwork(matcher, inventories);
default Map<InvWithLocation, Integer> getInventoriesWithMatchInNetwork(ICorporeaRequestMatcher matcher, ICorporeaSpark spark) {
return Collections.emptyMap();
}
/**
@@ -126,46 +83,35 @@ public final class CorporeaHelper {
* The deeper level function that use a List< IInventory > should be
* called instead if the context for this exists to avoid having to get the value again.
*/
public static Map<InvWithLocation, Integer> getInventoriesWithMatchInNetwork(ICorporeaRequestMatcher matcher, List<InvWithLocation> inventories) {
Map<InvWithLocation, Integer> countMap = new HashMap<>();
List<IWrappedInventory> wrappedInventories = BotaniaAPI.internalHandler.wrapInventory(inventories);
for (IWrappedInventory inv : wrappedInventories) {
CorporeaRequest request = new CorporeaRequest(matcher, -1);
inv.countItems(request);
if (request.foundItems > 0) {
countMap.put(inv.getWrappedObject(), request.foundItems);
}
}
return countMap;
default Map<InvWithLocation, Integer> getInventoriesWithMatchInNetwork(ICorporeaRequestMatcher matcher, List<InvWithLocation> inventories) {
return Collections.emptyMap();
}
/**
* Create a ICorporeaRequestMatcher from an ItemStack and NBT-checkness.
*/
public static ICorporeaRequestMatcher createMatcher(ItemStack stack, boolean checkNBT) {
return new CorporeaItemStackMatcher(stack, checkNBT);
default ICorporeaRequestMatcher createMatcher(ItemStack stack, boolean checkNBT) {
return ICorporeaRequestMatcher.Dummy.INSTANCE;
}
/**
* Create a ICorporeaRequestMatcher from a String.
*/
public static ICorporeaRequestMatcher createMatcher(String name) {
return new CorporeaStringMatcher(name);
default ICorporeaRequestMatcher createMatcher(String name) {
return ICorporeaRequestMatcher.Dummy.INSTANCE;
}
/**
* Bridge for requestItem() using an ItemStack.
*/
public static List<ItemStack> requestItem(ItemStack stack, ICorporeaSpark spark, boolean checkNBT, boolean doit) {
default ICorporeaResult requestItem(ItemStack stack, ICorporeaSpark spark, boolean checkNBT, boolean doit) {
return requestItem(createMatcher(stack, checkNBT), stack.getCount(), spark, doit);
}
/**
* Bridge for requestItem() using a String and an item count.
*/
public static List<ItemStack> requestItem(String name, int count, ICorporeaSpark spark, boolean doit) {
default ICorporeaResult requestItem(String name, int count, ICorporeaSpark spark, boolean doit) {
return requestItem(createMatcher(name), count, spark, doit);
}
@@ -176,98 +122,46 @@ public final class CorporeaHelper {
* Case itemCount is -1 it'll find EVERY item it can.
* <br>
* <br>
* The "matcher" parameter has to be an ItemStack or a String, if the first it'll check if the
* two stacks are similar using the "checkNBT" parameter, else it'll check if the name of the item
* equals or matches (case a regex is passed in) the matcher string.
* <br>
* <br>
* When requesting counting of items, individual stacks may exceed maxStackSize for
* purposes of counting huge amounts.
* @return Triple of stacks extracted, number of items matched, and number of items extracted
*/
public static List<ItemStack> requestItem(ICorporeaRequestMatcher matcher, int itemCount, ICorporeaSpark spark, boolean doit) {
List<ItemStack> stacks = new ArrayList<>();
CorporeaRequestEvent event = new CorporeaRequestEvent(matcher, itemCount, spark, doit);
if (MinecraftForge.EVENT_BUS.post(event)) {
return stacks;
}
List<InvWithLocation> inventories = getInventoriesOnNetwork(spark);
List<IWrappedInventory> inventoriesW = BotaniaAPI.internalHandler.wrapInventory(inventories);
Map<ICorporeaInterceptor, ICorporeaSpark> interceptors = new HashMap<ICorporeaInterceptor, ICorporeaSpark>();
CorporeaRequest request = new CorporeaRequest(matcher, itemCount);
for (IWrappedInventory inv : inventoriesW) {
ICorporeaSpark invSpark = inv.getSpark();
InvWithLocation originalInventory = inv.getWrappedObject();
if (originalInventory.world.getTileEntity(originalInventory.pos) instanceof ICorporeaInterceptor) {
ICorporeaInterceptor interceptor = (ICorporeaInterceptor) originalInventory.world.getTileEntity(originalInventory.pos);
interceptor.interceptRequest(matcher, itemCount, invSpark, spark, stacks, inventories, doit);
interceptors.put(interceptor, invSpark);
}
if (doit) {
stacks.addAll(inv.extractItems(request));
} else {
stacks.addAll(inv.countItems(request));
}
}
for (ICorporeaInterceptor interceptor : interceptors.keySet()) {
interceptor.interceptRequestLast(matcher, itemCount, interceptors.get(interceptor), spark, stacks, inventories, doit);
}
lastRequestMatches = request.foundItems;
lastRequestExtractions = request.extractedItems;
return stacks;
default ICorporeaResult requestItem(ICorporeaRequestMatcher matcher, int itemCount, ICorporeaSpark spark, boolean doit) {
return ICorporeaResult.Dummy.INSTANCE;
}
/**
* Gets the spark attached to the inventory passed case it's a TileEntity.
*/
public static ICorporeaSpark getSparkForInventory(InvWithLocation inv) {
TileEntity tile = inv.world.getTileEntity(inv.pos);
return getSparkForBlock(tile.getWorld(), tile.getPos());
@Nullable
default ICorporeaSpark getSparkForInventory(InvWithLocation inv) {
return null;
}
/**
* Gets the spark attached to the block in the coords passed in. Note that the coords passed
* in are for the block that the spark will be on, not the coords of the spark itself.
*/
public static ICorporeaSpark getSparkForBlock(World world, BlockPos pos) {
List<Entity> sparks = world.getEntitiesWithinAABB(Entity.class, new AxisAlignedBB(pos.up(), pos.add(1, 2, 1)), Predicates.instanceOf(ICorporeaSpark.class));
return sparks.isEmpty() ? null : (ICorporeaSpark) sparks.get(0);
@Nullable
default ICorporeaSpark getSparkForBlock(World world, BlockPos pos) {
return null;
}
/**
* Gets if the block in the coords passed in has a spark attached. Note that the coords passed
* in are for the block that the spark will be on, not the coords of the spark itself.
*/
public static boolean doesBlockHaveSpark(World world, BlockPos pos) {
default boolean doesBlockHaveSpark(World world, BlockPos pos) {
return getSparkForBlock(world, pos) != null;
}
/**
* Clears the cached networks, called once per tick, should not be called outside
* of the botania code.
*/
public static void clearCache() {
cachedNetworks.clear();
}
/**
* Returns the comparator strength for a corporea request that corporea crystal cubes and retainers use, following
* the usual "each step up requires double the items" formula.
*/
public static int signalStrengthForRequestSize(int requestSize) {
if (requestSize <= 0) {
return 0;
} else if (requestSize >= 16384) {
return 15;
} else {
return Math.min(15, MathHelper.log2(requestSize) + 1);
}
default int signalStrengthForRequestSize(int requestSize) {
return 0;
}
default <T extends ICorporeaRequestMatcher> void registerRequestMatcher(ResourceLocation id, Class<T> clazz, Function<CompoundNBT, T> deserializer) {}
}
@@ -18,10 +18,10 @@ import net.minecraftforge.eventbus.api.Event;
*/
@Cancelable
public class CorporeaIndexRequestEvent extends Event {
public final ServerPlayerEntity requester;
public ICorporeaRequestMatcher request;
public int requestCount;
public ICorporeaSpark indexSpark;
private final ServerPlayerEntity requester;
private final ICorporeaRequestMatcher request;
private final int requestCount;
private final ICorporeaSpark indexSpark;
public CorporeaIndexRequestEvent(ServerPlayerEntity requester, ICorporeaRequestMatcher request, int requestCount, ICorporeaSpark indexSpark) {
this.requester = requester;
@@ -29,4 +29,20 @@ public class CorporeaIndexRequestEvent extends Event {
this.requestCount = requestCount;
this.indexSpark = indexSpark;
}
public ServerPlayerEntity getRequester() {
return requester;
}
public ICorporeaRequestMatcher getMatcher() {
return request;
}
public int getRequestCount() {
return requestCount;
}
public ICorporeaSpark getIndexSpark() {
return indexSpark;
}
}
@@ -1,23 +0,0 @@
/*
* This class is distributed as part of the Botania Mod.
* Get the Source Code in github:
* https://github.com/Vazkii/Botania
*
* Botania is Open Source and distributed under the
* Botania License: http://botaniamod.net/license.php
*/
package vazkii.botania.api.corporea;
public class CorporeaRequest {
public final ICorporeaRequestMatcher matcher;
public int count;
public int foundItems = 0;
public int extractedItems = 0;
public CorporeaRequest(ICorporeaRequestMatcher matcher, int count) {
super();
this.matcher = matcher;
this.count = count;
}
}
@@ -1,139 +0,0 @@
/*
* This class is distributed as part of the Botania Mod.
* Get the Source Code in github:
* https://github.com/Vazkii/Botania
*
* Botania is Open Source and distributed under the
* Botania License: http://botaniamod.net/license.php
*/
package vazkii.botania.api.corporea;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import org.apache.commons.lang3.text.WordUtils;
import vazkii.botania.common.core.helper.ItemNBTHelper;
import java.util.regex.Pattern;
/**
* An interface for a Corporea Request matcher. Accepts an ItemStack and returns whether it fulfills the request.
* Needs to be registered over in
* {@link vazkii.botania.common.block.tile.corporea.TileCorporeaRetainer#addCorporeaRequestMatcher}.
*/
public final class CorporeaRequestDefaultMatchers {
public static class CorporeaStringMatcher implements ICorporeaRequestMatcher {
private static final Pattern patternControlCode = Pattern.compile("(?i)\\u00A7[0-9A-FK-OR]");
public static final String[] WILDCARD_STRINGS = { "...", "~", "+", "?", "*" };
private static final String TAG_REQUEST_CONTENTS = "requestContents";
private static final String TAG_REQUEST_CONTAINS = "requestContains";
private final String expression;
private final boolean contains;
public CorporeaStringMatcher(String expression) {
boolean contains = false;
for (String wc : WILDCARD_STRINGS) {
if (expression.endsWith(wc)) {
contains = true;
expression = expression.substring(0, expression.length() - wc.length());
} else if (expression.startsWith(wc)) {
contains = true;
expression = expression.substring(wc.length());
}
if (contains) {
break;
}
}
this.expression = expression;
this.contains = contains;
}
private CorporeaStringMatcher(String expression, boolean contains) {
this.expression = expression;
this.contains = contains;
}
@Override
public boolean isStackValid(ItemStack stack) {
if (stack.isEmpty()) {
return false;
}
String name = stripControlCodes(stack.getDisplayName().getString().toLowerCase().trim());
return equalOrContain(name)
|| equalOrContain(name + "s")
|| equalOrContain(name + "es")
|| name.endsWith("y") && equalOrContain(name.substring(0, name.length() - 1) + "ies");
}
public static ICorporeaRequestMatcher createFromNBT(CompoundNBT tag) {
String expression = tag.getString(TAG_REQUEST_CONTENTS);
boolean contains = tag.getBoolean(TAG_REQUEST_CONTAINS);
return new CorporeaStringMatcher(expression, contains);
}
@Override
public void writeToNBT(CompoundNBT tag) {
tag.putString(TAG_REQUEST_CONTENTS, expression);
tag.putBoolean(TAG_REQUEST_CONTAINS, contains);
}
@Override
@SuppressWarnings("deprecation")
public ITextComponent getRequestName() {
return new StringTextComponent(WordUtils.capitalizeFully(expression));
}
private boolean equalOrContain(String str) {
return contains ? str.contains(expression) : str.equals(expression);
}
// Copy from StringUtils
private static String stripControlCodes(String str) {
return patternControlCode.matcher(str).replaceAll("");
}
}
public static class CorporeaItemStackMatcher implements ICorporeaRequestMatcher {
private static final String TAG_REQUEST_STACK = "requestStack";
private static final String TAG_REQUEST_CHECK_NBT = "requestCheckNBT";
private final ItemStack match;
private final boolean checkNBT;
public CorporeaItemStackMatcher(ItemStack match, boolean checkNBT) {
this.match = match;
this.checkNBT = checkNBT;
}
@Override
public boolean isStackValid(ItemStack stack) {
return !stack.isEmpty() && !match.isEmpty() && stack.isItemEqual(match) && (!checkNBT || ItemNBTHelper.matchTag(match.getTag(), stack.getTag()));
}
public static ICorporeaRequestMatcher createFromNBT(CompoundNBT tag) {
return new CorporeaItemStackMatcher(ItemStack.read(tag.getCompound(TAG_REQUEST_STACK)), tag.getBoolean(TAG_REQUEST_CHECK_NBT));
}
@Override
public void writeToNBT(CompoundNBT tag) {
CompoundNBT cmp = match.write(new CompoundNBT());
tag.put(TAG_REQUEST_STACK, cmp);
tag.putBoolean(TAG_REQUEST_CHECK_NBT, checkNBT);
}
@Override
public ITextComponent getRequestName() {
return match.getTextComponent();
}
}
private CorporeaRequestDefaultMatchers() {}
}
@@ -17,19 +17,34 @@ import net.minecraftforge.eventbus.api.Event;
@Cancelable
public class CorporeaRequestEvent extends Event {
public final ICorporeaRequestMatcher request;
public final int count;
public final ICorporeaSpark spark;
/**
* If false then items won't be pulled.
*/
public final boolean realRequest;
private final ICorporeaRequestMatcher matcher;
private final int count;
private final ICorporeaSpark spark;
private final boolean dryRun;
public CorporeaRequestEvent(ICorporeaRequestMatcher request, int count, ICorporeaSpark spark, boolean real) {
this.request = request;
public CorporeaRequestEvent(ICorporeaRequestMatcher matcher, int count, ICorporeaSpark spark, boolean dryRun) {
this.matcher = matcher;
this.count = count;
this.spark = spark;
realRequest = real;
this.dryRun = dryRun;
}
public ICorporeaRequestMatcher getMatcher() {
return matcher;
}
public int getCount() {
return count;
}
public ICorporeaSpark getSpark() {
return spark;
}
/**
* @return {@code false} if this is a dry run, else {@code true}.
*/
public boolean isDryRun() {
return dryRun;
}
}
@@ -0,0 +1,34 @@
/*
* This class is distributed as part of the Botania Mod.
* Get the Source Code in github:
* https://github.com/Vazkii/Botania
*
* Botania is Open Source and distributed under the
* Botania License: http://botaniamod.net/license.php
*/
package vazkii.botania.api.corporea;
public interface ICorporeaRequest {
ICorporeaRequestMatcher getMatcher();
/**
* @return The amount still wanted by the request, -1 if the request wants everything matched by {@link #getMatcher}.
*/
int getStillNeeded();
int getFound();
int getExtracted();
/**
* Inform the request that {@code count} items have been satisfied,
* updating the result of {@link #getStillNeeded()}.
*/
void trackSatisfied(int count);
void trackFound(int count);
void trackExtracted(int count);
}
@@ -11,28 +11,33 @@ package vazkii.botania.api.corporea;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
/**
* An interface for a Corporea Request matcher. Accepts an ItemStack and returns whether it fulfills the request.
* Needs to be registered over in
* {@link vazkii.botania.common.block.tile.corporea.TileCorporeaRetainer#addCorporeaRequestMatcher}.
* Needs one additional (static) method for deserialization, which can't really go here because Java doesn't like static
* abstract's.
*/
public interface ICorporeaRequestMatcher {
/**
* Returns whether the given stack matches the request's criteria.
*/
boolean isStackValid(ItemStack stack);
default boolean isStackValid(ItemStack stack) {
return false;
}
/**
* Serialize to NBT data, for the Corporea Retainer's benefit.
*/
void writeToNBT(CompoundNBT tag);
default void writeToNBT(CompoundNBT tag) {}
/**
* Returns the pretty name of the requested item, for printing request feedback on Corporea Indexes.
*/
ITextComponent getRequestName();
default ITextComponent getRequestName() {
return new StringTextComponent("missingno");
}
enum Dummy implements ICorporeaRequestMatcher {
INSTANCE
}
}
@@ -15,9 +15,9 @@ package vazkii.botania.api.corporea;
*/
public interface ICorporeaRequestor {
/*
/**
* Executes the passed in request.
*/
public void doCorporeaRequest(ICorporeaRequestMatcher request, int count, ICorporeaSpark spark);
void doCorporeaRequest(ICorporeaRequestMatcher request, int count, ICorporeaSpark spark);
}
@@ -0,0 +1,36 @@
package vazkii.botania.api.corporea;
import net.minecraft.item.ItemStack;
import java.util.Collections;
import java.util.List;
/**
* Represents a completed {@link ICorporeaRequest}
*/
public interface ICorporeaResult {
/**
* @return The itemstacks found. Not a fresh copy each time called.
*/
default List<ItemStack> getStacks() {
return Collections.emptyList();
}
/**
* @return The number of items matching the request's matcher.
*/
default int getMatchedCount() {
return 0;
}
/**
* @return The number of items extracted.
*/
default int getExtractedCount() {
return 0;
}
enum Dummy implements ICorporeaResult {
INSTANCE
}
}
@@ -32,12 +32,12 @@ public interface ICorporeaSpark {
* at that point the connection list in the master spark would be cleared out, also clearing out the one
* in this instance, as it should be a pointer.
*/
public void registerConnections(ICorporeaSpark master, ICorporeaSpark referrer, List<ICorporeaSpark> connections);
void registerConnections(ICorporeaSpark master, ICorporeaSpark referrer, List<ICorporeaSpark> connections);
/**
* Gets the inventory this spark is bound to, generally the one right below it.
*/
public InvWithLocation getSparkInventory();
InvWithLocation getSparkInventory();
/**
* Gets the list of sparks this spark is connected to, see registerConnections(). This list
@@ -45,42 +45,42 @@ public interface ICorporeaSpark {
* that the spark is still in the network, if that's not the case, the pointer should be
* eliminated.
*/
public List<ICorporeaSpark> getConnections();
List<ICorporeaSpark> getConnections();
/**
* Gets the list of sparks that this spark added to the list of connections during registerConnections(), this
* is mainly used to create a non messy chain of particles to display the network when a spark is right
* clicked with a wand.
*/
public List<ICorporeaSpark> getRelatives();
List<ICorporeaSpark> getRelatives();
/**
* Gets the master spark in this network, see registerConnections(). The value this returns
* should be null and the pointer should be eliminated if the spark is no longer present
* in the network.
*/
public ICorporeaSpark getMaster();
ICorporeaSpark getMaster();
/**
* Called when an item is extracted from the inventory this spark is attached to through this
* spark.
*/
public void onItemExtracted(ItemStack stack);
void onItemExtracted(ItemStack stack);
/**
* Called when this spark requests items, passes in the result of the request and not the actual requested stack(s).
*/
public void onItemsRequested(List<ItemStack> stacks);
void onItemsRequested(List<ItemStack> stacks);
/**
* Gets if this spark is considered a master spark.
*/
public boolean isMaster();
boolean isMaster();
/**
* Gets the network that this spark is on, or the color it's displaying. Sparks may only connect to others
* of the same network, and on changing network should trigger a re-cache of the previous network.
*/
public DyeColor getNetwork();
DyeColor getNetwork();
}
@@ -32,7 +32,7 @@ public interface IWrappedInventory {
* purposes of counting huge amounts. To get final count requestor
* should sum stackSize of all stacks.
*/
List<ItemStack> countItems(CorporeaRequest request);
List<ItemStack> countItems(ICorporeaRequest request);
/**
* Convenience method for accessing spark over inventory
@@ -41,14 +41,14 @@ public interface IWrappedInventory {
/**
* Extracts items matching request from the inventory.<br/>
* {@link CorporeaRequest#count} is updated to reflect how many items are
* {@link ICorporeaRequest#stillNeeded} is updated to reflect how many items are
* yet to be extracted.<br/>
* {@link CorporeaRequest#foundItems} and
* {@link CorporeaRequest#extractedItems} are updated to reflect how many
* {@link ICorporeaRequest#foundItems} and
* {@link ICorporeaRequest#extractedItems} are updated to reflect how many
* items were found and extracted.
*
* @param request
* @return List of ItemStacks to be delivered to the destination.
*/
List<ItemStack> extractItems(CorporeaRequest request);
List<ItemStack> extractItems(ICorporeaRequest request);
}
@@ -14,27 +14,38 @@ import net.minecraftforge.items.IItemHandler;
public class InvWithLocation {
public final IItemHandler handler;
public final World world;
public final BlockPos pos;
private final IItemHandler handler;
private final World world;
private final BlockPos pos;
public InvWithLocation(IItemHandler itemHandler, World world, BlockPos pos) {
handler = itemHandler;
this.handler = itemHandler;
this.world = world;
this.pos = pos;
}
@Override
public int hashCode() {
return 31 * handler.hashCode() ^ world.hashCode() ^ pos.hashCode();
return 31 * getHandler().hashCode() ^ getWorld().hashCode() ^ getPos().hashCode();
}
@Override
public boolean equals(Object o) {
return o instanceof InvWithLocation
&& handler.equals(((InvWithLocation) o).handler)
&& world == ((InvWithLocation) o).world
&& pos.equals(((InvWithLocation) o).pos);
&& getHandler().equals(((InvWithLocation) o).getHandler())
&& getWorld() == ((InvWithLocation) o).getWorld()
&& getPos().equals(((InvWithLocation) o).getPos());
}
public IItemHandler getHandler() {
return handler;
}
public World getWorld() {
return world;
}
public BlockPos getPos() {
return pos;
}
}
@@ -33,6 +33,7 @@ import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import vazkii.botania.api.BotaniaAPI;
import vazkii.botania.api.corporea.CorporeaHelper;
import vazkii.botania.common.core.helper.ColorHelper;
import vazkii.botania.api.capability.FloatingFlowerImpl;
import vazkii.botania.api.item.IExoflameHeatable;
@@ -68,6 +69,8 @@ import vazkii.botania.common.core.loot.TrueGuardianKiller;
import vazkii.botania.common.core.proxy.IProxy;
import vazkii.botania.common.core.proxy.ServerProxy;
import vazkii.botania.common.crafting.FluxfieldCondition;
import vazkii.botania.common.impl.corporea.CorporeaItemStackMatcher;
import vazkii.botania.common.impl.corporea.CorporeaStringMatcher;
import vazkii.botania.common.lib.LibMisc;
import vazkii.botania.common.network.PacketHandler;
import vazkii.botania.common.world.ModFeatures;
@@ -78,6 +81,8 @@ import vazkii.patchouli.api.IStateMatcher;
import vazkii.patchouli.api.PatchouliAPI;
import vazkii.patchouli.common.multiblock.StateMatcher;
import static vazkii.botania.common.lib.ResourceLocationHelper.prefix;
@Mod(LibMisc.MOD_ID)
public class Botania {
@@ -136,6 +141,8 @@ public class Botania {
MinecraftForge.EVENT_BUS.register(new LootHandler());
EquipmentHandler.init();
CorporeaHelper.instance().registerRequestMatcher(prefix("string"), CorporeaStringMatcher.class, CorporeaStringMatcher::createFromNBT);
CorporeaHelper.instance().registerRequestMatcher(prefix("item_stack"), CorporeaItemStackMatcher.class, CorporeaItemStackMatcher::createFromNBT);
if (Botania.gardenOfGlassLoaded) {
MinecraftForge.EVENT_BUS.register(SkyblockWorldEvents.class);
@@ -94,7 +94,7 @@ public class SubTileHopperhock extends TileEntityFunctionalFlower {
List<ItemStack> filter = getFilterForInventory(pos_, true);
boolean canAccept = canAcceptItem(stack, filter, filterType);
ItemStack simulate = ItemHandlerHelper.insertItem(inv.handler, stack, true);
ItemStack simulate = ItemHandlerHelper.insertItem(inv.getHandler(), stack, true);
int availablePut = stack.getCount() - simulate.getCount();
canAccept &= availablePut > 0;
@@ -107,7 +107,7 @@ public class SubTileHopperhock extends TileEntityFunctionalFlower {
break setInv;
}
invToPutItemIn = inv.handler;
invToPutItemIn = inv.getHandler();
priorityInv = priority;
amountToPutIn = availablePut;
}
@@ -27,7 +27,7 @@ public abstract class TileCorporeaBase extends TileSimpleInventory {
}
public ICorporeaSpark getSpark() {
return CorporeaHelper.getSparkForBlock(world, getPos());
return CorporeaHelper.instance().getSparkForBlock(world, getPos());
}
}
@@ -78,7 +78,7 @@ public class TileCorporeaCrystalCube extends TileCorporeaBase implements ICorpor
ICorporeaSpark spark = getSpark();
if (spark != null && spark.getMaster() != null && requestTarget != null) {
int count = fullStack ? requestTarget.getMaxStackSize() : 1;
doCorporeaRequest(CorporeaHelper.createMatcher(requestTarget, true), count, spark);
doCorporeaRequest(CorporeaHelper.instance().createMatcher(requestTarget, true), count, spark);
}
}
@@ -91,7 +91,7 @@ public class TileCorporeaCrystalCube extends TileCorporeaBase implements ICorpor
itemCount = 0;
ICorporeaSpark spark = getSpark();
if (spark != null && spark.getMaster() != null && requestTarget != null) {
List<ItemStack> stacks = CorporeaHelper.requestItem(CorporeaHelper.createMatcher(requestTarget, true), -1, spark, false);
List<ItemStack> stacks = CorporeaHelper.instance().requestItem(CorporeaHelper.instance().createMatcher(requestTarget, true), -1, spark, false).getStacks();
for (ItemStack stack : stacks) {
itemCount += stack.getCount();
}
@@ -105,7 +105,7 @@ public class TileCorporeaCrystalCube extends TileCorporeaBase implements ICorpor
private void onUpdateCount() {
int oldCompValue = compValue;
compValue = CorporeaHelper.signalStrengthForRequestSize(itemCount);
compValue = CorporeaHelper.instance().signalStrengthForRequestSize(itemCount);
if (compValue != oldCompValue) {
world.updateComparatorOutputLevel(pos, getBlockState().getBlock());
}
@@ -138,7 +138,7 @@ public class TileCorporeaCrystalCube extends TileCorporeaBase implements ICorpor
@Override
public void doCorporeaRequest(ICorporeaRequestMatcher request, int count, ICorporeaSpark spark) {
List<ItemStack> stacks = CorporeaHelper.requestItem(request, count, spark, true);
List<ItemStack> stacks = CorporeaHelper.instance().requestItem(request, count, spark, true).getStacks();
spark.onItemsRequested(stacks);
boolean did = false;
for (ItemStack reqStack : stacks) {
@@ -45,7 +45,7 @@ public class TileCorporeaFunnel extends TileCorporeaBase implements ICorporeaReq
ItemStack stack = filter.get(world.rand.nextInt(filter.size()));
if (!stack.isEmpty()) {
doCorporeaRequest(CorporeaHelper.createMatcher(stack, true), stack.getCount(), spark);
doCorporeaRequest(CorporeaHelper.instance().createMatcher(stack, true), stack.getCount(), spark);
}
}
}
@@ -80,7 +80,7 @@ public class TileCorporeaFunnel extends TileCorporeaBase implements ICorporeaReq
public void doCorporeaRequest(ICorporeaRequestMatcher request, int count, ICorporeaSpark spark) {
IItemHandler inv = getInv();
List<ItemStack> stacks = CorporeaHelper.requestItem(request, count, spark, true);
List<ItemStack> stacks = CorporeaHelper.instance().requestItem(request, count, spark, true).getStacks();
spark.onItemsRequested(stacks);
for (ItemStack reqStack : stacks) {
if (inv != null && ItemHandlerHelper.insertItemStacked(inv, reqStack, true).isEmpty()) {
@@ -23,11 +23,7 @@ import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.registries.ObjectHolder;
import vazkii.botania.api.corporea.CorporeaHelper;
import vazkii.botania.api.corporea.CorporeaIndexRequestEvent;
import vazkii.botania.api.corporea.ICorporeaRequestMatcher;
import vazkii.botania.api.corporea.ICorporeaRequestor;
import vazkii.botania.api.corporea.ICorporeaSpark;
import vazkii.botania.api.corporea.*;
import vazkii.botania.common.advancements.CorporeaRequestTrigger;
import vazkii.botania.common.core.helper.MathHelper;
import vazkii.botania.common.lib.LibBlockNames;
@@ -323,7 +319,12 @@ public class TileCorporeaIndex extends TileCorporeaBase implements ICorporeaRequ
@Override
public void doCorporeaRequest(ICorporeaRequestMatcher request, int count, ICorporeaSpark spark) {
List<ItemStack> stacks = CorporeaHelper.requestItem(request, count, spark, true);
doRequest(request, count, spark);
}
private ICorporeaResult doRequest(ICorporeaRequestMatcher matcher, int count, ICorporeaSpark spark) {
ICorporeaResult result = CorporeaHelper.instance().requestItem(matcher, count, spark, true);
List<ItemStack> stacks = result.getStacks();
spark.onItemsRequested(stacks);
for (ItemStack stack : stacks) {
if (!stack.isEmpty()) {
@@ -331,6 +332,7 @@ public class TileCorporeaIndex extends TileCorporeaBase implements ICorporeaRequ
world.addEntity(item);
}
}
return result;
}
public static boolean isInRangeOfIndex(PlayerEntity player, TileCorporeaIndex index) {
@@ -370,10 +372,10 @@ public class TileCorporeaIndex extends TileCorporeaBase implements ICorporeaRequ
public void performPlayerRequest(ServerPlayerEntity player, ICorporeaRequestMatcher request, int count) {
CorporeaIndexRequestEvent indexReqEvent = new CorporeaIndexRequestEvent(player, request, count, this.getSpark());
if (!MinecraftForge.EVENT_BUS.post(indexReqEvent)) {
this.doCorporeaRequest(request, count, this.getSpark());
ICorporeaResult res = this.doRequest(request, count, this.getSpark());
player.sendMessage(new TranslationTextComponent("botaniamisc.requestMsg", count, request.getRequestName(), CorporeaHelper.lastRequestMatches, CorporeaHelper.lastRequestExtractions).applyTextStyle(TextFormatting.LIGHT_PURPLE));
CorporeaRequestTrigger.INSTANCE.trigger(player, player.getServerWorld(), this.getPos(), CorporeaHelper.lastRequestExtractions);
player.sendMessage(new TranslationTextComponent("botaniamisc.requestMsg", count, request.getRequestName(), res.getMatchedCount(), res.getExtractedCount()).applyTextStyle(TextFormatting.LIGHT_PURPLE));
CorporeaRequestTrigger.INSTANCE.trigger(player, player.getServerWorld(), this.getPos(), res.getExtractedCount());
}
}
@@ -408,7 +410,7 @@ public class TileCorporeaIndex extends TileCorporeaBase implements ICorporeaRequ
}
}
index.performPlayerRequest(event.getPlayer(), CorporeaHelper.createMatcher(name), count);
index.performPlayerRequest(event.getPlayer(), CorporeaHelper.instance().createMatcher(name), count);
}
}
@@ -51,7 +51,7 @@ public class TileCorporeaInterceptor extends TileCorporeaBase implements ICorpor
world.setBlockState(getPos(), getBlockState().with(BotaniaStateProps.POWERED, true));
world.getPendingBlockTicks().scheduleTick(getPos(), getBlockState().getBlock(), getBlockState().getBlock().tickRate(world));
TileEntity requestor = source.getSparkInventory().world.getTileEntity(source.getSparkInventory().pos);
TileEntity requestor = source.getSparkInventory().getWorld().getTileEntity(source.getSparkInventory().getPos());
for (Direction dir : Direction.values()) {
TileEntity tile = world.getTileEntity(pos.offset(dir));
if (tile instanceof TileCorporeaRetainer) {
@@ -10,15 +10,14 @@ package vazkii.botania.common.block.tile.corporea;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.tileentity.TileEntityType;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.registries.ObjectHolder;
import vazkii.botania.api.corporea.CorporeaHelper;
import vazkii.botania.api.corporea.ICorporeaRequestMatcher;
import vazkii.botania.api.corporea.ICorporeaRequestor;
import vazkii.botania.api.corporea.ICorporeaSpark;
import vazkii.botania.api.corporea.InvWithLocation;
import vazkii.botania.api.corporea.*;
import vazkii.botania.common.block.tile.TileMod;
import vazkii.botania.common.impl.corporea.CorporeaItemStackMatcher;
import vazkii.botania.common.impl.corporea.CorporeaStringMatcher;
import vazkii.botania.common.lib.LibBlockNames;
import vazkii.botania.common.lib.LibMisc;
@@ -26,10 +25,9 @@ import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import static vazkii.botania.api.corporea.CorporeaRequestDefaultMatchers.*;
public class TileCorporeaRetainer extends TileMod {
@ObjectHolder(LibMisc.MOD_ID + ":" + LibBlockNames.CORPOREA_RETAINER) public static TileEntityType<TileCorporeaRetainer> TYPE;
private static final String TAG_REQUEST_X = "requestX";
@@ -38,19 +36,14 @@ public class TileCorporeaRetainer extends TileMod {
private static final String TAG_REQUEST_TYPE = "requestType";
private static final String TAG_REQUEST_COUNT = "requestCount";
public static final Map<String, Function<CompoundNBT, ICorporeaRequestMatcher>> corporeaMatcherDeserializers = new HashMap<>();
public static final Map<Class<?>, String> corporeaMatcherSerializers = new HashMap<>();
private static final Map<ResourceLocation, Function<CompoundNBT, ? extends ICorporeaRequestMatcher>> corporeaMatcherDeserializers = new ConcurrentHashMap<>();
private static final Map<Class<? extends ICorporeaRequestMatcher>, ResourceLocation> corporeaMatcherSerializers = new ConcurrentHashMap<>();
private BlockPos requestPos = BlockPos.ZERO;
@Nullable private ICorporeaRequestMatcher request;
private int requestCount;
private int compValue;
static {
addCorporeaRequestMatcher("string", CorporeaStringMatcher.class, CorporeaStringMatcher::createFromNBT);
addCorporeaRequestMatcher("item_stack", CorporeaItemStackMatcher.class, CorporeaItemStackMatcher::createFromNBT);
}
public TileCorporeaRetainer() {
super(TYPE);
}
@@ -64,7 +57,7 @@ public class TileCorporeaRetainer extends TileMod {
this.request = request;
this.requestCount = requestCount;
compValue = CorporeaHelper.signalStrengthForRequestSize(requestCount);
compValue = CorporeaHelper.instance().signalStrengthForRequestSize(requestCount);
world.updateComparatorOutputLevel(getPos(), getBlockState().getBlock());
}
@@ -81,11 +74,11 @@ public class TileCorporeaRetainer extends TileMod {
return;
}
ICorporeaSpark spark = CorporeaHelper.getSparkForBlock(world, requestPos);
ICorporeaSpark spark = CorporeaHelper.instance().getSparkForBlock(world, requestPos);
if (spark != null) {
InvWithLocation inv = spark.getSparkInventory();
if (inv != null && inv.world.getTileEntity(inv.pos) instanceof ICorporeaRequestor) {
ICorporeaRequestor requestor = (ICorporeaRequestor) inv.world.getTileEntity(inv.pos);
if (inv != null && inv.getWorld().getTileEntity(inv.getPos()) instanceof ICorporeaRequestor) {
ICorporeaRequestor requestor = (ICorporeaRequestor) inv.getWorld().getTileEntity(inv.getPos());
requestor.doCorporeaRequest(request, requestCount, spark);
request = null;
@@ -104,14 +97,13 @@ public class TileCorporeaRetainer extends TileMod {
cmp.putInt(TAG_REQUEST_Y, requestPos.getY());
cmp.putInt(TAG_REQUEST_Z, requestPos.getZ());
String reqType = request != null ? corporeaMatcherSerializers.getOrDefault(request.getClass(), "") : "";
ResourceLocation reqType = request != null ? corporeaMatcherSerializers.get(request.getClass()) : null;
cmp.putString(TAG_REQUEST_TYPE, reqType);
if (reqType.length() > 0) {
if (reqType != null) {
cmp.putString(TAG_REQUEST_TYPE, reqType.toString());
request.writeToNBT(cmp);
cmp.putInt(TAG_REQUEST_COUNT, requestCount);
}
cmp.putInt(TAG_REQUEST_COUNT, requestCount);
}
@Override
@@ -123,8 +115,8 @@ public class TileCorporeaRetainer extends TileMod {
int z = cmp.getInt(TAG_REQUEST_Z);
requestPos = new BlockPos(x, y, z);
String reqType = cmp.getString(TAG_REQUEST_TYPE);
if (corporeaMatcherDeserializers.containsKey(reqType)) {
ResourceLocation reqType = ResourceLocation.tryCreate(cmp.getString(TAG_REQUEST_TYPE));
if (reqType != null && corporeaMatcherDeserializers.containsKey(reqType)) {
request = corporeaMatcherDeserializers.get(reqType).apply(cmp);
} else {
request = null;
@@ -132,9 +124,9 @@ public class TileCorporeaRetainer extends TileMod {
requestCount = cmp.getInt(TAG_REQUEST_COUNT);
}
public static void addCorporeaRequestMatcher(String type, Class<?> clazz, Function<CompoundNBT, ICorporeaRequestMatcher> deserializer) {
corporeaMatcherSerializers.put(clazz, type);
corporeaMatcherDeserializers.put(type, deserializer);
public static <T extends ICorporeaRequestMatcher> void addCorporeaRequestMatcher(ResourceLocation id, Class<T> clazz, Function<CompoundNBT, T> deserializer) {
corporeaMatcherSerializers.put(clazz, id);
corporeaMatcherDeserializers.put(id, deserializer);
}
}
@@ -13,6 +13,7 @@ import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import vazkii.botania.api.corporea.CorporeaHelper;
import vazkii.botania.common.impl.corporea.CorporeaHelperImpl;
import vazkii.botania.common.lib.LibMisc;
@Mod.EventBusSubscriber(modid = LibMisc.MOD_ID)
@@ -23,7 +24,7 @@ public final class CommonTickHandler {
@SubscribeEvent
public static void onTick(TickEvent.WorldTickEvent event) {
if (event.phase == TickEvent.Phase.END) {
CorporeaHelper.clearCache();
((CorporeaHelperImpl) CorporeaHelper.instance()).clearCache();
}
}
@@ -113,7 +113,7 @@ public class InternalMethodHandler extends DummyMethodHandler {
public List<IWrappedInventory> wrapInventory(List<InvWithLocation> inventories) {
List<IWrappedInventory> arrayList = new ArrayList<IWrappedInventory>();
for (InvWithLocation inv : inventories) {
ICorporeaSpark spark = CorporeaHelper.getSparkForInventory(inv);
ICorporeaSpark spark = CorporeaHelper.instance().getSparkForInventory(inv);
IWrappedInventory wrapped = null;
// try integrations
@@ -0,0 +1,179 @@
package vazkii.botania.common.impl.corporea;
import com.google.common.base.Predicates;
import net.minecraft.entity.Entity;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import vazkii.botania.api.BotaniaAPI;
import vazkii.botania.api.corporea.*;
import vazkii.botania.common.block.tile.corporea.TileCorporeaRetainer;
import java.util.*;
import java.util.function.Function;
public class CorporeaHelperImpl implements CorporeaHelper {
private final WeakHashMap<List<ICorporeaSpark>, List<InvWithLocation>> cachedNetworks = new WeakHashMap<>();
@Override
public List<InvWithLocation> getInventoriesOnNetwork(ICorporeaSpark spark) {
ICorporeaSpark master = spark.getMaster();
if (master == null) {
return Collections.emptyList();
}
List<ICorporeaSpark> network = master.getConnections();
if (cachedNetworks.containsKey(network)) {
List<InvWithLocation> cache = cachedNetworks.get(network);
if (cache != null) {
return cache;
}
}
List<InvWithLocation> inventories = new ArrayList<>();
if (network != null) {
for (ICorporeaSpark otherSpark : network) {
if (otherSpark != null) {
InvWithLocation inv = otherSpark.getSparkInventory();
if (inv != null) {
inventories.add(inv);
}
}
}
}
cachedNetworks.put(network, inventories);
return inventories;
}
@Override
public int getCountInNetwork(ICorporeaRequestMatcher matcher, ICorporeaSpark spark) {
List<InvWithLocation> inventories = getInventoriesOnNetwork(spark);
return getCountInNetwork(matcher, inventories);
}
@Override
public int getCountInNetwork(ICorporeaRequestMatcher matcher, List<InvWithLocation> inventories) {
Map<InvWithLocation, Integer> map = getInventoriesWithMatchInNetwork(matcher, inventories);
return getCountInNetwork(matcher, map);
}
@Override
public int getCountInNetwork(ICorporeaRequestMatcher matcher, Map<InvWithLocation, Integer> inventories) {
int count = 0;
for (int value : inventories.values()) {
count += value;
}
return count;
}
@Override
public Map<InvWithLocation, Integer> getInventoriesWithMatchInNetwork(ICorporeaRequestMatcher matcher, ICorporeaSpark spark) {
List<InvWithLocation> inventories = getInventoriesOnNetwork(spark);
return getInventoriesWithMatchInNetwork(matcher, inventories);
}
@Override
public Map<InvWithLocation, Integer> getInventoriesWithMatchInNetwork(ICorporeaRequestMatcher matcher, List<InvWithLocation> inventories) {
Map<InvWithLocation, Integer> countMap = new HashMap<>();
List<IWrappedInventory> wrappedInventories = BotaniaAPI.internalHandler.wrapInventory(inventories);
for (IWrappedInventory inv : wrappedInventories) {
ICorporeaRequest request = new CorporeaRequest(matcher, -1);
inv.countItems(request);
if (request.getFound() > 0) {
countMap.put(inv.getWrappedObject(), request.getFound());
}
}
return countMap;
}
@Override
public ICorporeaRequestMatcher createMatcher(ItemStack stack, boolean checkNBT) {
return new CorporeaItemStackMatcher(stack, checkNBT);
}
@Override
public ICorporeaRequestMatcher createMatcher(String name) {
return new CorporeaStringMatcher(name);
}
@Override
public ICorporeaResult requestItem(ICorporeaRequestMatcher matcher, int itemCount, ICorporeaSpark spark, boolean doit) {
List<ItemStack> stacks = new ArrayList<>();
CorporeaRequestEvent event = new CorporeaRequestEvent(matcher, itemCount, spark, !doit);
if (MinecraftForge.EVENT_BUS.post(event)) {
return new CorporeaResult(stacks, 0, 0); // todo 1.15 what to do here
}
List<InvWithLocation> inventories = getInventoriesOnNetwork(spark);
List<IWrappedInventory> inventoriesW = BotaniaAPI.internalHandler.wrapInventory(inventories);
Map<ICorporeaInterceptor, ICorporeaSpark> interceptors = new HashMap<>();
ICorporeaRequest request = new CorporeaRequest(matcher, itemCount);
for (IWrappedInventory inv : inventoriesW) {
ICorporeaSpark invSpark = inv.getSpark();
InvWithLocation originalInventory = inv.getWrappedObject();
if (originalInventory.getWorld().getTileEntity(originalInventory.getPos()) instanceof ICorporeaInterceptor) {
ICorporeaInterceptor interceptor = (ICorporeaInterceptor) originalInventory.getWorld().getTileEntity(originalInventory.getPos());
interceptor.interceptRequest(matcher, itemCount, invSpark, spark, stacks, inventories, doit);
interceptors.put(interceptor, invSpark);
}
if (doit) {
stacks.addAll(inv.extractItems(request));
} else {
stacks.addAll(inv.countItems(request));
}
}
for (ICorporeaInterceptor interceptor : interceptors.keySet()) {
interceptor.interceptRequestLast(matcher, itemCount, interceptors.get(interceptor), spark, stacks, inventories, doit);
}
return new CorporeaResult(stacks, request.getFound(), request.getExtracted());
}
@Override
public ICorporeaSpark getSparkForInventory(InvWithLocation inv) {
TileEntity tile = inv.getWorld().getTileEntity(inv.getPos());
return getSparkForBlock(tile.getWorld(), tile.getPos());
}
@Override
public ICorporeaSpark getSparkForBlock(World world, BlockPos pos) {
List<Entity> sparks = world.getEntitiesWithinAABB(Entity.class, new AxisAlignedBB(pos.up(), pos.add(1, 2, 1)), Predicates.instanceOf(ICorporeaSpark.class));
return sparks.isEmpty() ? null : (ICorporeaSpark) sparks.get(0);
}
@Override
public int signalStrengthForRequestSize(int requestSize) {
if (requestSize <= 0) {
return 0;
} else if (requestSize >= 16384) {
return 15;
} else {
return Math.min(15, MathHelper.log2(requestSize) + 1);
}
}
@Override
public <T extends ICorporeaRequestMatcher> void registerRequestMatcher(ResourceLocation id, Class<T> clazz, Function<CompoundNBT, T> deserializer) {
TileCorporeaRetainer.addCorporeaRequestMatcher(id, clazz, deserializer);
}
public void clearCache() {
cachedNetworks.clear();
}
}
@@ -0,0 +1,41 @@
package vazkii.botania.common.impl.corporea;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.text.ITextComponent;
import vazkii.botania.api.corporea.ICorporeaRequestMatcher;
import vazkii.botania.common.core.helper.ItemNBTHelper;
public class CorporeaItemStackMatcher implements ICorporeaRequestMatcher {
private static final String TAG_REQUEST_STACK = "requestStack";
private static final String TAG_REQUEST_CHECK_NBT = "requestCheckNBT";
private final ItemStack match;
private final boolean checkNBT;
public CorporeaItemStackMatcher(ItemStack match, boolean checkNBT) {
this.match = match;
this.checkNBT = checkNBT;
}
@Override
public boolean isStackValid(ItemStack stack) {
return !stack.isEmpty() && !match.isEmpty() && stack.isItemEqual(match) && (!checkNBT || ItemNBTHelper.matchTag(match.getTag(), stack.getTag()));
}
public static CorporeaItemStackMatcher createFromNBT(CompoundNBT tag) {
return new CorporeaItemStackMatcher(ItemStack.read(tag.getCompound(TAG_REQUEST_STACK)), tag.getBoolean(TAG_REQUEST_CHECK_NBT));
}
@Override
public void writeToNBT(CompoundNBT tag) {
CompoundNBT cmp = match.write(new CompoundNBT());
tag.put(TAG_REQUEST_STACK, cmp);
tag.putBoolean(TAG_REQUEST_CHECK_NBT, checkNBT);
}
@Override
public ITextComponent getRequestName() {
return match.getTextComponent();
}
}
@@ -0,0 +1,53 @@
package vazkii.botania.common.impl.corporea;
import vazkii.botania.api.corporea.ICorporeaRequest;
import vazkii.botania.api.corporea.ICorporeaRequestMatcher;
public class CorporeaRequest implements ICorporeaRequest {
private final ICorporeaRequestMatcher matcher;
private int stillNeeded;
private int foundItems = 0;
private int extractedItems = 0;
public CorporeaRequest(ICorporeaRequestMatcher matcher, int stillNeeded) {
this.matcher = matcher;
this.stillNeeded = stillNeeded;
}
@Override
public ICorporeaRequestMatcher getMatcher() {
return matcher;
}
@Override
public int getStillNeeded() {
return stillNeeded;
}
@Override
public int getFound() {
return foundItems;
}
@Override
public int getExtracted() {
return extractedItems;
}
@Override
public void trackSatisfied(int count) {
if (stillNeeded != -1) {
stillNeeded -= count;
}
}
@Override
public void trackFound(int count) {
foundItems += count;
}
@Override
public void trackExtracted(int count) {
extractedItems += count;
}
}
@@ -0,0 +1,33 @@
package vazkii.botania.common.impl.corporea;
import net.minecraft.item.ItemStack;
import vazkii.botania.api.corporea.ICorporeaResult;
import java.util.List;
public class CorporeaResult implements ICorporeaResult {
private final List<ItemStack> stacks;
private final int matched;
private final int extracted;
public CorporeaResult(List<ItemStack> stacks, int matched, int extracted) {
this.stacks = stacks;
this.matched = matched;
this.extracted = extracted;
}
@Override
public List<ItemStack> getStacks() {
return stacks;
}
@Override
public int getMatchedCount() {
return matched;
}
@Override
public int getExtractedCount() {
return extracted;
}
}
@@ -0,0 +1,85 @@
package vazkii.botania.common.impl.corporea;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import org.apache.commons.lang3.text.WordUtils;
import vazkii.botania.api.corporea.ICorporeaRequestMatcher;
import java.util.regex.Pattern;
public class CorporeaStringMatcher implements ICorporeaRequestMatcher {
private static final Pattern patternControlCode = Pattern.compile("(?i)\\u00A7[0-9A-FK-OR]");
public static final String[] WILDCARD_STRINGS = { "...", "~", "+", "?", "*" };
private static final String TAG_REQUEST_CONTENTS = "requestContents";
private static final String TAG_REQUEST_CONTAINS = "requestContains";
private final String expression;
private final boolean contains;
public CorporeaStringMatcher(String expression) {
boolean contains = false;
for (String wc : WILDCARD_STRINGS) {
if (expression.endsWith(wc)) {
contains = true;
expression = expression.substring(0, expression.length() - wc.length());
} else if (expression.startsWith(wc)) {
contains = true;
expression = expression.substring(wc.length());
}
if (contains) {
break;
}
}
this.expression = expression;
this.contains = contains;
}
private CorporeaStringMatcher(String expression, boolean contains) {
this.expression = expression;
this.contains = contains;
}
@Override
public boolean isStackValid(ItemStack stack) {
if (stack.isEmpty()) {
return false;
}
String name = stripControlCodes(stack.getDisplayName().getString().toLowerCase().trim());
return equalOrContain(name)
|| equalOrContain(name + "s")
|| equalOrContain(name + "es")
|| name.endsWith("y") && equalOrContain(name.substring(0, name.length() - 1) + "ies");
}
public static CorporeaStringMatcher createFromNBT(CompoundNBT tag) {
String expression = tag.getString(TAG_REQUEST_CONTENTS);
boolean contains = tag.getBoolean(TAG_REQUEST_CONTAINS);
return new CorporeaStringMatcher(expression, contains);
}
@Override
public void writeToNBT(CompoundNBT tag) {
tag.putString(TAG_REQUEST_CONTENTS, expression);
tag.putBoolean(TAG_REQUEST_CONTAINS, contains);
}
@Override
@SuppressWarnings("deprecation")
public ITextComponent getRequestName() {
return new StringTextComponent(WordUtils.capitalizeFully(expression));
}
private boolean equalOrContain(String str) {
return contains ? str.contains(expression) : str.equals(expression);
}
// Copy from StringUtils
private static String stripControlCodes(String str) {
return patternControlCode.matcher(str).replaceAll("");
}
}
@@ -10,7 +10,7 @@ package vazkii.botania.common.integration.corporea;
import net.minecraft.item.ItemStack;
import vazkii.botania.api.corporea.CorporeaRequest;
import vazkii.botania.api.corporea.ICorporeaRequest;
import vazkii.botania.api.corporea.ICorporeaSpark;
import vazkii.botania.api.corporea.IWrappedInventory;
import vazkii.botania.api.corporea.InvWithLocation;
@@ -33,38 +33,36 @@ public class WrappedIInventory extends WrappedInventoryBase {
}
@Override
public List<ItemStack> countItems(CorporeaRequest request) {
public List<ItemStack> countItems(ICorporeaRequest request) {
return iterateOverSlots(request, false);
}
@Override
public List<ItemStack> extractItems(CorporeaRequest request) {
public List<ItemStack> extractItems(ICorporeaRequest request) {
return iterateOverSlots(request, true);
}
protected List<ItemStack> iterateOverSlots(CorporeaRequest request, boolean doit) {
protected List<ItemStack> iterateOverSlots(ICorporeaRequest request, boolean doit) {
List<ItemStack> stacks = new ArrayList<ItemStack>();
for (int i = inv.handler.getSlots() - 1; i >= 0; i--) {
ItemStack stackAt = inv.handler.getStackInSlot(i);
for (int i = inv.getHandler().getSlots() - 1; i >= 0; i--) {
ItemStack stackAt = inv.getHandler().getStackInSlot(i);
// WARNING: this code is very similar in all implementations of
// IWrappedInventory - keep it synch
if (request.matcher.isStackValid(stackAt)) {
int rem = Math.min(stackAt.getCount(), request.count == -1 ? stackAt.getCount() : request.count);
request.foundItems += stackAt.getCount();
if (request.getMatcher().isStackValid(stackAt)) {
int rem = Math.min(stackAt.getCount(), request.getStillNeeded() == -1 ? stackAt.getCount() : request.getStillNeeded());
request.trackFound(stackAt.getCount());
if (rem > 0) {
stacks.add(inv.handler.extractItem(i, rem, !doit));
stacks.add(inv.getHandler().extractItem(i, rem, !doit));
if (doit && spark != null) {
spark.onItemExtracted(stackAt);
}
}
request.extractedItems += rem;
request.trackExtracted(rem);
if (request.count != -1) {
request.count -= rem;
}
request.trackSatisfied(rem);
}
}
@@ -38,7 +38,7 @@ public class ItemCorporeaSpark extends Item {
if (tile != null
&& (tile.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, Direction.UP).isPresent()
|| tile.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null).isPresent())
&& !CorporeaHelper.doesBlockHaveSpark(world, pos)) {
&& !CorporeaHelper.instance().doesBlockHaveSpark(world, pos)) {
ctx.getItem().shrink(1);
if (!world.isRemote) {
EntityCorporeaSpark spark = new EntityCorporeaSpark(world);
@@ -44,7 +44,7 @@ public class PacketIndexKeybindRequest {
boolean checkNBT = message.stack.getTag() != null && !message.stack.getTag().isEmpty();
for (TileCorporeaIndex index : TileCorporeaIndex.InputHandler.getNearbyIndexes(player)) {
if (index.getSpark() != null) {
index.performPlayerRequest(player, CorporeaHelper.createMatcher(message.stack, checkNBT), message.stack.getCount());
index.performPlayerRequest(player, CorporeaHelper.instance().createMatcher(message.stack, checkNBT), message.stack.getCount());
}
}
});