Merge branch 'master' into bot-system

This commit is contained in:
Brady
2018-10-29 22:08:29 -05:00
30 changed files with 408 additions and 342 deletions
+3 -3
View File
@@ -3,13 +3,13 @@
[![Release](https://img.shields.io/github/release/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/releases) [![Release](https://img.shields.io/github/release/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/releases)
[![License](https://img.shields.io/github/license/cabaletta/baritone.svg)](LICENSE) [![License](https://img.shields.io/github/license/cabaletta/baritone.svg)](LICENSE)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/a73d037823b64a5faf597a18d71e3400)](https://www.codacy.com/app/leijurv/baritone?utm_source=github.com&utm_medium=referral&utm_content=cabaletta/baritone&utm_campaign=Badge_Grade) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/a73d037823b64a5faf597a18d71e3400)](https://www.codacy.com/app/leijurv/baritone?utm_source=github.com&utm_medium=referral&utm_content=cabaletta/baritone&utm_campaign=Badge_Grade)
[![HitCount](http://hits.dwyl.com/cabaletta/baritone.svg)](http://hits.dwyl.com/cabaletta/baritone)
<!-- Unofficial Jenkins: [![Build Status](https://plutiejenkins.leijurv.com/job/baritone/badge/icon)](https://plutiejenkins.leijurv.com/job/baritone/lastSuccessfulBuild/) --> [![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/cabaletta/baritone/issues)
A Minecraft pathfinder bot. This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/), A Minecraft pathfinder bot. This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/),
the original version of the bot for Minecraft 1.8, rebuilt for 1.12.2. Baritone focuses on reliability and particularly performance (it's over [29x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths). the original version of the bot for Minecraft 1.8, rebuilt for 1.12.2. Baritone focuses on reliability and particularly performance (it's over [29x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths).
Baritone is the pathfinding system used in [Impact](https://impactdevelopment.github.io/) since 4.4. Baritone is the pathfinding system used in [Impact](https://impactdevelopment.github.io/) since 4.4. There's a [showcase video](https://www.youtube.com/watch?v=yI8hgW_m6dQ) made by @Adovin#3153 on Baritone's integration into Impact. [Here's](https://www.youtube.com/watch?v=StquF69-_wI) a video I made showing off what it can do.
Here are some links to help to get started: Here are some links to help to get started:
@@ -34,9 +34,9 @@ import java.util.List;
*/ */
class BaritoneGradleTask extends DefaultTask { class BaritoneGradleTask extends DefaultTask {
static final JsonParser PARSER = new JsonParser(); protected static final JsonParser PARSER = new JsonParser();
static final String protected static final String
PROGUARD_ZIP = "proguard.zip", PROGUARD_ZIP = "proguard.zip",
PROGUARD_JAR = "proguard.jar", PROGUARD_JAR = "proguard.jar",
PROGUARD_CONFIG_TEMPLATE = "scripts/proguard.pro", PROGUARD_CONFIG_TEMPLATE = "scripts/proguard.pro",
@@ -54,10 +54,10 @@ class BaritoneGradleTask extends DefaultTask {
ARTIFACT_API = "%s-api-%s.jar", ARTIFACT_API = "%s-api-%s.jar",
ARTIFACT_STANDALONE = "%s-standalone-%s.jar"; ARTIFACT_STANDALONE = "%s-standalone-%s.jar";
String artifactName, artifactVersion; protected String artifactName, artifactVersion;
Path artifactPath, artifactUnoptimizedPath, artifactApiPath, artifactStandalonePath, proguardOut; protected Path artifactPath, artifactUnoptimizedPath, artifactApiPath, artifactStandalonePath, proguardOut;
void verifyArtifacts() throws Exception { protected void verifyArtifacts() throws IllegalStateException {
this.artifactName = getProject().getName(); this.artifactName = getProject().getName();
this.artifactVersion = getProject().getVersion().toString(); this.artifactVersion = getProject().getVersion().toString();
@@ -69,34 +69,34 @@ class BaritoneGradleTask extends DefaultTask {
this.proguardOut = this.getTemporaryFile(PROGUARD_EXPORT_PATH); this.proguardOut = this.getTemporaryFile(PROGUARD_EXPORT_PATH);
if (!Files.exists(this.artifactPath)) { if (!Files.exists(this.artifactPath)) {
throw new Exception("Artifact not found! Run build first!"); throw new IllegalStateException("Artifact not found! Run build first!");
} }
} }
void write(InputStream stream, Path file) throws Exception { protected void write(InputStream stream, Path file) throws Exception {
if (Files.exists(file)) { if (Files.exists(file)) {
Files.delete(file); Files.delete(file);
} }
Files.copy(stream, file); Files.copy(stream, file);
} }
String formatVersion(String string) { protected String formatVersion(String string) {
return String.format(string, this.artifactName, this.artifactVersion); return String.format(string, this.artifactName, this.artifactVersion);
} }
Path getRelativeFile(String file) { protected Path getRelativeFile(String file) {
return Paths.get(new File(file).getAbsolutePath()); return Paths.get(new File(file).getAbsolutePath());
} }
Path getTemporaryFile(String file) { protected Path getTemporaryFile(String file) {
return Paths.get(new File(getTemporaryDir(), file).getAbsolutePath()); return Paths.get(new File(getTemporaryDir(), file).getAbsolutePath());
} }
Path getBuildFile(String file) { protected Path getBuildFile(String file) {
return getRelativeFile("build/libs/" + file); return getRelativeFile("build/libs/" + file);
} }
JsonElement readJson(List<String> lines) { protected JsonElement readJson(List<String> lines) {
return PARSER.parse(String.join("\n", lines)); return PARSER.parse(String.join("\n", lines));
} }
} }
@@ -76,7 +76,7 @@ public class CreateDistTask extends BaritoneGradleTask {
return DatatypeConverter.printHexBinary(SHA1_DIGEST.digest(Files.readAllBytes(path))).toLowerCase(); return DatatypeConverter.printHexBinary(SHA1_DIGEST.digest(Files.readAllBytes(path))).toLowerCase();
} catch (Exception e) { } catch (Exception e) {
// haha no thanks // haha no thanks
throw new RuntimeException(e); throw new IllegalStateException(e);
} }
} }
} }
@@ -241,7 +241,7 @@ public class ProguardTask extends BaritoneGradleTask {
// Halt the current thread until the process is complete, if the exit code isn't 0, throw an exception // Halt the current thread until the process is complete, if the exit code isn't 0, throw an exception
int exitCode = p.waitFor(); int exitCode = p.waitFor();
if (exitCode != 0) { if (exitCode != 0) {
throw new Exception("Proguard exited with code " + exitCode); throw new IllegalStateException("Proguard exited with code " + exitCode);
} }
} }
+13 -1
View File
@@ -24,8 +24,8 @@ import net.minecraft.util.text.ITextComponent;
import java.awt.*; import java.awt.*;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.*;
import java.util.List; import java.util.List;
import java.util.*;
import java.util.function.Consumer; import java.util.function.Consumer;
/** /**
@@ -396,6 +396,18 @@ public class Settings {
*/ */
public Setting<Integer> axisHeight = new Setting<>(120); public Setting<Integer> axisHeight = new Setting<>(120);
/**
* Allow MineBehavior to use X-Ray to see where the ores are. Turn this option off to force it to mine "legit"
* where it will only mine an ore once it can actually see it, so it won't do or know anything that a normal player
* couldn't. If you don't want it to look like you're X-Raying, turn this off
*/
public Setting<Boolean> legitMine = new Setting<>(false);
/**
* What Y level to go to for legit strip mining
*/
public Setting<Integer> legitMineYLevel = new Setting<>(11);
/** /**
* When mining block of a certain type, try to mine two at once instead of one. * When mining block of a certain type, try to mine two at once instead of one.
* If the block above is also a goal block, set GoalBlock instead of GoalTwoBlocks * If the block above is also a goal block, set GoalBlock instead of GoalTwoBlocks
@@ -220,10 +220,8 @@ public final class RotationUtils {
if (result.getBlockPos().equals(pos)) { if (result.getBlockPos().equals(pos)) {
return Optional.of(rotation); return Optional.of(rotation);
} }
if (entity.world.getBlockState(pos).getBlock() instanceof BlockFire) { if (entity.world.getBlockState(pos).getBlock() instanceof BlockFire && result.getBlockPos().equals(pos.down())) {
if (result.getBlockPos().equals(pos.down())) { return Optional.of(rotation);
return Optional.of(rotation);
}
} }
} }
return Optional.empty(); return Optional.empty();
@@ -21,10 +21,13 @@ import baritone.Baritone;
import baritone.api.event.events.ChatEvent; import baritone.api.event.events.ChatEvent;
import baritone.api.event.events.PlayerUpdateEvent; import baritone.api.event.events.PlayerUpdateEvent;
import baritone.api.event.events.type.EventState; import baritone.api.event.events.type.EventState;
import baritone.behavior.PathingBehavior;
import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.entity.player.PlayerCapabilities;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
/** /**
@@ -72,4 +75,16 @@ public class MixinEntityPlayerSP {
private void onPostUpdate(CallbackInfo ci) { private void onPostUpdate(CallbackInfo ci) {
Baritone.INSTANCE.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent((EntityPlayerSP) (Object) this, EventState.POST)); Baritone.INSTANCE.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent((EntityPlayerSP) (Object) this, EventState.POST));
} }
@Redirect(
method = "onLivingUpdate",
at = @At(
value = "FIELD",
target = "net/minecraft/entity/player/PlayerCapabilities.allowFlying:Z"
)
)
private boolean isAllowFlying(PlayerCapabilities capabilities) {
PathingBehavior pathingBehavior = Baritone.INSTANCE.getPathingBehavior();
return (!pathingBehavior.isEnabled() || !pathingBehavior.isPathing()) && capabilities.allowFlying;
}
} }
@@ -22,9 +22,7 @@ import baritone.api.event.events.BlockInteractEvent;
import baritone.api.event.events.TickEvent; import baritone.api.event.events.TickEvent;
import baritone.api.event.events.WorldEvent; import baritone.api.event.events.WorldEvent;
import baritone.api.event.events.type.EventState; import baritone.api.event.events.type.EventState;
import baritone.behavior.PathingBehavior;
import baritone.utils.BaritoneAutoTest; import baritone.utils.BaritoneAutoTest;
import baritone.utils.ExampleBaritoneControl;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiScreen;
@@ -60,7 +58,6 @@ public class MixinMinecraft {
) )
private void postInit(CallbackInfo ci) { private void postInit(CallbackInfo ci) {
Baritone.INSTANCE.init(); Baritone.INSTANCE.init();
ExampleBaritoneControl.INSTANCE.initAndRegister();
} }
@Inject( @Inject(
@@ -145,7 +142,7 @@ public class MixinMinecraft {
) )
) )
private boolean isAllowUserInput(GuiScreen screen) { private boolean isAllowUserInput(GuiScreen screen) {
return (PathingBehavior.INSTANCE.getCurrent() != null && PathingBehavior.INSTANCE.isEnabled() && player != null) || screen.allowUserInput; return (Baritone.INSTANCE.getPathingBehavior().getCurrent() != null && Baritone.INSTANCE.getPathingBehavior().isEnabled() && player != null) || screen.allowUserInput;
} }
@Inject( @Inject(
+55 -8
View File
@@ -18,11 +18,15 @@
package baritone; package baritone;
import baritone.api.BaritoneAPI; import baritone.api.BaritoneAPI;
import baritone.api.IBaritoneProvider;
import baritone.api.Settings; import baritone.api.Settings;
import baritone.api.event.listener.IGameEventListener; import baritone.api.event.listener.IGameEventListener;
import baritone.behavior.*; import baritone.behavior.*;
import baritone.cache.WorldProvider;
import baritone.cache.WorldScanner;
import baritone.event.GameEventHandler; import baritone.event.GameEventHandler;
import baritone.utils.BaritoneAutoTest; import baritone.utils.BaritoneAutoTest;
import baritone.utils.ExampleBaritoneControl;
import baritone.utils.InputOverrideHandler; import baritone.utils.InputOverrideHandler;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
@@ -40,7 +44,7 @@ import java.util.concurrent.TimeUnit;
* @author Brady * @author Brady
* @since 7/31/2018 10:50 PM * @since 7/31/2018 10:50 PM
*/ */
public enum Baritone { public enum Baritone implements IBaritoneProvider {
/** /**
* Singleton instance of this class * Singleton instance of this class
@@ -55,10 +59,16 @@ public enum Baritone {
private GameEventHandler gameEventHandler; private GameEventHandler gameEventHandler;
private InputOverrideHandler inputOverrideHandler; private InputOverrideHandler inputOverrideHandler;
private Settings settings; private Settings settings;
private List<Behavior> behaviors;
private File dir; private File dir;
private ThreadPoolExecutor threadPool; private ThreadPoolExecutor threadPool;
private List<Behavior> behaviors;
private PathingBehavior pathingBehavior;
private LookBehavior lookBehavior;
private MemoryBehavior memoryBehavior;
private FollowBehavior followBehavior;
private MineBehavior mineBehavior;
/** /**
* Whether or not Baritone is active * Whether or not Baritone is active
*/ */
@@ -81,12 +91,13 @@ public enum Baritone {
this.behaviors = new ArrayList<>(); this.behaviors = new ArrayList<>();
{ {
registerBehavior(PathingBehavior.INSTANCE); // the Behavior constructor calls baritone.registerBehavior(this) so this populates the behaviors arraylist
registerBehavior(LookBehavior.INSTANCE); pathingBehavior = new PathingBehavior(this);
registerBehavior(MemoryBehavior.INSTANCE); lookBehavior = new LookBehavior(this);
registerBehavior(LocationTrackingBehavior.INSTANCE); memoryBehavior = new MemoryBehavior(this);
registerBehavior(FollowBehavior.INSTANCE); followBehavior = new FollowBehavior(this);
registerBehavior(MineBehavior.INSTANCE); mineBehavior = new MineBehavior(this);
new ExampleBaritoneControl(this);
} }
if (BaritoneAutoTest.ENABLE_AUTO_TEST) { if (BaritoneAutoTest.ENABLE_AUTO_TEST) {
registerEventListener(BaritoneAutoTest.INSTANCE); registerEventListener(BaritoneAutoTest.INSTANCE);
@@ -127,6 +138,42 @@ public enum Baritone {
this.registerEventListener(behavior); this.registerEventListener(behavior);
} }
@Override
public FollowBehavior getFollowBehavior() {
return followBehavior;
}
@Override
public LookBehavior getLookBehavior() {
return lookBehavior;
}
@Override
public MemoryBehavior getMemoryBehavior() {
return memoryBehavior;
}
@Override
public MineBehavior getMineBehavior() {
return mineBehavior;
}
@Override
public PathingBehavior getPathingBehavior() {
return pathingBehavior;
}
@Override
public WorldProvider getWorldProvider() {
return WorldProvider.INSTANCE;
}
@Override
public WorldScanner getWorldScanner() {
return WorldScanner.INSTANCE;
}
@Override
public void registerEventListener(IGameEventListener listener) { public void registerEventListener(IGameEventListener listener) {
this.gameEventHandler.registerEventListener(listener); this.gameEventHandler.registerEventListener(listener);
} }
+7 -6
View File
@@ -22,11 +22,12 @@ import baritone.api.behavior.*;
import baritone.api.cache.IWorldProvider; import baritone.api.cache.IWorldProvider;
import baritone.api.cache.IWorldScanner; import baritone.api.cache.IWorldScanner;
import baritone.api.event.listener.IGameEventListener; import baritone.api.event.listener.IGameEventListener;
import baritone.behavior.*;
import baritone.cache.WorldProvider; import baritone.cache.WorldProvider;
import baritone.cache.WorldScanner; import baritone.cache.WorldScanner;
/** /**
* todo fix this cancer
*
* @author Brady * @author Brady
* @since 9/29/2018 * @since 9/29/2018
*/ */
@@ -34,27 +35,27 @@ public final class BaritoneProvider implements IBaritoneProvider {
@Override @Override
public IFollowBehavior getFollowBehavior() { public IFollowBehavior getFollowBehavior() {
return FollowBehavior.INSTANCE; return Baritone.INSTANCE.getFollowBehavior();
} }
@Override @Override
public ILookBehavior getLookBehavior() { public ILookBehavior getLookBehavior() {
return LookBehavior.INSTANCE; return Baritone.INSTANCE.getLookBehavior();
} }
@Override @Override
public IMemoryBehavior getMemoryBehavior() { public IMemoryBehavior getMemoryBehavior() {
return MemoryBehavior.INSTANCE; return Baritone.INSTANCE.getMemoryBehavior();
} }
@Override @Override
public IMineBehavior getMineBehavior() { public IMineBehavior getMineBehavior() {
return MineBehavior.INSTANCE; return Baritone.INSTANCE.getMineBehavior();
} }
@Override @Override
public IPathingBehavior getPathingBehavior() { public IPathingBehavior getPathingBehavior() {
return PathingBehavior.INSTANCE; return Baritone.INSTANCE.getPathingBehavior();
} }
@Override @Override
@@ -17,6 +17,7 @@
package baritone.behavior; package baritone.behavior;
import baritone.Baritone;
import baritone.api.behavior.IBehavior; import baritone.api.behavior.IBehavior;
/** /**
@@ -27,11 +28,18 @@ import baritone.api.behavior.IBehavior;
*/ */
public class Behavior implements IBehavior { public class Behavior implements IBehavior {
public final Baritone baritone;
/** /**
* Whether or not this behavior is enabled * Whether or not this behavior is enabled
*/ */
private boolean enabled = true; private boolean enabled = true;
protected Behavior(Baritone baritone) {
this.baritone = baritone;
baritone.registerBehavior(this);
}
/** /**
* Toggles the enabled state of this {@link Behavior}. * Toggles the enabled state of this {@link Behavior}.
* *
@@ -33,11 +33,11 @@ import net.minecraft.util.math.BlockPos;
*/ */
public final class FollowBehavior extends Behavior implements IFollowBehavior, Helper { public final class FollowBehavior extends Behavior implements IFollowBehavior, Helper {
public static final FollowBehavior INSTANCE = new FollowBehavior();
private Entity following; private Entity following;
private FollowBehavior() {} public FollowBehavior(Baritone baritone) {
super(baritone);
}
@Override @Override
public void onTick(TickEvent event) { public void onTick(TickEvent event) {
@@ -56,9 +56,9 @@ public final class FollowBehavior extends Behavior implements IFollowBehavior, H
GoalXZ g = GoalXZ.fromDirection(following.getPositionVector(), Baritone.settings().followOffsetDirection.get(), Baritone.settings().followOffsetDistance.get()); GoalXZ g = GoalXZ.fromDirection(following.getPositionVector(), Baritone.settings().followOffsetDirection.get(), Baritone.settings().followOffsetDistance.get());
pos = new BlockPos(g.getX(), following.posY, g.getZ()); pos = new BlockPos(g.getX(), following.posY, g.getZ());
} }
PathingBehavior.INSTANCE.setGoal(new GoalNear(pos, Baritone.settings().followRadius.get())); baritone.getPathingBehavior().setGoal(new GoalNear(pos, Baritone.settings().followRadius.get()));
PathingBehavior.INSTANCE.revalidateGoal(); ((PathingBehavior) baritone.getPathingBehavior()).revalidateGoal();
PathingBehavior.INSTANCE.path(); baritone.getPathingBehavior().path();
} }
@Override @Override
@@ -73,7 +73,7 @@ public final class FollowBehavior extends Behavior implements IFollowBehavior, H
@Override @Override
public void cancel() { public void cancel() {
PathingBehavior.INSTANCE.cancel(); baritone.getPathingBehavior().cancel();
follow(null); follow(null);
} }
} }
@@ -1,53 +0,0 @@
/*
* 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.behavior;
import baritone.api.event.events.BlockInteractEvent;
import baritone.cache.Waypoint;
import baritone.cache.WorldProvider;
import baritone.utils.BlockStateInterface;
import baritone.utils.Helper;
import net.minecraft.block.BlockBed;
/**
* A collection of event methods that are used to interact with Baritone's
* waypoint system. This class probably needs a better name.
*
* @see Waypoint
*
* @author Brady
* @since 8/22/2018
*/
public final class LocationTrackingBehavior extends Behavior implements Helper {
public static final LocationTrackingBehavior INSTANCE = new LocationTrackingBehavior();
private LocationTrackingBehavior() {}
@Override
public void onBlockInteract(BlockInteractEvent event) {
if (event.getType() == BlockInteractEvent.Type.USE && BlockStateInterface.getBlock(event.getPos()) instanceof BlockBed) {
WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("bed", Waypoint.Tag.BED, event.getPos()));
}
}
@Override
public void onPlayerDeath() {
WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("death", Waypoint.Tag.DEATH, playerFeet()));
}
}
@@ -26,9 +26,6 @@ import baritone.api.utils.Rotation;
import baritone.utils.Helper; import baritone.utils.Helper;
public final class LookBehavior extends Behavior implements ILookBehavior, Helper { public final class LookBehavior extends Behavior implements ILookBehavior, Helper {
public static final LookBehavior INSTANCE = new LookBehavior();
/** /**
* Target's values are as follows: * Target's values are as follows:
* <p> * <p>
@@ -49,7 +46,9 @@ public final class LookBehavior extends Behavior implements ILookBehavior, Helpe
*/ */
private float lastYaw; private float lastYaw;
private LookBehavior() {} public LookBehavior(Baritone baritone) {
super(baritone);
}
@Override @Override
public void updateTarget(Rotation target, boolean force) { public void updateTarget(Rotation target, boolean force) {
@@ -17,14 +17,19 @@
package baritone.behavior; package baritone.behavior;
import baritone.Baritone;
import baritone.api.behavior.IMemoryBehavior; import baritone.api.behavior.IMemoryBehavior;
import baritone.api.behavior.memory.IRememberedInventory; import baritone.api.behavior.memory.IRememberedInventory;
import baritone.api.cache.IWorldData; import baritone.api.cache.IWorldData;
import baritone.api.event.events.BlockInteractEvent;
import baritone.api.event.events.PacketEvent; import baritone.api.event.events.PacketEvent;
import baritone.api.event.events.PlayerUpdateEvent; import baritone.api.event.events.PlayerUpdateEvent;
import baritone.api.event.events.type.EventState; import baritone.api.event.events.type.EventState;
import baritone.cache.Waypoint;
import baritone.cache.WorldProvider; import baritone.cache.WorldProvider;
import baritone.utils.BlockStateInterface;
import baritone.utils.Helper; import baritone.utils.Helper;
import net.minecraft.block.BlockBed;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.network.Packet; import net.minecraft.network.Packet;
import net.minecraft.network.play.client.CPacketCloseWindow; import net.minecraft.network.play.client.CPacketCloseWindow;
@@ -43,11 +48,11 @@ import java.util.*;
*/ */
public final class MemoryBehavior extends Behavior implements IMemoryBehavior, Helper { public final class MemoryBehavior extends Behavior implements IMemoryBehavior, Helper {
public static MemoryBehavior INSTANCE = new MemoryBehavior();
private final Map<IWorldData, WorldDataContainer> worldDataContainers = new HashMap<>(); private final Map<IWorldData, WorldDataContainer> worldDataContainers = new HashMap<>();
private MemoryBehavior() {} public MemoryBehavior(Baritone baritone) {
super(baritone);
}
@Override @Override
public synchronized void onPlayerUpdate(PlayerUpdateEvent event) { public synchronized void onPlayerUpdate(PlayerUpdateEvent event) {
@@ -114,6 +119,18 @@ public final class MemoryBehavior extends Behavior implements IMemoryBehavior, H
} }
} }
@Override
public void onBlockInteract(BlockInteractEvent event) {
if (event.getType() == BlockInteractEvent.Type.USE && BlockStateInterface.getBlock(event.getPos()) instanceof BlockBed) {
WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("bed", Waypoint.Tag.BED, event.getPos()));
}
}
@Override
public void onPlayerDeath() {
WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("death", Waypoint.Tag.DEATH, playerFeet()));
}
private Optional<RememberedInventory> getInventoryFromWindow(int windowId) { private Optional<RememberedInventory> getInventoryFromWindow(int windowId) {
return this.getCurrentContainer().rememberedInventories.values().stream().filter(i -> i.windowId == windowId).findFirst(); return this.getCurrentContainer().rememberedInventories.values().stream().filter(i -> i.windowId == windowId).findFirst();
} }
@@ -20,14 +20,13 @@ package baritone.behavior;
import baritone.Baritone; import baritone.Baritone;
import baritone.api.behavior.IMineBehavior; import baritone.api.behavior.IMineBehavior;
import baritone.api.event.events.TickEvent; import baritone.api.event.events.TickEvent;
import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.*;
import baritone.api.pathing.goals.GoalBlock; import baritone.api.utils.RotationUtils;
import baritone.api.pathing.goals.GoalComposite;
import baritone.api.pathing.goals.GoalTwoBlocks;
import baritone.cache.CachedChunk; import baritone.cache.CachedChunk;
import baritone.cache.ChunkPacker; import baritone.cache.ChunkPacker;
import baritone.cache.WorldProvider; import baritone.cache.WorldProvider;
import baritone.cache.WorldScanner; import baritone.cache.WorldScanner;
import baritone.pathing.movement.MovementHelper;
import baritone.utils.BlockStateInterface; import baritone.utils.BlockStateInterface;
import baritone.utils.Helper; import baritone.utils.Helper;
import net.minecraft.block.Block; import net.minecraft.block.Block;
@@ -47,13 +46,14 @@ import java.util.stream.Collectors;
*/ */
public final class MineBehavior extends Behavior implements IMineBehavior, Helper { public final class MineBehavior extends Behavior implements IMineBehavior, Helper {
public static final MineBehavior INSTANCE = new MineBehavior();
private List<Block> mining; private List<Block> mining;
private List<BlockPos> locationsCache; private List<BlockPos> knownOreLocations;
private int quantity; private BlockPos branchPoint;
private int desiredQuantity;
private MineBehavior() {} public MineBehavior(Baritone baritone) {
super(baritone);
}
@Override @Override
public void onTick(TickEvent event) { public void onTick(TickEvent event) {
@@ -64,53 +64,79 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe
if (mining == null) { if (mining == null) {
return; return;
} }
if (quantity > 0) { if (desiredQuantity > 0) {
Item item = mining.get(0).getItemDropped(mining.get(0).getDefaultState(), new Random(), 0); Item item = mining.get(0).getItemDropped(mining.get(0).getDefaultState(), new Random(), 0);
int curr = player().inventory.mainInventory.stream().filter(stack -> item.equals(stack.getItem())).mapToInt(ItemStack::getCount).sum(); int curr = player().inventory.mainInventory.stream().filter(stack -> item.equals(stack.getItem())).mapToInt(ItemStack::getCount).sum();
System.out.println("Currently have " + curr + " " + item); System.out.println("Currently have " + curr + " " + item);
if (curr >= quantity) { if (curr >= desiredQuantity) {
logDirect("Have " + curr + " " + item.getItemStackDisplayName(new ItemStack(item, 1))); logDirect("Have " + curr + " " + item.getItemStackDisplayName(new ItemStack(item, 1)));
cancel(); cancel();
return; return;
} }
} }
int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.get(); int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.get();
if (mineGoalUpdateInterval != 0) { if (mineGoalUpdateInterval != 0 && event.getCount() % mineGoalUpdateInterval == 0) {
if (event.getCount() % mineGoalUpdateInterval == 0) { Baritone.INSTANCE.getExecutor().execute(this::rescan);
Baritone.INSTANCE.getExecutor().execute(this::rescan); }
} if (Baritone.settings().legitMine.get()) {
addNearby();
} }
updateGoal(); updateGoal();
PathingBehavior.INSTANCE.revalidateGoal(); baritone.getPathingBehavior().revalidateGoal();
} }
private void updateGoal() { private void updateGoal() {
if (mining == null) { if (mining == null) {
return; return;
} }
List<BlockPos> locs = locationsCache; List<BlockPos> locs = knownOreLocations;
if (!locs.isEmpty()) { if (!locs.isEmpty()) {
locs = prune(new ArrayList<>(locs), mining, 64); List<BlockPos> locs2 = prune(new ArrayList<>(locs), mining, 64);
PathingBehavior.INSTANCE.setGoal(coalesce(locs)); // can't reassign locs, gotta make a new var locs2, because we use it in a lambda right here, and variables you use in a lambda must be effectively final
PathingBehavior.INSTANCE.path(); baritone.getPathingBehavior().setGoalAndPath(new GoalComposite(locs2.stream().map(loc -> coalesce(loc, locs2)).toArray(Goal[]::new)));
locationsCache = locs; knownOreLocations = locs;
return;
} }
// we don't know any ore locations at the moment
if (!Baritone.settings().legitMine.get()) {
return;
}
// only in non-Xray mode (aka legit mode) do we do this
if (branchPoint == null) {
int y = Baritone.settings().legitMineYLevel.get();
if (!baritone.getPathingBehavior().isPathing() && playerFeet().y == y) {
// cool, path is over and we are at desired y
branchPoint = playerFeet();
} else {
baritone.getPathingBehavior().setGoalAndPath(new GoalYLevel(y));
return;
}
}
if (playerFeet().equals(branchPoint)) {
// TODO mine 1x1 shafts to either side
branchPoint = branchPoint.north(10);
}
baritone.getPathingBehavior().setGoalAndPath(new GoalBlock(branchPoint));
} }
private void rescan() { private void rescan() {
if (mining == null) { if (mining == null) {
return; return;
} }
List<BlockPos> locs = scanFor(mining, 64); if (Baritone.settings().legitMine.get()) {
return;
}
List<BlockPos> locs = searchWorld(mining, 64);
if (locs.isEmpty()) { if (locs.isEmpty()) {
logDebug("No locations for " + mining + " known, cancelling"); logDebug("No locations for " + mining + " known, cancelling");
mine(0, (String[]) null); mine(0, (String[]) null);
return; return;
} }
locationsCache = locs; knownOreLocations = locs;
} }
public Goal coalesce(BlockPos loc, List<BlockPos> locs) { private static Goal coalesce(BlockPos loc, List<BlockPos> locs) {
if (!Baritone.settings().forceInternalMining.get()) { if (!Baritone.settings().forceInternalMining.get()) {
return new GoalTwoBlocks(loc); return new GoalTwoBlocks(loc);
} }
@@ -132,11 +158,7 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe
} }
} }
public GoalComposite coalesce(List<BlockPos> locs) { public List<BlockPos> searchWorld(List<Block> mining, int max) {
return new GoalComposite(locs.stream().map(loc -> coalesce(loc, locs)).toArray(Goal[]::new));
}
public List<BlockPos> scanFor(List<Block> mining, int max) {
List<BlockPos> locs = new ArrayList<>(); List<BlockPos> locs = new ArrayList<>();
List<Block> uninteresting = new ArrayList<>(); List<Block> uninteresting = new ArrayList<>();
//long b = System.currentTimeMillis(); //long b = System.currentTimeMillis();
@@ -159,26 +181,55 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe
return prune(locs, mining, max); return prune(locs, mining, max);
} }
public List<BlockPos> prune(List<BlockPos> locs, List<Block> mining, int max) { public void addNearby() {
BlockPos playerFeet = MineBehavior.INSTANCE.playerFeet(); BlockPos playerFeet = playerFeet();
locs.sort(Comparator.comparingDouble(playerFeet::distanceSq)); int searchDist = 4;//why four? idk
for (int x = playerFeet.getX() - searchDist; x <= playerFeet.getX() + searchDist; x++) {
for (int y = playerFeet.getY() - searchDist; y <= playerFeet.getY() + searchDist; y++) {
for (int z = playerFeet.getZ() - searchDist; z <= playerFeet.getZ() + searchDist; z++) {
BlockPos pos = new BlockPos(x, y, z);
if (mining.contains(BlockStateInterface.getBlock(pos)) && RotationUtils.reachable(player(), pos).isPresent()) {//crucial to only add blocks we can see because otherwise this is an x-ray and it'll get caught
knownOreLocations.add(pos);
}
}
}
}
knownOreLocations = prune(knownOreLocations, mining, 64);
}
public List<BlockPos> prune(List<BlockPos> locs2, List<Block> mining, int max) {
List<BlockPos> locs = locs2
.stream()
// remove any that are within loaded chunks that aren't actually what we want
.filter(pos -> world().getChunk(pos) instanceof EmptyChunk || mining.contains(BlockStateInterface.get(pos).getBlock()))
// remove any that are implausible to mine (encased in bedrock, or touching lava)
.filter(MineBehavior::plausibleToBreak)
.sorted(Comparator.comparingDouble(Helper.HELPER.playerFeet()::distanceSq))
.collect(Collectors.toList());
// remove any that are within loaded chunks that aren't actually what we want
locs.removeAll(locs.stream()
.filter(pos -> !(MineBehavior.INSTANCE.world().getChunk(pos) instanceof EmptyChunk))
.filter(pos -> !mining.contains(BlockStateInterface.get(pos).getBlock()))
.collect(Collectors.toList()));
if (locs.size() > max) { if (locs.size() > max) {
return locs.subList(0, max); return locs.subList(0, max);
} }
return locs; return locs;
} }
public static boolean plausibleToBreak(BlockPos pos) {
if (MovementHelper.avoidBreaking(pos.getX(), pos.getY(), pos.getZ(), BlockStateInterface.get(pos))) {
return false;
}
// bedrock above and below makes it implausible, otherwise we're good
return !(BlockStateInterface.getBlock(pos.up()) == Blocks.BEDROCK && BlockStateInterface.getBlock(pos.down()) == Blocks.BEDROCK);
}
@Override @Override
public void mine(int quantity, String... blocks) { public void mine(int quantity, String... blocks) {
this.mining = blocks == null || blocks.length == 0 ? null : Arrays.stream(blocks).map(ChunkPacker::stringToBlock).collect(Collectors.toList()); this.mining = blocks == null || blocks.length == 0 ? null : Arrays.stream(blocks).map(ChunkPacker::stringToBlock).collect(Collectors.toList());
this.quantity = quantity; this.desiredQuantity = quantity;
this.locationsCache = new ArrayList<>(); this.knownOreLocations = new ArrayList<>();
this.branchPoint = null;
rescan(); rescan();
updateGoal(); updateGoal();
} }
@@ -186,8 +237,9 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe
@Override @Override
public void mine(int quantity, Block... blocks) { public void mine(int quantity, Block... blocks) {
this.mining = blocks == null || blocks.length == 0 ? null : Arrays.asList(blocks); this.mining = blocks == null || blocks.length == 0 ? null : Arrays.asList(blocks);
this.quantity = quantity; this.desiredQuantity = quantity;
this.locationsCache = new ArrayList<>(); this.knownOreLocations = new ArrayList<>();
this.branchPoint = null;
rescan(); rescan();
updateGoal(); updateGoal();
} }
@@ -195,6 +247,6 @@ public final class MineBehavior extends Behavior implements IMineBehavior, Helpe
@Override @Override
public void cancel() { public void cancel() {
mine(0, (String[]) null); mine(0, (String[]) null);
PathingBehavior.INSTANCE.cancel(); baritone.getPathingBehavior().cancel();
} }
} }
@@ -32,6 +32,7 @@ import baritone.api.utils.interfaces.IGoalRenderPos;
import baritone.pathing.calc.AStarPathFinder; import baritone.pathing.calc.AStarPathFinder;
import baritone.pathing.calc.AbstractNodeCostSearch; import baritone.pathing.calc.AbstractNodeCostSearch;
import baritone.pathing.calc.CutoffPath; import baritone.pathing.calc.CutoffPath;
import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementHelper;
import baritone.pathing.path.PathExecutor; import baritone.pathing.path.PathExecutor;
import baritone.utils.BlockBreakHelper; import baritone.utils.BlockBreakHelper;
@@ -46,8 +47,6 @@ import java.util.stream.Collectors;
public final class PathingBehavior extends Behavior implements IPathingBehavior, Helper { public final class PathingBehavior extends Behavior implements IPathingBehavior, Helper {
public static final PathingBehavior INSTANCE = new PathingBehavior();
private PathExecutor current; private PathExecutor current;
private PathExecutor next; private PathExecutor next;
@@ -62,7 +61,9 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
private final LinkedBlockingQueue<PathEvent> toDispatch = new LinkedBlockingQueue<>(); private final LinkedBlockingQueue<PathEvent> toDispatch = new LinkedBlockingQueue<>();
private PathingBehavior() {} public PathingBehavior(Baritone baritone) {
super(baritone);
}
private void queuePathEvent(PathEvent event) { private void queuePathEvent(PathEvent event) {
toDispatch.add(event); toDispatch.add(event);
@@ -83,7 +84,6 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
cancel(); cancel();
return; return;
} }
mc.playerController.setPlayerCapabilities(mc.player);
tickPath(); tickPath();
dispatchEvents(); dispatchEvents();
} }
@@ -134,19 +134,14 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
return; return;
} }
// at this point, we know current is in progress // at this point, we know current is in progress
if (safe) { if (safe && next != null && next.snipsnapifpossible()) {
// a movement just ended // a movement just ended; jump directly onto the next path
if (next != null) { logDebug("Splicing into planned next path early...");
if (next.snipsnapifpossible()) { queuePathEvent(PathEvent.SPLICING_ONTO_NEXT_EARLY);
// jump directly onto the next path current = next;
logDebug("Splicing into planned next path early..."); next = null;
queuePathEvent(PathEvent.SPLICING_ONTO_NEXT_EARLY); current.onTick();
current = next; return;
next = null;
current.onTick();
return;
}
}
} }
synchronized (pathCalcLock) { synchronized (pathCalcLock) {
if (isPathCalcInProgress) { if (isPathCalcInProgress) {
@@ -201,6 +196,11 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
this.goal = goal; this.goal = goal;
} }
public boolean setGoalAndPath(Goal goal) {
setGoal(goal);
return path();
}
@Override @Override
public Goal getGoal() { public Goal getGoal() {
return goal; return goal;
@@ -326,12 +326,13 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
} }
isPathCalcInProgress = true; isPathCalcInProgress = true;
} }
CalculationContext context = new CalculationContext(); // not safe to create on the other thread, it looks up a lot of stuff in minecraft
Baritone.INSTANCE.getExecutor().execute(() -> { Baritone.INSTANCE.getExecutor().execute(() -> {
if (talkAboutIt) { if (talkAboutIt) {
logDebug("Starting to search for path from " + start + " to " + goal); logDebug("Starting to search for path from " + start + " to " + goal);
} }
Optional<IPath> path = findPath(start, previous); Optional<IPath> path = findPath(start, previous, context);
if (Baritone.settings().cutoffAtLoadBoundary.get()) { if (Baritone.settings().cutoffAtLoadBoundary.get()) {
path = path.map(p -> { path = path.map(p -> {
IPath result = p.cutoffAtLoadedChunks(); IPath result = p.cutoffAtLoadedChunks();
@@ -399,7 +400,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
* @param start * @param start
* @return * @return
*/ */
private Optional<IPath> findPath(BlockPos start, Optional<IPath> previous) { private Optional<IPath> findPath(BlockPos start, Optional<IPath> previous, CalculationContext context) {
Goal goal = this.goal; Goal goal = this.goal;
if (goal == null) { if (goal == null) {
logDebug("no goal"); logDebug("no goal");
@@ -429,7 +430,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
favoredPositions = previous.map(IPath::positions).map(Collection::stream).map(x -> x.map(BetterBlockPos::longHash)).map(x -> x.collect(Collectors.toList())).map(HashSet::new); // <-- okay this is EPIC favoredPositions = previous.map(IPath::positions).map(Collection::stream).map(x -> x.map(BetterBlockPos::longHash)).map(x -> x.collect(Collectors.toList())).map(HashSet::new); // <-- okay this is EPIC
} }
try { try {
IPathFinder pf = new AStarPathFinder(start.getX(), start.getY(), start.getZ(), goal, favoredPositions); IPathFinder pf = new AStarPathFinder(start.getX(), start.getY(), start.getZ(), goal, favoredPositions, context);
return pf.calculate(timeout); return pf.calculate(timeout);
} catch (Exception e) { } catch (Exception e) {
logDebug("Pathing exception: " + e); logDebug("Pathing exception: " + e);
+55 -34
View File
@@ -33,41 +33,62 @@ import java.util.*;
*/ */
public final class CachedChunk implements IBlockTypeAccess, Helper { public final class CachedChunk implements IBlockTypeAccess, Helper {
public static final Set<Block> BLOCKS_TO_KEEP_TRACK_OF = Collections.unmodifiableSet(new HashSet<Block>() {{ public static final Set<Block> BLOCKS_TO_KEEP_TRACK_OF;
add(Blocks.DIAMOND_ORE);
add(Blocks.DIAMOND_BLOCK);
//add(Blocks.COAL_ORE);
add(Blocks.COAL_BLOCK);
//add(Blocks.IRON_ORE);
add(Blocks.IRON_BLOCK);
//add(Blocks.GOLD_ORE);
add(Blocks.GOLD_BLOCK);
add(Blocks.EMERALD_ORE);
add(Blocks.EMERALD_BLOCK);
add(Blocks.ENDER_CHEST); static {
add(Blocks.FURNACE); HashSet<Block> temp = new HashSet<>();
add(Blocks.CHEST); temp.add(Blocks.DIAMOND_ORE);
add(Blocks.TRAPPED_CHEST); temp.add(Blocks.DIAMOND_BLOCK);
add(Blocks.END_PORTAL); //temp.add(Blocks.COAL_ORE);
add(Blocks.END_PORTAL_FRAME); temp.add(Blocks.COAL_BLOCK);
add(Blocks.MOB_SPAWNER); //temp.add(Blocks.IRON_ORE);
// TODO add all shulker colors temp.add(Blocks.IRON_BLOCK);
add(Blocks.PORTAL); //temp.add(Blocks.GOLD_ORE);
add(Blocks.HOPPER); temp.add(Blocks.GOLD_BLOCK);
add(Blocks.BEACON); temp.add(Blocks.EMERALD_ORE);
add(Blocks.BREWING_STAND); temp.add(Blocks.EMERALD_BLOCK);
add(Blocks.SKULL);
add(Blocks.ENCHANTING_TABLE); temp.add(Blocks.ENDER_CHEST);
add(Blocks.ANVIL); temp.add(Blocks.FURNACE);
add(Blocks.LIT_FURNACE); temp.add(Blocks.CHEST);
add(Blocks.BED); temp.add(Blocks.TRAPPED_CHEST);
add(Blocks.DRAGON_EGG); temp.add(Blocks.END_PORTAL);
add(Blocks.JUKEBOX); temp.add(Blocks.END_PORTAL_FRAME);
add(Blocks.END_GATEWAY); temp.add(Blocks.MOB_SPAWNER);
add(Blocks.WEB); temp.add(Blocks.BARRIER);
add(Blocks.NETHER_WART); temp.add(Blocks.OBSERVER);
}}); temp.add(Blocks.WHITE_SHULKER_BOX);
temp.add(Blocks.ORANGE_SHULKER_BOX);
temp.add(Blocks.MAGENTA_SHULKER_BOX);
temp.add(Blocks.LIGHT_BLUE_SHULKER_BOX);
temp.add(Blocks.YELLOW_SHULKER_BOX);
temp.add(Blocks.LIME_SHULKER_BOX);
temp.add(Blocks.PINK_SHULKER_BOX);
temp.add(Blocks.GRAY_SHULKER_BOX);
temp.add(Blocks.SILVER_SHULKER_BOX);
temp.add(Blocks.CYAN_SHULKER_BOX);
temp.add(Blocks.PURPLE_SHULKER_BOX);
temp.add(Blocks.BLUE_SHULKER_BOX);
temp.add(Blocks.BROWN_SHULKER_BOX);
temp.add(Blocks.GREEN_SHULKER_BOX);
temp.add(Blocks.RED_SHULKER_BOX);
temp.add(Blocks.BLACK_SHULKER_BOX);
temp.add(Blocks.PORTAL);
temp.add(Blocks.HOPPER);
temp.add(Blocks.BEACON);
temp.add(Blocks.BREWING_STAND);
temp.add(Blocks.SKULL);
temp.add(Blocks.ENCHANTING_TABLE);
temp.add(Blocks.ANVIL);
temp.add(Blocks.LIT_FURNACE);
temp.add(Blocks.BED);
temp.add(Blocks.DRAGON_EGG);
temp.add(Blocks.JUKEBOX);
temp.add(Blocks.END_GATEWAY);
temp.add(Blocks.WEB);
temp.add(Blocks.NETHER_WART);
BLOCKS_TO_KEEP_TRACK_OF = Collections.unmodifiableSet(temp);
}
/** /**
* The size of the chunk data in bits. Equal to 16 KiB. * The size of the chunk data in bits. Equal to 16 KiB.
@@ -41,10 +41,12 @@ import java.util.Optional;
public final class AStarPathFinder extends AbstractNodeCostSearch implements Helper { public final class AStarPathFinder extends AbstractNodeCostSearch implements Helper {
private final Optional<HashSet<Long>> favoredPositions; private final Optional<HashSet<Long>> favoredPositions;
private final CalculationContext calcContext;
public AStarPathFinder(int startX, int startY, int startZ, Goal goal, Optional<HashSet<Long>> favoredPositions) { public AStarPathFinder(int startX, int startY, int startZ, Goal goal, Optional<HashSet<Long>> favoredPositions, CalculationContext context) {
super(startX, startY, startZ, goal); super(startX, startY, startZ, goal);
this.favoredPositions = favoredPositions; this.favoredPositions = favoredPositions;
this.calcContext = context;
} }
@Override @Override
@@ -61,7 +63,6 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel
bestHeuristicSoFar[i] = startNode.estimatedCostToGoal; bestHeuristicSoFar[i] = startNode.estimatedCostToGoal;
bestSoFar[i] = startNode; bestSoFar[i] = startNode;
} }
CalculationContext calcContext = new CalculationContext();
MutableMoveResult res = new MutableMoveResult(); MutableMoveResult res = new MutableMoveResult();
HashSet<Long> favored = favoredPositions.orElse(null); HashSet<Long> favored = favoredPositions.orElse(null);
BetterWorldBorder worldBorder = new BetterWorldBorder(world().getWorldBorder()); BetterWorldBorder worldBorder = new BetterWorldBorder(world().getWorldBorder());
@@ -99,14 +100,12 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel
for (Moves moves : Moves.values()) { for (Moves moves : Moves.values()) {
int newX = currentNode.x + moves.xOffset; int newX = currentNode.x + moves.xOffset;
int newZ = currentNode.z + moves.zOffset; int newZ = currentNode.z + moves.zOffset;
if (newX >> 4 != currentNode.x >> 4 || newZ >> 4 != currentNode.z >> 4) { if ((newX >> 4 != currentNode.x >> 4 || newZ >> 4 != currentNode.z >> 4) && !BlockStateInterface.isLoaded(newX, newZ)) {
// only need to check if the destination is a loaded chunk if it's in a different chunk than the start of the movement // only need to check if the destination is a loaded chunk if it's in a different chunk than the start of the movement
if (!BlockStateInterface.isLoaded(newX, newZ)) { if (!moves.dynamicXZ) { // only increment the counter if the movement would have gone out of bounds guaranteed
if (!moves.dynamicXZ) { // only increment the counter if the movement would have gone out of bounds guaranteed numEmptyChunk++;
numEmptyChunk++;
}
continue;
} }
continue;
} }
if (!moves.dynamicXZ && !worldBorder.entirelyContains(newX, newZ)) { if (!moves.dynamicXZ && !worldBorder.entirelyContains(newX, newZ)) {
continue; continue;
@@ -87,10 +87,7 @@ public class CalculationContext implements Helper {
if (!allowBreak()) { if (!allowBreak()) {
return false; return false;
} }
if (isPossiblyProtected(x, y, z)) { return !isPossiblyProtected(x, y, z);
return false;
}
return true;
} }
public boolean isPossiblyProtected(int x, int y, int z) { public boolean isPossiblyProtected(int x, int y, int z) {
@@ -24,7 +24,6 @@ import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.Rotation; import baritone.api.utils.Rotation;
import baritone.api.utils.RotationUtils; import baritone.api.utils.RotationUtils;
import baritone.api.utils.VecUtils; import baritone.api.utils.VecUtils;
import baritone.behavior.LookBehavior;
import baritone.utils.BlockBreakHelper; import baritone.utils.BlockBreakHelper;
import baritone.utils.BlockStateInterface; import baritone.utils.BlockStateInterface;
import baritone.utils.Helper; import baritone.utils.Helper;
@@ -115,7 +114,7 @@ public abstract class Movement implements IMovement, Helper, MovementHelper {
*/ */
@Override @Override
public MovementStatus update() { public MovementStatus update() {
player().capabilities.allowFlying = false; player().capabilities.isFlying = false;
MovementState latestState = updateState(currentState); MovementState latestState = updateState(currentState);
if (BlockStateInterface.isLiquid(playerFeet())) { if (BlockStateInterface.isLiquid(playerFeet())) {
latestState.setInput(Input.JUMP, true); latestState.setInput(Input.JUMP, true);
@@ -126,7 +125,7 @@ public abstract class Movement implements IMovement, Helper, MovementHelper {
// If the movement target has to force the new rotations, or we aren't using silent move, then force the rotations // If the movement target has to force the new rotations, or we aren't using silent move, then force the rotations
latestState.getTarget().getRotation().ifPresent(rotation -> latestState.getTarget().getRotation().ifPresent(rotation ->
LookBehavior.INSTANCE.updateTarget( Baritone.INSTANCE.getLookBehavior().updateTarget(
rotation, rotation,
latestState.getTarget().hasToForceRotations())); latestState.getTarget().hasToForceRotations()));
@@ -226,7 +226,7 @@ public interface MovementHelper extends ActionCosts, Helper {
return true; return true;
} }
return facing == playerFacing == open; return (facing == playerFacing) == open;
} }
static boolean avoidWalkingInto(Block block) { static boolean avoidWalkingInto(Block block) {
@@ -295,10 +295,7 @@ public interface MovementHelper extends ActionCosts, Helper {
} }
return true; return true;
} }
if (block instanceof BlockStairs) { return block instanceof BlockStairs;
return true;
}
return false;
} }
static boolean canWalkOn(BetterBlockPos pos, IBlockState state) { static boolean canWalkOn(BetterBlockPos pos, IBlockState state) {
@@ -97,21 +97,19 @@ public class MovementAscend extends Movement {
} }
} }
IBlockState srcUp2 = null; IBlockState srcUp2 = null;
if (BlockStateInterface.get(x, y + 3, z).getBlock() instanceof BlockFalling) {//it would fall on us and possibly suffocate us if (BlockStateInterface.get(x, y + 3, z).getBlock() instanceof BlockFalling && (MovementHelper.canWalkThrough(x, y + 1, z) || !((srcUp2 = BlockStateInterface.get(x, y + 2, z)).getBlock() instanceof BlockFalling))) {//it would fall on us and possibly suffocate us
// HOWEVER, we assume that we're standing in the start position // HOWEVER, we assume that we're standing in the start position
// that means that src and src.up(1) are both air // that means that src and src.up(1) are both air
// maybe they aren't now, but they will be by the time this starts // maybe they aren't now, but they will be by the time this starts
if (MovementHelper.canWalkThrough(x, y + 1, z) || !((srcUp2 = BlockStateInterface.get(x, y + 2, z)).getBlock() instanceof BlockFalling)) { // if the lower one is can't walk through and the upper one is falling, that means that by standing on src
// if the lower one is can't walk through and the upper one is falling, that means that by standing on src // (the presupposition of this Movement)
// (the presupposition of this Movement) // we have necessarily already cleared the entire BlockFalling stack
// we have necessarily already cleared the entire BlockFalling stack // on top of our head
// on top of our head
// as in, if we have a block, then two BlockFallings on top of it // as in, if we have a block, then two BlockFallings on top of it
// and that block is x, y+1, z, and we'd have to clear it to even start this movement // and that block is x, y+1, z, and we'd have to clear it to even start this movement
// we don't need to worry about those BlockFallings because we've already cleared them // we don't need to worry about those BlockFallings because we've already cleared them
return COST_INF; return COST_INF;
}
// you may think we only need to check srcUp2, not srcUp // you may think we only need to check srcUp2, not srcUp
// however, in the scenario where glitchy world gen where unsupported sand / gravel generates // however, in the scenario where glitchy world gen where unsupported sand / gravel generates
// it's possible srcUp is AIR from the start, and srcUp2 is falling // it's possible srcUp is AIR from the start, and srcUp2 is falling
@@ -206,10 +204,8 @@ public class MovementAscend extends Movement {
return state.setStatus(MovementStatus.UNREACHABLE); return state.setStatus(MovementStatus.UNREACHABLE);
} }
MovementHelper.moveTowards(state, dest); MovementHelper.moveTowards(state, dest);
if (MovementHelper.isBottomSlab(jumpingOnto)) { if (MovementHelper.isBottomSlab(jumpingOnto) && !MovementHelper.isBottomSlab(src.down())) {
if (!MovementHelper.isBottomSlab(src.down())) { return state; // don't jump while walking from a non double slab into a bottom slab
return state; // don't jump while walking from a non double slab into a bottom slab
}
} }
if (Baritone.settings().assumeStep.get()) { if (Baritone.settings().assumeStep.get()) {
@@ -183,11 +183,10 @@ public class MovementDescend extends Movement {
} }
BlockPos playerFeet = playerFeet(); BlockPos playerFeet = playerFeet();
if (playerFeet.equals(dest)) { if (playerFeet.equals(dest) && (BlockStateInterface.isLiquid(dest) || player().posY - playerFeet.getY() < 0.094)) { // lilypads
if (BlockStateInterface.isLiquid(dest) || player().posY - playerFeet.getY() < 0.094) { // lilypads // Wait until we're actually on the ground before saying we're done because sometimes we continue to fall if the next action starts immediately
// Wait until we're actually on the ground before saying we're done because sometimes we continue to fall if the next action starts immediately return state.setStatus(MovementStatus.SUCCESS);
return state.setStatus(MovementStatus.SUCCESS); /* else {
}/* else {
// System.out.println(player().posY + " " + playerFeet.getY() + " " + (player().posY - playerFeet.getY())); // System.out.println(player().posY + " " + playerFeet.getY() + " " + (player().posY - playerFeet.getY()));
}*/ }*/
} }
@@ -101,22 +101,18 @@ public class MovementDiagonal extends Movement {
return COST_INF; return COST_INF;
} }
IBlockState pb3 = BlockStateInterface.get(destX, y + 1, z); IBlockState pb3 = BlockStateInterface.get(destX, y + 1, z);
if (optionA == 0) { if (optionA == 0 && ((MovementHelper.avoidWalkingInto(pb2.getBlock()) && pb2.getBlock() != Blocks.WATER) || (MovementHelper.avoidWalkingInto(pb3.getBlock()) && pb3.getBlock() != Blocks.WATER))) {
// at this point we're done calculating optionA, so we can check if it's actually possible to edge around in that direction // at this point we're done calculating optionA, so we can check if it's actually possible to edge around in that direction
if ((MovementHelper.avoidWalkingInto(pb2.getBlock()) && pb2.getBlock() != Blocks.WATER) || (MovementHelper.avoidWalkingInto(pb3.getBlock()) && pb3.getBlock() != Blocks.WATER)) { return COST_INF;
return COST_INF;
}
} }
optionB += MovementHelper.getMiningDurationTicks(context, destX, y + 1, z, pb3, true); optionB += MovementHelper.getMiningDurationTicks(context, destX, y + 1, z, pb3, true);
if (optionA != 0 && optionB != 0) { if (optionA != 0 && optionB != 0) {
// and finally, if the cost is nonzero for both ways to approach this diagonal, it's not possible // and finally, if the cost is nonzero for both ways to approach this diagonal, it's not possible
return COST_INF; return COST_INF;
} }
if (optionB == 0) { if (optionB == 0 && ((MovementHelper.avoidWalkingInto(pb0.getBlock()) && pb0.getBlock() != Blocks.WATER) || (MovementHelper.avoidWalkingInto(pb1.getBlock()) && pb1.getBlock() != Blocks.WATER))) {
// and now that option B is fully calculated, see if we can edge around that way // and now that option B is fully calculated, see if we can edge around that way
if ((MovementHelper.avoidWalkingInto(pb0.getBlock()) && pb0.getBlock() != Blocks.WATER) || (MovementHelper.avoidWalkingInto(pb1.getBlock()) && pb1.getBlock() != Blocks.WATER)) { return COST_INF;
return COST_INF;
}
} }
boolean water = false; boolean water = false;
if (BlockStateInterface.isWater(BlockStateInterface.getBlock(x, y, z)) || BlockStateInterface.isWater(destInto.getBlock())) { if (BlockStateInterface.isWater(BlockStateInterface.getBlock(x, y, z)) || BlockStateInterface.isWater(destInto.getBlock())) {
@@ -54,16 +54,12 @@ public class MovementPillar extends Movement {
if (fromDownDown.getBlock() instanceof BlockLadder || fromDownDown.getBlock() instanceof BlockVine) { if (fromDownDown.getBlock() instanceof BlockLadder || fromDownDown.getBlock() instanceof BlockVine) {
return COST_INF; return COST_INF;
} }
if (fromDownDown.getBlock() instanceof BlockSlab) { if (fromDownDown.getBlock() instanceof BlockSlab && !((BlockSlab) fromDownDown.getBlock()).isDouble() && fromDownDown.getValue(BlockSlab.HALF) == BlockSlab.EnumBlockHalf.BOTTOM) {
if (!((BlockSlab) fromDownDown.getBlock()).isDouble() && fromDownDown.getValue(BlockSlab.HALF) == BlockSlab.EnumBlockHalf.BOTTOM) { return COST_INF; // can't pillar up from a bottom slab onto a non ladder
return COST_INF; // can't pillar up from a bottom slab onto a non ladder
}
} }
} }
if (fromDown instanceof BlockVine) { if (fromDown instanceof BlockVine && !hasAgainst(x, y, z)) {
if (!hasAgainst(x, y, z)) { return COST_INF;
return COST_INF;
}
} }
IBlockState toBreak = BlockStateInterface.get(x, y + 2, z); IBlockState toBreak = BlockStateInterface.get(x, y + 2, z);
Block toBreakBlock = toBreak.getBlock(); Block toBreakBlock = toBreak.getBlock();
@@ -189,11 +189,9 @@ public class MovementTraverse extends Movement {
} else if (pb1.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(dest, src)) { } else if (pb1.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(dest, src)) {
isDoorActuallyBlockingUs = true; isDoorActuallyBlockingUs = true;
} }
if (isDoorActuallyBlockingUs) { if (isDoorActuallyBlockingUs && !(Blocks.IRON_DOOR.equals(pb0.getBlock()) || Blocks.IRON_DOOR.equals(pb1.getBlock()))) {
if (!(Blocks.IRON_DOOR.equals(pb0.getBlock()) || Blocks.IRON_DOOR.equals(pb1.getBlock()))) { return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), VecUtils.calculateBlockCenter(positionsToBreak[0])), true))
return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), VecUtils.calculateBlockCenter(positionsToBreak[0])), true)) .setInput(InputOverrideHandler.Input.CLICK_RIGHT, true);
.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true);
}
} }
} }
@@ -267,11 +265,8 @@ public class MovementTraverse extends Movement {
state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations()), true)); state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations()), true));
EnumFacing side = Minecraft.getMinecraft().objectMouseOver.sideHit; EnumFacing side = Minecraft.getMinecraft().objectMouseOver.sideHit;
if (Objects.equals(RayTraceUtils.getSelectedBlock().orElse(null), against1) && (Minecraft.getMinecraft().player.isSneaking() || Baritone.settings().assumeSafeWalk.get())) { if (Objects.equals(RayTraceUtils.getSelectedBlock().orElse(null), against1) && (Minecraft.getMinecraft().player.isSneaking() || Baritone.settings().assumeSafeWalk.get()) && RayTraceUtils.getSelectedBlock().get().offset(side).equals(positionToPlace)) {
if (RayTraceUtils.getSelectedBlock().get().offset(side).equals(positionToPlace)) { return state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true);
return state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true);
}
// wrong side?
} }
//System.out.println("Trying to look at " + against1 + ", actually looking at" + RayTraceUtils.getSelectedBlock()); //System.out.println("Trying to look at " + against1 + ", actually looking at" + RayTraceUtils.getSelectedBlock());
return state.setInput(InputOverrideHandler.Input.CLICK_LEFT, true); return state.setInput(InputOverrideHandler.Input.CLICK_LEFT, true);
@@ -326,10 +326,7 @@ public class PathExecutor implements IPathExecutor, Helper {
// when we're midair in the middle of a fall, we're very far from both the beginning and the end, but we aren't actually off path // when we're midair in the middle of a fall, we're very far from both the beginning and the end, but we aren't actually off path
if (path.movements().get(pathPosition) instanceof MovementFall) { if (path.movements().get(pathPosition) instanceof MovementFall) {
BlockPos fallDest = path.positions().get(pathPosition + 1); // .get(pathPosition) is the block we fell off of BlockPos fallDest = path.positions().get(pathPosition + 1); // .get(pathPosition) is the block we fell off of
if (VecUtils.entityFlatDistanceToCenter(player(), fallDest) < leniency) { // ignore Y by using flat distance return VecUtils.entityFlatDistanceToCenter(player(), fallDest) >= leniency; // ignore Y by using flat distance
return false;
}
return true;
} else { } else {
return true; return true;
} }
@@ -427,20 +424,13 @@ public class PathExecutor implements IPathExecutor, Helper {
} }
private static boolean canSprintInto(IMovement current, IMovement next) { private static boolean canSprintInto(IMovement current, IMovement next) {
if (next instanceof MovementDescend) { if (next instanceof MovementDescend && next.getDirection().equals(current.getDirection())) {
if (next.getDirection().equals(current.getDirection())) {
return true;
}
}
if (next instanceof MovementTraverse) {
if (next.getDirection().down().equals(current.getDirection()) && MovementHelper.canWalkOn(next.getDest().down())) {
return true;
}
}
if (next instanceof MovementDiagonal && Baritone.settings().allowOvershootDiagonalDescend.get()) {
return true; return true;
} }
return false; if (next instanceof MovementTraverse && next.getDirection().down().equals(current.getDirection()) && MovementHelper.canWalkOn(next.getDest().down())) {
return true;
}
return next instanceof MovementDiagonal && Baritone.settings().allowOvershootDiagonalDescend.get();
} }
private void onChangeInPathPosition() { private void onChangeInPathPosition() {
@@ -17,11 +17,11 @@
package baritone.utils; package baritone.utils;
import baritone.Baritone;
import baritone.api.event.events.TickEvent; import baritone.api.event.events.TickEvent;
import baritone.api.event.listener.AbstractGameEventListener; import baritone.api.event.listener.AbstractGameEventListener;
import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.Goal;
import baritone.api.pathing.goals.GoalBlock; import baritone.api.pathing.goals.GoalBlock;
import baritone.behavior.PathingBehavior;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiMainMenu; import net.minecraft.client.gui.GuiMainMenu;
import net.minecraft.client.settings.GameSettings; import net.minecraft.client.settings.GameSettings;
@@ -105,8 +105,8 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper {
} }
// Setup Baritone's pathing goal and (if needed) begin pathing // Setup Baritone's pathing goal and (if needed) begin pathing
PathingBehavior.INSTANCE.setGoal(GOAL); Baritone.INSTANCE.getPathingBehavior().setGoal(GOAL);
PathingBehavior.INSTANCE.path(); Baritone.INSTANCE.getPathingBehavior().path();
// If we have reached our goal, print a message and safely close the game // If we have reached our goal, print a message and safely close the game
if (GOAL.isInGoal(playerFeet())) { if (GOAL.isInGoal(playerFeet())) {
@@ -26,8 +26,6 @@ import baritone.api.pathing.movement.ActionCosts;
import baritone.api.utils.RayTraceUtils; import baritone.api.utils.RayTraceUtils;
import baritone.api.utils.SettingsUtil; import baritone.api.utils.SettingsUtil;
import baritone.behavior.Behavior; import baritone.behavior.Behavior;
import baritone.behavior.FollowBehavior;
import baritone.behavior.MineBehavior;
import baritone.behavior.PathingBehavior; import baritone.behavior.PathingBehavior;
import baritone.cache.ChunkPacker; import baritone.cache.ChunkPacker;
import baritone.cache.Waypoint; import baritone.cache.Waypoint;
@@ -48,22 +46,14 @@ import java.util.stream.Stream;
public class ExampleBaritoneControl extends Behavior implements Helper { public class ExampleBaritoneControl extends Behavior implements Helper {
public static ExampleBaritoneControl INSTANCE = new ExampleBaritoneControl(); public ExampleBaritoneControl(Baritone baritone) {
super(baritone);
private ExampleBaritoneControl() {
}
public void initAndRegister() {
Baritone.INSTANCE.registerBehavior(this);
} }
@Override @Override
public void onSendChatMessage(ChatEvent event) { public void onSendChatMessage(ChatEvent event) {
if (!Baritone.settings().chatControl.get()) { if (!Baritone.settings().chatControl.get() && !Baritone.settings().removePrefix.get()) {
if (!Baritone.settings().removePrefix.get()) { return;
return;
}
} }
String msg = event.getMessage(); String msg = event.getMessage();
if (Baritone.settings().prefix.get()) { if (Baritone.settings().prefix.get()) {
@@ -77,8 +67,9 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
} }
} }
public boolean runCommand(String msg) { public boolean runCommand(String msg0) {
msg = msg.toLowerCase(Locale.US).trim(); String msg = msg0.toLowerCase(Locale.US).trim(); // don't reassign the argument LOL
PathingBehavior pathingBehavior = baritone.getPathingBehavior();
List<Settings.Setting<Boolean>> toggleable = Baritone.settings().getAllValuesByType(Boolean.class); List<Settings.Setting<Boolean>> toggleable = Baritone.settings().getAllValuesByType(Boolean.class);
for (Settings.Setting<Boolean> setting : toggleable) { for (Settings.Setting<Boolean> setting : toggleable) {
if (msg.equalsIgnoreCase(setting.getName())) { if (msg.equalsIgnoreCase(setting.getName())) {
@@ -160,16 +151,16 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
logDirect("unable to parse integer " + ex); logDirect("unable to parse integer " + ex);
return true; return true;
} }
PathingBehavior.INSTANCE.setGoal(goal); pathingBehavior.setGoal(goal);
logDirect("Goal: " + goal); logDirect("Goal: " + goal);
return true; return true;
} }
if (msg.equals("path")) { if (msg.equals("path")) {
if (!PathingBehavior.INSTANCE.path()) { if (!pathingBehavior.path()) {
if (PathingBehavior.INSTANCE.getGoal() == null) { if (pathingBehavior.getGoal() == null) {
logDirect("No goal."); logDirect("No goal.");
} else { } else {
if (PathingBehavior.INSTANCE.getGoal().isInGoal(playerFeet())) { if (pathingBehavior.getGoal().isInGoal(playerFeet())) {
logDirect("Already in goal"); logDirect("Already in goal");
} else { } else {
logDirect("Currently executing a path. Please cancel it first."); logDirect("Currently executing a path. Please cancel it first.");
@@ -196,23 +187,23 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
return true; return true;
} }
if (msg.equals("axis")) { if (msg.equals("axis")) {
PathingBehavior.INSTANCE.setGoal(new GoalAxis()); pathingBehavior.setGoal(new GoalAxis());
PathingBehavior.INSTANCE.path(); pathingBehavior.path();
return true; return true;
} }
if (msg.equals("cancel") || msg.equals("stop")) { if (msg.equals("cancel") || msg.equals("stop")) {
MineBehavior.INSTANCE.cancel(); baritone.getMineBehavior().cancel();
FollowBehavior.INSTANCE.cancel(); baritone.getFollowBehavior().cancel();
PathingBehavior.INSTANCE.cancel(); pathingBehavior.cancel();
logDirect("ok canceled"); logDirect("ok canceled");
return true; return true;
} }
if (msg.equals("forcecancel")) { if (msg.equals("forcecancel")) {
MineBehavior.INSTANCE.cancel(); baritone.getMineBehavior().cancel();
FollowBehavior.INSTANCE.cancel(); baritone.getFollowBehavior().cancel();
PathingBehavior.INSTANCE.cancel(); pathingBehavior.cancel();
AbstractNodeCostSearch.forceCancel(); AbstractNodeCostSearch.forceCancel();
PathingBehavior.INSTANCE.forceCancel(); pathingBehavior.forceCancel();
logDirect("ok force canceled"); logDirect("ok force canceled");
return true; return true;
} }
@@ -222,7 +213,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
return true; return true;
} }
if (msg.equals("invert")) { if (msg.equals("invert")) {
Goal goal = PathingBehavior.INSTANCE.getGoal(); Goal goal = pathingBehavior.getGoal();
BlockPos runAwayFrom; BlockPos runAwayFrom;
if (goal instanceof GoalXZ) { if (goal instanceof GoalXZ) {
runAwayFrom = new BlockPos(((GoalXZ) goal).getX(), 0, ((GoalXZ) goal).getZ()); runAwayFrom = new BlockPos(((GoalXZ) goal).getX(), 0, ((GoalXZ) goal).getZ());
@@ -233,13 +224,13 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
logDirect("Inverting goal of player feet"); logDirect("Inverting goal of player feet");
runAwayFrom = playerFeet(); runAwayFrom = playerFeet();
} }
PathingBehavior.INSTANCE.setGoal(new GoalRunAway(1, runAwayFrom) { pathingBehavior.setGoal(new GoalRunAway(1, runAwayFrom) {
@Override @Override
public boolean isInGoal(BlockPos pos) { public boolean isInGoal(BlockPos pos) {
return false; return false;
} }
}); });
if (!PathingBehavior.INSTANCE.path()) { if (!pathingBehavior.path()) {
logDirect("Currently executing a path. Please cancel it first."); logDirect("Currently executing a path. Please cancel it first.");
} }
return true; return true;
@@ -252,10 +243,8 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
} else { } else {
for (EntityPlayer pl : world().playerEntities) { for (EntityPlayer pl : world().playerEntities) {
String theirName = pl.getName().trim().toLowerCase(); String theirName = pl.getName().trim().toLowerCase();
if (!theirName.equals(player().getName().trim().toLowerCase())) { // don't follow ourselves lol if (!theirName.equals(player().getName().trim().toLowerCase()) && (theirName.contains(name) || name.contains(theirName))) { // don't follow ourselves lol
if (theirName.contains(name) || name.contains(theirName)) { toFollow = Optional.of(pl);
toFollow = Optional.of(pl);
}
} }
} }
} }
@@ -263,7 +252,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
logDirect("Not found"); logDirect("Not found");
return true; return true;
} }
FollowBehavior.INSTANCE.follow(toFollow.get()); baritone.getFollowBehavior().follow(toFollow.get());
logDirect("Following " + toFollow.get()); logDirect("Following " + toFollow.get());
return true; return true;
} }
@@ -295,7 +284,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
int quantity = Integer.parseInt(blockTypes[1]); int quantity = Integer.parseInt(blockTypes[1]);
Block block = ChunkPacker.stringToBlock(blockTypes[0]); Block block = ChunkPacker.stringToBlock(blockTypes[0]);
Objects.requireNonNull(block); Objects.requireNonNull(block);
MineBehavior.INSTANCE.mine(quantity, block); baritone.getMineBehavior().mine(quantity, block);
logDirect("Will mine " + quantity + " " + blockTypes[0]); logDirect("Will mine " + quantity + " " + blockTypes[0]);
return true; return true;
} catch (NumberFormatException | ArrayIndexOutOfBoundsException | NullPointerException ex) {} } catch (NumberFormatException | ArrayIndexOutOfBoundsException | NullPointerException ex) {}
@@ -306,14 +295,14 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
} }
} }
MineBehavior.INSTANCE.mine(0, blockTypes); baritone.getMineBehavior().mine(0, blockTypes);
logDirect("Started mining blocks of type " + Arrays.toString(blockTypes)); logDirect("Started mining blocks of type " + Arrays.toString(blockTypes));
return true; return true;
} }
if (msg.startsWith("thisway")) { if (msg.startsWith("thisway")) {
try { try {
Goal goal = GoalXZ.fromDirection(playerFeetAsVec(), player().rotationYaw, Double.parseDouble(msg.substring(7).trim())); Goal goal = GoalXZ.fromDirection(playerFeetAsVec(), player().rotationYaw, Double.parseDouble(msg.substring(7).trim()));
PathingBehavior.INSTANCE.setGoal(goal); pathingBehavior.setGoal(goal);
logDirect("Goal: " + goal); logDirect("Goal: " + goal);
} catch (NumberFormatException ex) { } catch (NumberFormatException ex) {
logDirect("Error unable to parse '" + msg.substring(7).trim() + "' to a double."); logDirect("Error unable to parse '" + msg.substring(7).trim() + "' to a double.");
@@ -360,7 +349,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
name = parts[0]; name = parts[0];
} }
WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().addWaypoint(new Waypoint(name, Waypoint.Tag.USER, pos)); WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().addWaypoint(new Waypoint(name, Waypoint.Tag.USER, pos));
logDirect("Saved user defined position " + pos + " under name '" + name + "'. Say 'goto user' to set goal, say 'list user' to list."); logDirect("Saved user defined position " + pos + " under name '" + name + "'. Say 'goto " + name + "' to set goal, say 'list user' to list custom waypoints.");
return true; return true;
} }
if (msg.startsWith("goto")) { if (msg.startsWith("goto")) {
@@ -382,13 +371,13 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
return true; return true;
} }
} else { } else {
List<BlockPos> locs = MineBehavior.INSTANCE.scanFor(Collections.singletonList(block), 64); List<BlockPos> locs = baritone.getMineBehavior().searchWorld(Collections.singletonList(block), 64);
if (locs.isEmpty()) { if (locs.isEmpty()) {
logDirect("No locations for " + mining + " known, cancelling"); logDirect("No locations for " + mining + " known, cancelling");
return true; return true;
} }
PathingBehavior.INSTANCE.setGoal(new GoalComposite(locs.stream().map(GoalGetToBlock::new).toArray(Goal[]::new))); pathingBehavior.setGoal(new GoalComposite(locs.stream().map(GoalGetToBlock::new).toArray(Goal[]::new)));
PathingBehavior.INSTANCE.path(); pathingBehavior.path();
return true; return true;
} }
} else { } else {
@@ -399,11 +388,9 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
} }
} }
Goal goal = new GoalBlock(waypoint.getLocation()); Goal goal = new GoalBlock(waypoint.getLocation());
PathingBehavior.INSTANCE.setGoal(goal); pathingBehavior.setGoal(goal);
if (!PathingBehavior.INSTANCE.path()) { if (!pathingBehavior.path() && !goal.isInGoal(playerFeet())) {
if (!goal.isInGoal(playerFeet())) { logDirect("Currently executing a path. Please cancel it first.");
logDirect("Currently executing a path. Please cancel it first.");
}
} }
return true; return true;
} }
@@ -414,10 +401,10 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
// for some reason the default spawnpoint is underground sometimes // for some reason the default spawnpoint is underground sometimes
Goal goal = new GoalXZ(spawnPoint.getX(), spawnPoint.getZ()); Goal goal = new GoalXZ(spawnPoint.getX(), spawnPoint.getZ());
logDirect("spawn not saved, defaulting to world spawn. set goal to " + goal); logDirect("spawn not saved, defaulting to world spawn. set goal to " + goal);
PathingBehavior.INSTANCE.setGoal(goal); pathingBehavior.setGoal(goal);
} else { } else {
Goal goal = new GoalBlock(waypoint.getLocation()); Goal goal = new GoalBlock(waypoint.getLocation());
PathingBehavior.INSTANCE.setGoal(goal); pathingBehavior.setGoal(goal);
logDirect("Set goal to most recent bed " + goal); logDirect("Set goal to most recent bed " + goal);
} }
return true; return true;
@@ -433,8 +420,8 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
logDirect("home not saved"); logDirect("home not saved");
} else { } else {
Goal goal = new GoalBlock(waypoint.getLocation()); Goal goal = new GoalBlock(waypoint.getLocation());
PathingBehavior.INSTANCE.setGoal(goal); pathingBehavior.setGoal(goal);
PathingBehavior.INSTANCE.path(); pathingBehavior.path();
logDirect("Going to saved home " + goal); logDirect("Going to saved home " + goal);
} }
return true; return true;
@@ -457,7 +444,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
return true; return true;
} }
if (msg.equals("pause")) { if (msg.equals("pause")) {
boolean enabled = PathingBehavior.INSTANCE.toggle(); boolean enabled = pathingBehavior.toggle();
logDirect("Pathing Behavior has " + (enabled ? "resumed" : "paused") + "."); logDirect("Pathing Behavior has " + (enabled ? "resumed" : "paused") + ".");
return true; return true;
} }