Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve InventoryBehavior #4037

Draft
wants to merge 21 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/api/java/baritone/api/Settings.java
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,12 @@ public final class Settings {
*/
public final Setting<Boolean> allowInventory = new Setting<>(false);

/**
* Allow Baritone to automatically put useful items (such as tools and throwaway blocks) on the hotbar while
* pathing. Having this setting enabled implies {@link #allowInventory}.
*/
public final Setting<Boolean> allowHotbarManagement = new Setting<>(false);
ZeroMemes marked this conversation as resolved.
Show resolved Hide resolved

/**
* Wait this many ticks between InventoryBehavior moving inventory items
*/
Expand Down
33 changes: 33 additions & 0 deletions src/main/java/baritone/PerformanceCritical.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* This file is part of Baritone.
*
* Baritone 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.
*
* Baritone 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 Baritone. If not, see <https://www.gnu.org/licenses/>.
*/

package baritone;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* Annotation that should be used on methods which are performance critical (i.e. called millions of times per second
* by the pathfinder) and should be modified with care.
*
* @author Brady
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface PerformanceCritical {}
75 changes: 45 additions & 30 deletions src/main/java/baritone/behavior/InventoryBehavior.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,44 +33,52 @@
import java.util.ArrayList;
import java.util.OptionalInt;
import java.util.Random;
import java.util.function.IntPredicate;
import java.util.function.Predicate;

public final class InventoryBehavior extends Behavior implements Helper {

int ticksSinceLastInventoryMove;
int[] lastTickRequestedMove; // not everything asks every tick, so remember the request while coming to a halt
private int ticksSinceLastInventoryMove;
private int[] lastTickRequestedMove; // not everything asks every tick, so remember the request while coming to a halt

public InventoryBehavior(Baritone baritone) {
super(baritone);
}

@Override
public void onTick(TickEvent event) {
if (!Baritone.settings().allowInventory.value) {
if (event.getType() == TickEvent.Type.OUT) {
return;
}
if (event.getType() == TickEvent.Type.OUT) {
ticksSinceLastInventoryMove++;

// TODO: Move these checks into "requestSwapWithHotBar" or whatever supersedes it
if (!this.canAccessInventory()) {
return;
}
if (ctx.player().openContainer != ctx.player().inventoryContainer) {
// we have a crafting table or a chest or something open
return;
}
ticksSinceLastInventoryMove++;
if (firstValidThrowaway() >= 9) { // aka there are none on the hotbar, but there are some in main inventory
requestSwapWithHotBar(firstValidThrowaway(), 8);
}
int pick = bestToolAgainst(Blocks.STONE, ItemPickaxe.class);
if (pick >= 9) {
requestSwapWithHotBar(pick, 0);

if (Baritone.settings().allowHotbarManagement.value && baritone.getPathingBehavior().isPathing()) {
// TODO: Some way of indicating which slots are currently reserved by this setting
if (firstValidThrowaway() >= 9) { // aka there are none on the hotbar, but there are some in main inventory
requestSwapWithHotBar(firstValidThrowaway(), 8);
}
int pick = bestToolAgainst(Blocks.STONE, ItemPickaxe.class);
if (pick >= 9) {
requestSwapWithHotBar(pick, 0);
}
}

if (lastTickRequestedMove != null) {
logDebug("Remembering to move " + lastTickRequestedMove[0] + " " + lastTickRequestedMove[1] + " from a previous tick");
requestSwapWithHotBar(lastTickRequestedMove[0], lastTickRequestedMove[1]);
}
}

public boolean attemptToPutOnHotbar(int inMainInvy, Predicate<Integer> disallowedHotbar) {
public boolean attemptToPutOnHotbar(int inMainInvy, IntPredicate disallowedHotbar) {
OptionalInt destination = getTempHotbarSlot(disallowedHotbar);
if (destination.isPresent()) {
if (!requestSwapWithHotBar(inMainInvy, destination.getAsInt())) {
Expand All @@ -80,7 +88,7 @@ public boolean attemptToPutOnHotbar(int inMainInvy, Predicate<Integer> disallowe
return true;
}

public OptionalInt getTempHotbarSlot(Predicate<Integer> disallowedHotbar) {
public OptionalInt getTempHotbarSlot(IntPredicate disallowedHotbar) {
// we're using 0 and 8 for pickaxe and throwaway
ArrayList<Integer> candidates = new ArrayList<>();
for (int i = 1; i < 8; i++) {
Expand Down Expand Up @@ -120,7 +128,7 @@ private boolean requestSwapWithHotBar(int inInventory, int inHotbar) {
private int firstValidThrowaway() { // TODO offhand idk
NonNullList<ItemStack> invy = ctx.player().inventory.mainInventory;
for (int i = 0; i < invy.size(); i++) {
if (Baritone.settings().acceptableThrowawayItems.value.contains(invy.get(i).getItem())) {
if (this.isThrowawayItem(invy.get(i))) {
return i;
}
}
Expand Down Expand Up @@ -151,12 +159,7 @@ private int bestToolAgainst(Block against, Class<? extends ItemTool> cla$$) {
}

public boolean hasGenericThrowaway() {
for (Item item : Baritone.settings().acceptableThrowawayItems.value) {
if (throwaway(false, stack -> item.equals(stack.getItem()))) {
return true;
}
}
return false;
return this.canSelectItem(this::isThrowawayItem);
}

public boolean selectThrowawayForLocation(boolean select, int x, int y, int z) {
Expand All @@ -167,19 +170,18 @@ public boolean selectThrowawayForLocation(boolean select, int x, int y, int z) {
if (maybe != null && throwaway(select, stack -> stack.getItem() instanceof ItemBlock && ((ItemBlock) stack.getItem()).getBlock().equals(maybe.getBlock()))) {
return true;
}
for (Item item : Baritone.settings().acceptableThrowawayItems.value) {
if (throwaway(select, stack -> item.equals(stack.getItem()))) {
return true;
}
}
return false;
return throwaway(select, this::isThrowawayItem);
ZeroMemes marked this conversation as resolved.
Show resolved Hide resolved
}

public boolean throwaway(boolean select, Predicate<? super ItemStack> desired) {
return throwaway(select, desired, Baritone.settings().allowInventory.value);
public boolean canSelectItem(Predicate<? super ItemStack> desired) {
return this.throwaway(false, desired);
}

public boolean throwaway(boolean select, Predicate<? super ItemStack> desired, boolean allowInventory) {
public boolean trySelectItem(Predicate<? super ItemStack> desired) {
return this.throwaway(true, desired);
}

public boolean throwaway(boolean select, Predicate<? super ItemStack> desired) {
EntityPlayerSP p = ctx.player();
NonNullList<ItemStack> inv = p.inventory.mainInventory;
for (int i = 0; i < 9; i++) {
Expand All @@ -196,6 +198,7 @@ public boolean throwaway(boolean select, Predicate<? super ItemStack> desired, b
return true;
}
}

if (desired.test(p.inventory.offHandInventory.get(0))) {
// main hand takes precedence over off hand
// that means that if we have block A selected in main hand and block B in off hand, right clicking places block B
Expand All @@ -213,7 +216,7 @@ public boolean throwaway(boolean select, Predicate<? super ItemStack> desired, b
}
}

if (allowInventory) {
if (this.canAccessInventory()) {
for (int i = 9; i < 36; i++) {
if (desired.test(inv.get(i))) {
if (select) {
Expand All @@ -227,4 +230,16 @@ public boolean throwaway(boolean select, Predicate<? super ItemStack> desired, b

return false;
}

public boolean canAccessInventory() {
return Baritone.settings().allowInventory.value || Baritone.settings().allowHotbarManagement.value;
}

public boolean isThrowawayItem(ItemStack stack) {
return this.isThrowawayItem(stack.getItem());
}

public boolean isThrowawayItem(Item item) {
return Baritone.settings().acceptableThrowawayItems.value.contains(item);
}
}
2 changes: 1 addition & 1 deletion src/main/java/baritone/process/BuilderProcess.java
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,7 @@ public int lengthZ() {
return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL);
}

if (Baritone.settings().allowInventory.value) {
if (baritone.getInventoryBehavior().canAccessInventory()) {
ArrayList<Integer> usefulSlots = new ArrayList<>();
List<IBlockState> noValidHotbarOption = new ArrayList<>();
outer:
Expand Down
14 changes: 7 additions & 7 deletions src/main/java/baritone/process/FarmProcess.java
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) {
for (BlockPos pos : both) {
boolean soulsand = openSoulsand.contains(pos);
Optional<Rotation> rot = RotationUtils.reachableOffset(ctx, pos, new Vec3d(pos.getX() + 0.5, pos.getY() + 1, pos.getZ() + 0.5), ctx.playerController().getBlockReachDistance(), false);
if (rot.isPresent() && isSafeToCancel && baritone.getInventoryBehavior().throwaway(true, soulsand ? this::isNetherWart : this::isPlantable)) {
if (rot.isPresent() && isSafeToCancel && baritone.getInventoryBehavior().trySelectItem(soulsand ? this::isNetherWart : this::isPlantable)) {
RayTraceResult result = RayTraceUtils.rayTraceTowards(ctx.player(), rot.get(), ctx.playerController().getBlockReachDistance());
if (result.typeOfHit == RayTraceResult.Type.BLOCK && result.sideHit == EnumFacing.UP) {
baritone.getLookBehavior().updateTarget(rot.get(), true);
Expand All @@ -287,7 +287,7 @@ public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) {
}
Vec3d faceCenter = new Vec3d(pos).add(0.5, 0.5, 0.5).add(new Vec3d(dir.getDirectionVec()).scale(0.5));
Optional<Rotation> rot = RotationUtils.reachableOffset(ctx, pos, faceCenter, ctx.playerController().getBlockReachDistance(), false);
if (rot.isPresent() && isSafeToCancel && baritone.getInventoryBehavior().throwaway(true, this::isCocoa)) {
if (rot.isPresent() && isSafeToCancel && baritone.getInventoryBehavior().trySelectItem(this::isCocoa)) {
RayTraceResult result = RayTraceUtils.rayTraceTowards(ctx.player(), rot.get(), ctx.playerController().getBlockReachDistance());
if (result.typeOfHit == RayTraceResult.Type.BLOCK && result.sideHit == dir) {
baritone.getLookBehavior().updateTarget(rot.get(), true);
Expand All @@ -301,7 +301,7 @@ public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) {
}
for (BlockPos pos : bonemealable) {
Optional<Rotation> rot = RotationUtils.reachable(ctx, pos);
if (rot.isPresent() && isSafeToCancel && baritone.getInventoryBehavior().throwaway(true, this::isBoneMeal)) {
if (rot.isPresent() && isSafeToCancel && baritone.getInventoryBehavior().trySelectItem(this::isBoneMeal)) {
baritone.getLookBehavior().updateTarget(rot.get(), true);
if (ctx.isLookingAt(pos)) {
baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_RIGHT, true);
Expand All @@ -323,17 +323,17 @@ public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) {
for (BlockPos pos : toBreak) {
goalz.add(new BuilderProcess.GoalBreak(pos));
}
if (baritone.getInventoryBehavior().throwaway(false, this::isPlantable)) {
if (baritone.getInventoryBehavior().canSelectItem(this::isPlantable)) {
for (BlockPos pos : openFarmland) {
goalz.add(new GoalBlock(pos.up()));
}
}
if (baritone.getInventoryBehavior().throwaway(false, this::isNetherWart)) {
if (baritone.getInventoryBehavior().canSelectItem(this::isNetherWart)) {
for (BlockPos pos : openSoulsand) {
goalz.add(new GoalBlock(pos.up()));
}
}
if (baritone.getInventoryBehavior().throwaway(false, this::isCocoa)) {
if (baritone.getInventoryBehavior().canSelectItem(this::isCocoa)) {
for (BlockPos pos : openLog) {
for (EnumFacing direction : EnumFacing.Plane.HORIZONTAL) {
if (ctx.world().getBlockState(pos.offset(direction)).getBlock() instanceof BlockAir) {
Expand All @@ -342,7 +342,7 @@ public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) {
}
}
}
if (baritone.getInventoryBehavior().throwaway(false, this::isBoneMeal)) {
if (baritone.getInventoryBehavior().canSelectItem(this::isBoneMeal)) {
for (BlockPos pos : bonemealable) {
goalz.add(new GoalBlock(pos));
}
Expand Down
18 changes: 10 additions & 8 deletions src/main/java/baritone/utils/ToolSet.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@
package baritone.utils;

import baritone.Baritone;
import baritone.PerformanceCritical;
import baritone.utils.accessor.IItemTool;
import it.unimi.dsi.fastutil.objects.Reference2DoubleOpenHashMap;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.entity.EntityPlayerSP;
Expand All @@ -29,8 +31,6 @@
import net.minecraft.item.ItemSword;
import net.minecraft.item.ItemTool;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
Expand All @@ -44,7 +44,7 @@ public class ToolSet {
* A cache mapping a {@link Block} to how long it will take to break
* with this toolset, given the optimum tool is used.
*/
private final Map<Block, Double> breakStrengthCache;
private final Reference2DoubleOpenHashMap<Block> breakStrengthCache;

/**
* My buddy leijurv owned me so we have this to not create a new lambda instance.
Expand All @@ -54,15 +54,15 @@ public class ToolSet {
private final EntityPlayerSP player;

public ToolSet(EntityPlayerSP player) {
breakStrengthCache = new HashMap<>();
this.breakStrengthCache = new Reference2DoubleOpenHashMap<>();
this.player = player;

if (Baritone.settings().considerPotionEffects.value) {
double amplifier = potionAmplifier();
Function<Double, Double> amplify = x -> amplifier * x;
backendCalculation = amplify.compose(this::getBestDestructionTime);
this.backendCalculation = amplify.compose(this::getBestDestructionTime);
} else {
backendCalculation = this::getBestDestructionTime;
this.backendCalculation = this::getBestDestructionTime;
}
}

Expand All @@ -72,8 +72,11 @@ public ToolSet(EntityPlayerSP player) {
* @param state the blockstate to be mined
* @return the speed of how fast we'll mine it. 1/(time in ticks)
*/
@PerformanceCritical
public double getStrVsBlock(IBlockState state) {
return breakStrengthCache.computeIfAbsent(state.getBlock(), backendCalculation);
// fastutil 8+ has a computeIfAbsent overload that uses a primitive mapping function
// for now, we're stuck with the boxed implementation
return this.breakStrengthCache.computeIfAbsent(state.getBlock(), this.backendCalculation);
}

/**
Expand Down Expand Up @@ -104,7 +107,6 @@ public boolean hasSilkTouch(ItemStack stack) {
* @param b the blockstate to be mined
* @return An int containing the index in the tools array that worked best
*/

public int getBestSlot(Block b, boolean preferSilkTouch) {
return getBestSlot(b, preferSilkTouch, false);
}
Expand Down