Skip to content

Commit

Permalink
Try to get block state without taking snapshots (#234)
Browse files Browse the repository at this point in the history
  • Loading branch information
NewwindServer authored Aug 5, 2024
1 parent 335d849 commit 8c15b3d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@
import org.bukkit.util.BoundingBox;
import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Method;

import static com.lishid.openinv.util.InventoryAccess.getBlockState;

public interface IAnySilentContainer {

/**
Expand Down Expand Up @@ -58,7 +62,7 @@ public interface IAnySilentContainer {
* @return true if the container is blocked
*/
default boolean isAnyContainerNeeded(@NotNull Block block) {
BlockState blockState = block.getState();
BlockState blockState = getBlockState(block);

// Barrels do not require AnyContainer.
if (blockState instanceof Barrel) {
Expand Down Expand Up @@ -148,7 +152,7 @@ default boolean isChestBlocked(@NotNull Block chest) {
* @return true if the type is a supported container
*/
default boolean isAnySilentContainer(@NotNull Block block) {
return isAnySilentContainer(block.getState());
return isAnySilentContainer(getBlockState(block));
}

/**
Expand Down
26 changes: 26 additions & 0 deletions api/src/main/java/com/lishid/openinv/util/InventoryAccess.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,42 @@
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialInventory;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.inventory.Inventory;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.function.BiFunction;

public final class InventoryAccess {

private static @Nullable BiFunction<Inventory, Class<? extends ISpecialInventory>, ISpecialInventory> provider;
private static Method blockGetStateNoSnapshotMethod;

static {
try {
blockGetStateNoSnapshotMethod = Block.class.getMethod("getState", boolean.class);
} catch (NoSuchMethodException e) {
blockGetStateNoSnapshotMethod = null;
}
}

public static BlockState getBlockState(Block block) {
// Try to get block state without snapshot (only available in paper currently)
if (blockGetStateNoSnapshotMethod != null) {
try {
return (BlockState) blockGetStateNoSnapshotMethod.invoke(block, false);
} catch (InvocationTargetException | IllegalAccessException e) {
return block.getState();
}
} else {
return block.getState();
}
}

public static boolean isUsable() {
return provider != null;
Expand Down

0 comments on commit 8c15b3d

Please sign in to comment.