diff --git a/.circleci/config.yml b/.circleci/config.yml deleted file mode 100644 index d9cdd911..00000000 --- a/.circleci/config.yml +++ /dev/null @@ -1,43 +0,0 @@ -# Java Gradle CircleCI 2.0 configuration file -# -# Check https://circleci.com/docs/2.0/language-java/ for more details -# -version: 2 -jobs: - build: - docker: - # specify the version you desire here - - image: circleci/openjdk:8-jdk - - # Specify service dependencies here if necessary - # CircleCI maintains a library of pre-built images - # documented at https://circleci.com/docs/2.0/circleci-images/ - # - image: circleci/postgres:9.4 - - working_directory: ~/repo - - environment: - # Customize the JVM maximum heap limit - JVM_OPTS: -Xmx3200m - TERM: dumb - - steps: - - checkout - - # Download and cache dependencies - - restore_cache: - keys: - - v1-dependencies-{{ checksum "build.gradle" }} - # fallback to using the latest cache if no exact match is found - - v1-dependencies- - - - run: gradle dependencies - - - save_cache: - paths: - - ~/.gradle - key: v1-dependencies-{{ checksum "build.gradle" }} - - # run tests! - - run: gradle test - diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000..dff5f3a5 --- /dev/null +++ b/.travis.yml @@ -0,0 +1 @@ +language: java diff --git a/FEATURES.md b/FEATURES.md new file mode 100644 index 00000000..998b546a --- /dev/null +++ b/FEATURES.md @@ -0,0 +1,48 @@ +# Pathing features +- **Long distance pathing and splicing** Baritone calculates paths in segments, and precalculates the next segment when the current one is about to end, so that it's moving towards the goal at all times. +- **Chunk caching** Baritone simplifies chunks to a compacted internal 2-bit representation (AIR, SOLID, WATER, AVOID) and stores them in RAM for better very-long-distance pathing. There is also an option to save these cached chunks to disk. Example +- **Block breaking** Baritone considers breaking blocks as part of its path. It also takes into account your current tool set and hot bar. For example, if you have a Eff V diamond pick, it may choose to mine through a stone barrier, while if you only had a wood pick it might be faster to climb over it. +- **Block placing** Baritone considers placing blocks as part of its path. This includes sneak-back-placing, pillaring, etc. It has a configurable penalty of placing a block (set to 1 second by default), to conserve its resources. The list of acceptable throwaway blocks is also configurable, and is cobble, dirt, or netherrack by default. Example +- **Falling** Baritone will fall up to 3 blocks onto solid ground (configurable, if you have Feather Falling and/or don't mind taking a little damage). If you have a water bucket on your hotbar, it will fall up to 23 blocks and place the bucket beneath it. It will fall an unlimited distance into existing still water. +- **Vines and ladders** Baritone understands how to climb and descend vines and ladders. There is experimental support for more advanced maneuvers, like strafing to a different ladder / vine column in midair (off by default, setting named `allowVines`). +- **Opening fence gates and doors** +- **Slabs and stairs** +- **Falling blocks** Baritone understands the costs of breaking blocks with falling blocks on top, and includes all of their break costs. Additionally, since it avoids breaking any blocks touching a liquid, it won't break the bottom of a gravel stack below a lava lake (anymore). +- **Avoiding dangerous blocks** Obviously, it knows not to walk through fire or on magma, not to corner over lava (that deals some damage), not to break any blocks touching a liquid (it might drown), etc. + +# Pathing method +Baritone uses a modified version of A*. + +- **Incremental cost backoff** Since most of the time Baritone only knows the terrain up to the render distance, it can't calculate a full path to the goal. Therefore it needs to select a segment to execute first (assuming it will calculate the next segment at the end of this one). It uses incremental cost backoff to select the best node by varying metrics, then paths to that node. This is unchanged from MineBot and I made a write-up that still applies. In essence, it keeps track of the best node by various increasing coefficients, then picks the node with the least coefficient that goes at least 5 blocks from the starting position. +- **Minimum improvement repropagation** The pathfinder ignores alternate routes that provide minimal improvements (less than 0.01 ticks of improvement), because the calculation cost of repropagating this to all connected nodes is much higher than the half-millisecond path time improvement it would get. +- **Backtrack cost favoring** While calculating the next segment, Baritone favors backtracking its current segment slightly, as a tiebreaker. This allows it to splice and jump onto the next segment as early as possible, if the next segment begins with a backtrack of the current one. Example + +# Configuring Baritone +All the settings and documentation are here. +To change a boolean setting, just say its name in chat (for example saying `allowBreak` toggles whether Baritone will consider breaking blocks). For a numeric setting, say its name then the new value (like `pathTimeoutMS 250`). It's case insensitive. + +# Goals +The pathing goal can be set to any of these options: +- **GoalBlock** one specific block that the player should stand inside at foot level +- **GoalXZ** an X and a Z coordinate, used for long distance pathing +- **GoalYLevel** a Y coordinate +- **GoalTwoBlocks** a block position that the player should stand in, either at foot or eye level +- **GoalGetToBlock** a block position that the player should stand adjacent to, below, or on top of +- **GoalNear** a block position that the player should get within a certain radius of, used for following entities + +And finally `GoalComposite`. `GoalComposite` is a list of other goals, any one of which satisfies the goal. For example, `mine diamond_ore` creates a `GoalComposite` of `GoalTwoBlocks`s for every diamond ore location it knows of. + + +# Future features +Things it doesn't have yet +- Trapdoors +- Sprint jumping in a 1x2 corridor + +See issues for more. + +Things it may not ever have, from most likely to least likely =( +- Parkour (jumping over gaps of any length) +- Boats +- Pigs +- Horses (2x3 path instead of 1x2) +- Elytra diff --git a/IMPACT.md b/IMPACT.md new file mode 100644 index 00000000..7fa22435 --- /dev/null +++ b/IMPACT.md @@ -0,0 +1,16 @@ +# Integration between Baritone and Impact + +Baritone will be in Impact 4.4 with nice integrations with its utility modules, but if you're impatient you can run Baritone on top of Impact 4.3 right now. + +You can either build Baritone yourself, or download the jar from September 4 from here + +To build it yourself, clone and setup Baritone (instructions in main README.md). Then, build the jar. From the command line, it's `./gradlew build` (or `gradlew build` on Windows). In IntelliJ, you can just start the `build` task in the Gradle menu. + +Copy the jar into place. It should be `build/libs/baritone-1.0.0.jar` in baritone. Copy it to your libraries in your Minecraft install. For example, on Mac I do `cp Documents/baritone/build/libs/baritone-1.0.0.jar Library/Application\ Support/minecraft/libraries/cabaletta/baritone/1.0.0/baritone-1.0.0.jar`. The first time you'll need to make the directory `cabaletta/baritone/1.0.0` in libraries first. + +Then, we'll need to modify the Impact launch json. Open `minecraft/versions/1.12.2-Impact_4.3/1.12.2-Impact_4.3.json` or copy your existing installation and rename the version folder, json, and id in the json. + +- Add the Baritone tweak class to line 7 "minecraftArguments" like so: `"minecraftArguments": " ... --tweakClass clientapi.load.ClientTweaker --tweakClass baritone.launch.BaritoneTweakerOptifine",`. You need the Optifine tweaker even though there is no Optifine involved, for reasons I don't quite understand. +- Add the Baritone library. Insert `{ "name": "cabaletta:baritone:1.0.0" },` between Impact and ClientAPI, which should be between lines 15 and 16. + +Restart the Minecraft launcher, then load Impact 4.3 as normal, and it should now include Baritone. diff --git a/README.md b/README.md index 2748cb4f..b95cc957 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,13 @@ # Baritone +[![Build Status](https://travis-ci.com/cabaletta/baritone.svg?branch=master)](https://travis-ci.com/cabaletta/baritone) + A Minecraft 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. +Features + +Baritone + Impact + # Setup - Open the project in IntelliJ as a Gradle project - Run the Gradle task `setupDecompWorkspace` @@ -10,6 +16,7 @@ the original version of the bot for Minecraft 1.8, rebuilt for 1.12.2. - Select the "Minecraft Client" launch config and run ## Command Line +On Mac OSX and Linux, use `./gradlew` instead of `gradlew`. ``` $ gradlew setupDecompWorkspace $ gradlew --refresh-dependencies @@ -31,10 +38,12 @@ PathingBehavior.INSTANCE.setGoal(new GoalXZ(10000, 20000)); PathingBehavior.INSTANCE.path(); ``` -# Can I use Baritone as a library in my hacked client? +# FAQ + +## Can I use Baritone as a library in my hacked client? Sure! -# How is it so fast? +## How is it so fast? -Magic \ No newline at end of file +Magic diff --git a/build.gradle b/build.gradle index 7dd75be8..bdb3c311 100755 --- a/build.gradle +++ b/build.gradle @@ -65,7 +65,7 @@ repositories { } dependencies { - implementation ('org.spongepowered:mixin:0.7.11-SNAPSHOT') { + runtime implementation('org.spongepowered:mixin:0.7.11-SNAPSHOT') { // Mixin includes a lot of dependencies that are too up-to-date exclude module: 'launchwrapper' exclude module: 'guava' diff --git a/proguard.pro b/proguard.pro new file mode 100644 index 00000000..7f0cfcdc --- /dev/null +++ b/proguard.pro @@ -0,0 +1,369 @@ +-injars baritone-1.0.0.jar +-outjars Obfuscated + + +-keepattributes Signature +-keepattributes *Annotation* + +-optimizationpasses 20 +-verbose + +-allowaccessmodification # anything not kept can be changed from public to private and inlined etc +-mergeinterfacesaggressively +-overloadaggressively +-dontusemixedcaseclassnames + +# instead of obfing to a, b, c, obf to baritone.a, baritone.b, baritone.c so as to not conflict with mcp +-flattenpackagehierarchy +-repackageclasses 'baritone' + +#-keep class baritone.behavior.** { *; } +#-keep class baritone.api.** { *; } +#-keep class baritone.* { *; } +#-keep class baritone.pathing.goals.** { *; } + +# setting names are reflected from field names, so keep field names +-keepclassmembers class baritone.Settings { + public ; +} + +# need to keep mixin names +-keep class baritone.launch.** { *; } + +# copy all necessary libraries into tempLibraries to build +-libraryjars '/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/lib/rt.jar' + +-libraryjars 'tempLibraries/1.12.2.jar' + +-libraryjars 'tempLibraries/authlib-1.5.25.jar' +-libraryjars 'tempLibraries/codecjorbis-20101023.jar' +-libraryjars 'tempLibraries/codecwav-20101023.jar' +-libraryjars 'tempLibraries/commons-codec-1.10.jar' +-libraryjars 'tempLibraries/commons-compress-1.8.1.jar' +-libraryjars 'tempLibraries/commons-io-2.5.jar' +-libraryjars 'tempLibraries/commons-lang3-3.5.jar' +-libraryjars 'tempLibraries/commons-logging-1.1.3.jar' +-libraryjars 'tempLibraries/fastutil-7.1.0.jar' +-libraryjars 'tempLibraries/gson-2.8.0.jar' +-libraryjars 'tempLibraries/guava-21.0.jar' +-libraryjars 'tempLibraries/httpclient-4.3.3.jar' +-libraryjars 'tempLibraries/httpcore-4.3.2.jar' +-libraryjars 'tempLibraries/icu4j-core-mojang-51.2.jar' +-libraryjars 'tempLibraries/java-objc-bridge-1.0.0-natives-osx.jar' +-libraryjars 'tempLibraries/java-objc-bridge-1.0.0.jar' +-libraryjars 'tempLibraries/jinput-2.0.5.jar' +-libraryjars 'tempLibraries/jinput-platform-2.0.5-natives-osx.jar' +-libraryjars 'tempLibraries/jna-4.4.0.jar' +-libraryjars 'tempLibraries/jopt-simple-5.0.3.jar' +-libraryjars 'tempLibraries/jsr305-3.0.1-sources.jar' +-libraryjars 'tempLibraries/jsr305-3.0.1.jar' +-libraryjars 'tempLibraries/jutils-1.0.0.jar' +-libraryjars 'tempLibraries/libraryjavasound-20101123.jar' +-libraryjars 'tempLibraries/librarylwjglopenal-20100824.jar' +-libraryjars 'tempLibraries/log4j-api-2.8.1.jar' +-libraryjars 'tempLibraries/log4j-core-2.8.1.jar' +-libraryjars 'tempLibraries/lwjgl-2.9.2-nightly-20140822.jar' +-libraryjars 'tempLibraries/lwjgl-platform-2.9.2-nightly-20140822-natives-osx.jar' +-libraryjars 'tempLibraries/lwjgl_util-2.9.2-nightly-20140822.jar' +-libraryjars 'tempLibraries/netty-all-4.1.9.Final.jar' +-libraryjars 'tempLibraries/oshi-core-1.1.jar' +-libraryjars 'tempLibraries/patchy-1.1.jar' +-libraryjars 'tempLibraries/platform-3.4.0.jar' +-libraryjars 'tempLibraries/realms-1.10.22.jar' +-libraryjars 'tempLibraries/soundsystem-20120107.jar' +-libraryjars 'tempLibraries/text2speech-1.10.3.jar' + +-libraryjars 'tempLibraries/mixin-0.7.8-SNAPSHOT.jar' +-libraryjars 'tempLibraries/launchwrapper-1.12.jar' + + + + +# Keep - Applications. Keep all application classes, along with their 'main' +# methods. +-keepclasseswithmembers public class * { + public static void main(java.lang.String[]); +} + +# Also keep - Enumerations. Keep the special static methods that are required in +# enumeration classes. +-keepclassmembers enum * { + public static **[] values(); + public static ** valueOf(java.lang.String); +} + +# Also keep - Database drivers. Keep all implementations of java.sql.Driver. +-keep class * extends java.sql.Driver + +# Also keep - Swing UI L&F. Keep all extensions of javax.swing.plaf.ComponentUI, +# along with the special 'createUI' method. +-keep class * extends javax.swing.plaf.ComponentUI { + public static javax.swing.plaf.ComponentUI createUI(javax.swing.JComponent); +} + +# Keep names - Native method names. Keep all native class/method names. +-keepclasseswithmembers,includedescriptorclasses,allowshrinking class * { + native ; +} + +# Remove - System method calls. Remove all invocations of System +# methods without side effects whose return values are not used. +-assumenosideeffects public class java.lang.System { + public static long currentTimeMillis(); + static java.lang.Class getCallerClass(); + public static int identityHashCode(java.lang.Object); + public static java.lang.SecurityManager getSecurityManager(); + public static java.util.Properties getProperties(); + public static java.lang.String getProperty(java.lang.String); + public static java.lang.String getenv(java.lang.String); + public static java.lang.String mapLibraryName(java.lang.String); + public static java.lang.String getProperty(java.lang.String,java.lang.String); +} + +# Remove - Math method calls. Remove all invocations of Math +# methods without side effects whose return values are not used. +-assumenosideeffects public class java.lang.Math { + public static double sin(double); + public static double cos(double); + public static double tan(double); + public static double asin(double); + public static double acos(double); + public static double atan(double); + public static double toRadians(double); + public static double toDegrees(double); + public static double exp(double); + public static double log(double); + public static double log10(double); + public static double sqrt(double); + public static double cbrt(double); + public static double IEEEremainder(double,double); + public static double ceil(double); + public static double floor(double); + public static double rint(double); + public static double atan2(double,double); + public static double pow(double,double); + public static int round(float); + public static long round(double); + public static double random(); + public static int abs(int); + public static long abs(long); + public static float abs(float); + public static double abs(double); + public static int max(int,int); + public static long max(long,long); + public static float max(float,float); + public static double max(double,double); + public static int min(int,int); + public static long min(long,long); + public static float min(float,float); + public static double min(double,double); + public static double ulp(double); + public static float ulp(float); + public static double signum(double); + public static float signum(float); + public static double sinh(double); + public static double cosh(double); + public static double tanh(double); + public static double hypot(double,double); + public static double expm1(double); + public static double log1p(double); +} + +# Remove - Number method calls. Remove all invocations of Number +# methods without side effects whose return values are not used. +-assumenosideeffects public class java.lang.* extends java.lang.Number { + public static java.lang.String toString(byte); + public static java.lang.Byte valueOf(byte); + public static byte parseByte(java.lang.String); + public static byte parseByte(java.lang.String,int); + public static java.lang.Byte valueOf(java.lang.String,int); + public static java.lang.Byte valueOf(java.lang.String); + public static java.lang.Byte decode(java.lang.String); + public int compareTo(java.lang.Byte); + public static java.lang.String toString(short); + public static short parseShort(java.lang.String); + public static short parseShort(java.lang.String,int); + public static java.lang.Short valueOf(java.lang.String,int); + public static java.lang.Short valueOf(java.lang.String); + public static java.lang.Short valueOf(short); + public static java.lang.Short decode(java.lang.String); + public static short reverseBytes(short); + public int compareTo(java.lang.Short); + public static java.lang.String toString(int,int); + public static java.lang.String toHexString(int); + public static java.lang.String toOctalString(int); + public static java.lang.String toBinaryString(int); + public static java.lang.String toString(int); + public static int parseInt(java.lang.String,int); + public static int parseInt(java.lang.String); + public static java.lang.Integer valueOf(java.lang.String,int); + public static java.lang.Integer valueOf(java.lang.String); + public static java.lang.Integer valueOf(int); + public static java.lang.Integer getInteger(java.lang.String); + public static java.lang.Integer getInteger(java.lang.String,int); + public static java.lang.Integer getInteger(java.lang.String,java.lang.Integer); + public static java.lang.Integer decode(java.lang.String); + public static int highestOneBit(int); + public static int lowestOneBit(int); + public static int numberOfLeadingZeros(int); + public static int numberOfTrailingZeros(int); + public static int bitCount(int); + public static int rotateLeft(int,int); + public static int rotateRight(int,int); + public static int reverse(int); + public static int signum(int); + public static int reverseBytes(int); + public int compareTo(java.lang.Integer); + public static java.lang.String toString(long,int); + public static java.lang.String toHexString(long); + public static java.lang.String toOctalString(long); + public static java.lang.String toBinaryString(long); + public static java.lang.String toString(long); + public static long parseLong(java.lang.String,int); + public static long parseLong(java.lang.String); + public static java.lang.Long valueOf(java.lang.String,int); + public static java.lang.Long valueOf(java.lang.String); + public static java.lang.Long valueOf(long); + public static java.lang.Long decode(java.lang.String); + public static java.lang.Long getLong(java.lang.String); + public static java.lang.Long getLong(java.lang.String,long); + public static java.lang.Long getLong(java.lang.String,java.lang.Long); + public static long highestOneBit(long); + public static long lowestOneBit(long); + public static int numberOfLeadingZeros(long); + public static int numberOfTrailingZeros(long); + public static int bitCount(long); + public static long rotateLeft(long,int); + public static long rotateRight(long,int); + public static long reverse(long); + public static int signum(long); + public static long reverseBytes(long); + public int compareTo(java.lang.Long); + public static java.lang.String toString(float); + public static java.lang.String toHexString(float); + public static java.lang.Float valueOf(java.lang.String); + public static java.lang.Float valueOf(float); + public static float parseFloat(java.lang.String); + public static boolean isNaN(float); + public static boolean isInfinite(float); + public static int floatToIntBits(float); + public static int floatToRawIntBits(float); + public static float intBitsToFloat(int); + public static int compare(float,float); + public boolean isNaN(); + public boolean isInfinite(); + public int compareTo(java.lang.Float); + public static java.lang.String toString(double); + public static java.lang.String toHexString(double); + public static java.lang.Double valueOf(java.lang.String); + public static java.lang.Double valueOf(double); + public static double parseDouble(java.lang.String); + public static boolean isNaN(double); + public static boolean isInfinite(double); + public static long doubleToLongBits(double); + public static long doubleToRawLongBits(double); + public static double longBitsToDouble(long); + public static int compare(double,double); + public boolean isNaN(); + public boolean isInfinite(); + public int compareTo(java.lang.Double); + public byte byteValue(); + public short shortValue(); + public int intValue(); + public long longValue(); + public float floatValue(); + public double doubleValue(); + public int compareTo(java.lang.Object); + public boolean equals(java.lang.Object); + public int hashCode(); + public java.lang.String toString(); +} + +# Remove - String method calls. Remove all invocations of String +# methods without side effects whose return values are not used. +-assumenosideeffects public class java.lang.String { + public static java.lang.String copyValueOf(char[]); + public static java.lang.String copyValueOf(char[],int,int); + public static java.lang.String valueOf(boolean); + public static java.lang.String valueOf(char); + public static java.lang.String valueOf(char[]); + public static java.lang.String valueOf(char[],int,int); + public static java.lang.String valueOf(double); + public static java.lang.String valueOf(float); + public static java.lang.String valueOf(int); + public static java.lang.String valueOf(java.lang.Object); + public static java.lang.String valueOf(long); + public boolean contentEquals(java.lang.StringBuffer); + public boolean endsWith(java.lang.String); + public boolean equalsIgnoreCase(java.lang.String); + public boolean equals(java.lang.Object); + public boolean matches(java.lang.String); + public boolean regionMatches(boolean,int,java.lang.String,int,int); + public boolean regionMatches(int,java.lang.String,int,int); + public boolean startsWith(java.lang.String); + public boolean startsWith(java.lang.String,int); + public byte[] getBytes(); + public byte[] getBytes(java.lang.String); + public char charAt(int); + public char[] toCharArray(); + public int compareToIgnoreCase(java.lang.String); + public int compareTo(java.lang.Object); + public int compareTo(java.lang.String); + public int hashCode(); + public int indexOf(int); + public int indexOf(int,int); + public int indexOf(java.lang.String); + public int indexOf(java.lang.String,int); + public int lastIndexOf(int); + public int lastIndexOf(int,int); + public int lastIndexOf(java.lang.String); + public int lastIndexOf(java.lang.String,int); + public int length(); + public java.lang.CharSequence subSequence(int,int); + public java.lang.String concat(java.lang.String); + public java.lang.String replaceAll(java.lang.String,java.lang.String); + public java.lang.String replace(char,char); + public java.lang.String replaceFirst(java.lang.String,java.lang.String); + public java.lang.String[] split(java.lang.String); + public java.lang.String[] split(java.lang.String,int); + public java.lang.String substring(int); + public java.lang.String substring(int,int); + public java.lang.String toLowerCase(); + public java.lang.String toLowerCase(java.util.Locale); + public java.lang.String toString(); + public java.lang.String toUpperCase(); + public java.lang.String toUpperCase(java.util.Locale); + public java.lang.String trim(); +} + +# Remove - StringBuffer method calls. Remove all invocations of StringBuffer +# methods without side effects whose return values are not used. +-assumenosideeffects public class java.lang.StringBuffer { + public java.lang.String toString(); + public char charAt(int); + public int capacity(); + public int codePointAt(int); + public int codePointBefore(int); + public int indexOf(java.lang.String,int); + public int lastIndexOf(java.lang.String); + public int lastIndexOf(java.lang.String,int); + public int length(); + public java.lang.String substring(int); + public java.lang.String substring(int,int); +} + +# Remove - StringBuilder method calls. Remove all invocations of StringBuilder +# methods without side effects whose return values are not used. +-assumenosideeffects public class java.lang.StringBuilder { + public java.lang.String toString(); + public char charAt(int); + public int capacity(); + public int codePointAt(int); + public int codePointBefore(int); + public int indexOf(java.lang.String,int); + public int lastIndexOf(java.lang.String); + public int lastIndexOf(java.lang.String,int); + public int length(); + public java.lang.String substring(int); + public java.lang.String substring(int,int); +} diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index bd678dd8..0b571264 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -21,6 +21,7 @@ import baritone.api.event.GameEventHandler; import baritone.behavior.Behavior; import baritone.behavior.impl.*; import baritone.utils.InputOverrideHandler; +import baritone.utils.ToolSet; import net.minecraft.client.Minecraft; import java.io.File; @@ -28,6 +29,7 @@ import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; +import java.util.function.Consumer; /** * @author Brady @@ -52,9 +54,9 @@ public enum Baritone { private File dir; /** - * List of runnables to be called after Baritone has initialized + * List of consumers to be called after Baritone has initialized */ - private List onInitRunnables; + private List> onInitConsumers; /** * Whether or not Baritone is active @@ -62,7 +64,7 @@ public enum Baritone { private boolean active; Baritone() { - this.onInitRunnables = new ArrayList<>(); + this.onInitConsumers = new ArrayList<>(); } public synchronized void init() { @@ -80,6 +82,7 @@ public enum Baritone { registerBehavior(LocationTrackingBehavior.INSTANCE); registerBehavior(FollowBehavior.INSTANCE); registerBehavior(MineBehavior.INSTANCE); + this.gameEventHandler.registerEventListener(ToolSet.INTERNAL_EVENT_LISTENER); } this.dir = new File(Minecraft.getMinecraft().gameDir, "baritone"); if (!Files.exists(dir.toPath())) { @@ -91,7 +94,7 @@ public enum Baritone { this.active = true; this.initialized = true; - this.onInitRunnables.forEach(Runnable::run); + this.onInitConsumers.forEach(consumer -> consumer.accept(this)); } public final boolean isInitialized() { @@ -131,7 +134,7 @@ public enum Baritone { return this.dir; } - public final void registerInitListener(Runnable runnable) { - this.onInitRunnables.add(runnable); + public final void registerInitListener(Consumer runnable) { + this.onInitConsumers.add(runnable); } } diff --git a/src/main/java/baritone/Settings.java b/src/main/java/baritone/Settings.java index 79bbec6b..2e6f0e39 100644 --- a/src/main/java/baritone/Settings.java +++ b/src/main/java/baritone/Settings.java @@ -77,6 +77,12 @@ public class Settings { */ public Setting allowVines = new Setting<>(false); + /** + * Slab behavior is complicated, disable this for higher path reliability. Leave enabled if you have bottom slabs + * everywhere in your base. + */ + public Setting allowWalkOnBottomSlab = new Setting<>(true); + /** * This is the big A* setting. * As long as your cost heuristic is an *underestimate*, it's guaranteed to find you the best path. @@ -122,8 +128,9 @@ public class Settings { /** * After calculating a path (potentially through cached chunks), artificially cut it off to just the part that is * entirely within currently loaded chunks. Improves path safety because cached chunks are heavily simplified. + * See issue #114 for why this is disabled. */ - public Setting cutoffAtLoadBoundary = new Setting<>(true); + public Setting cutoffAtLoadBoundary = new Setting<>(false); /** * Stop 5 movements before anything that made the path COST_INF. @@ -184,7 +191,12 @@ public class Settings { /** * Pathing can never take longer than this */ - public Setting pathTimeoutMS = new Setting<>(4000L); + public Setting pathTimeoutMS = new Setting<>(2000L); + + /** + * Planning ahead while executing a segment can never take longer than this + */ + public Setting planAheadTimeoutMS = new Setting<>(4000L); /** * For debugging, consider nodes much much slower @@ -217,6 +229,11 @@ public class Settings { */ public Setting chatControl = new Setting<>(true); + /** + * A second override over chatControl to force it on + */ + public Setting removePrefix = new Setting<>(false); + /** * Render the path */ diff --git a/src/main/java/baritone/api/event/GameEventHandler.java b/src/main/java/baritone/api/event/GameEventHandler.java index 88cd0560..45e86885 100644 --- a/src/main/java/baritone/api/event/GameEventHandler.java +++ b/src/main/java/baritone/api/event/GameEventHandler.java @@ -39,6 +39,7 @@ import baritone.api.event.events.*; import baritone.api.event.events.type.EventState; import baritone.api.event.listener.IGameEventListener; import baritone.chunk.WorldProvider; +import baritone.utils.BlockStateInterface; import baritone.utils.Helper; import baritone.utils.InputOverrideHandler; import baritone.utils.interfaces.Toggleable; @@ -133,6 +134,8 @@ public final class GameEventHandler implements IGameEventListener, Helper { public final void onWorldEvent(WorldEvent event) { WorldProvider cache = WorldProvider.INSTANCE; + BlockStateInterface.clearCachedChunk(); + switch (event.getState()) { case PRE: break; diff --git a/src/main/java/baritone/behavior/impl/LookBehaviorUtils.java b/src/main/java/baritone/behavior/impl/LookBehaviorUtils.java index fd75c478..91b046e0 100644 --- a/src/main/java/baritone/behavior/impl/LookBehaviorUtils.java +++ b/src/main/java/baritone/behavior/impl/LookBehaviorUtils.java @@ -17,10 +17,7 @@ package baritone.behavior.impl; -import baritone.utils.BlockStateInterface; -import baritone.utils.Helper; -import baritone.utils.Rotation; -import baritone.utils.Utils; +import baritone.utils.*; import net.minecraft.block.BlockFire; import net.minecraft.block.state.IBlockState; import net.minecraft.util.math.*; @@ -87,18 +84,6 @@ public final class LookBehaviorUtils implements Helper { return Optional.empty(); } - private static RayTraceResult rayTraceTowards(Rotation rotation) { - double blockReachDistance = mc.playerController.getBlockReachDistance(); - Vec3d start = mc.player.getPositionEyes(1.0F); - Vec3d direction = calcVec3dFromRotation(rotation); - Vec3d end = start.add( - direction.x * blockReachDistance, - direction.y * blockReachDistance, - direction.z * blockReachDistance - ); - return mc.world.rayTraceBlocks(start, end, false, false, true); - } - /** * Checks if coordinate is reachable with the given block-face rotation offset * @@ -108,7 +93,7 @@ public final class LookBehaviorUtils implements Helper { */ protected static Optional reachableOffset(BlockPos pos, Vec3d offsetPos) { Rotation rotation = Utils.calcRotationFromVec3d(mc.player.getPositionEyes(1.0F), offsetPos); - RayTraceResult result = rayTraceTowards(rotation); + RayTraceResult result = RayTraceUtils.rayTraceTowards(rotation); System.out.println(result); if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK) { if (result.getBlockPos().equals(pos)) { diff --git a/src/main/java/baritone/behavior/impl/MineBehavior.java b/src/main/java/baritone/behavior/impl/MineBehavior.java index e59058a8..0b4b3b2a 100644 --- a/src/main/java/baritone/behavior/impl/MineBehavior.java +++ b/src/main/java/baritone/behavior/impl/MineBehavior.java @@ -17,10 +17,12 @@ package baritone.behavior.impl; -import baritone.api.event.events.TickEvent; +import baritone.api.event.events.PathEvent; import baritone.behavior.Behavior; +import baritone.chunk.CachedChunk; import baritone.chunk.ChunkPacker; import baritone.chunk.WorldProvider; +import baritone.chunk.WorldScanner; import baritone.pathing.goals.Goal; import baritone.pathing.goals.GoalComposite; import baritone.pathing.goals.GoalTwoBlocks; @@ -29,6 +31,7 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.chunk.EmptyChunk; import java.util.ArrayList; +import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; @@ -44,43 +47,65 @@ public class MineBehavior extends Behavior { private MineBehavior() { } - String mining; + List mining; @Override - public void onTick(TickEvent event) { - if (event.getType() == TickEvent.Type.OUT) { - return; - } + public void onPathEvent(PathEvent event) { + updateGoal(); + } + + public void updateGoal() { if (mining == null) { return; } - List locs = new ArrayList<>(WorldProvider.INSTANCE.getCurrentWorld().cache.getLocationsOf(mining, 1, 1)); + List locs = scanFor(mining, 64); if (locs.isEmpty()) { displayChatMessageRaw("No locations for " + mining + " known, cancelling"); cancel(); return; } - BlockPos playerFeet = playerFeet(); - locs.sort(Comparator.comparingDouble(playerFeet::distanceSq)); - - // remove any that are within loaded chunks that aren't actually what we want - locs.removeAll(locs.stream() - .filter(pos -> !(world().getChunk(pos) instanceof EmptyChunk)) - .filter(pos -> !ChunkPacker.blockToString(BlockStateInterface.get(pos).getBlock()).equalsIgnoreCase(mining)) - .collect(Collectors.toList())); - if (locs.size() > 30) { - locs = locs.subList(0, 30); - } PathingBehavior.INSTANCE.setGoal(new GoalComposite(locs.stream().map(GoalTwoBlocks::new).toArray(Goal[]::new))); PathingBehavior.INSTANCE.path(); } - public void mine(String mining) { - this.mining = mining; + public static List scanFor(List mining, int max) { + List locs = new ArrayList<>(); + List uninteresting = new ArrayList<>(); + //long b = System.currentTimeMillis(); + for (String m : mining) { + if (CachedChunk.BLOCKS_TO_KEEP_TRACK_OF.contains(ChunkPacker.stringToBlock(m))) { + locs.addAll(WorldProvider.INSTANCE.getCurrentWorld().cache.getLocationsOf(m, 1, 1)); + } else { + uninteresting.add(m); + } + } + //System.out.println("Scan of cached chunks took " + (System.currentTimeMillis() - b) + "ms"); + if (!uninteresting.isEmpty()) { + //long before = System.currentTimeMillis(); + locs.addAll(WorldScanner.INSTANCE.scanLoadedChunks(uninteresting, max)); + //System.out.println("Scan of loaded chunks took " + (System.currentTimeMillis() - before) + "ms"); + } + BlockPos playerFeet = MineBehavior.INSTANCE.playerFeet(); + locs.sort(Comparator.comparingDouble(playerFeet::distanceSq)); + + // 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(ChunkPacker.blockToString(BlockStateInterface.get(pos).getBlock()).toLowerCase())) + .collect(Collectors.toList())); + if (locs.size() > max) { + locs = locs.subList(0, max); + } + return locs; + } + + public void mine(String... mining) { + this.mining = mining == null || mining.length == 0 ? null : new ArrayList<>(Arrays.asList(mining)); + updateGoal(); } public void cancel() { PathingBehavior.INSTANCE.cancel(); - mine(null); + mine(); } } diff --git a/src/main/java/baritone/behavior/impl/PathingBehavior.java b/src/main/java/baritone/behavior/impl/PathingBehavior.java index 4b5f1f43..fa651a87 100644 --- a/src/main/java/baritone/behavior/impl/PathingBehavior.java +++ b/src/main/java/baritone/behavior/impl/PathingBehavior.java @@ -27,6 +27,7 @@ import baritone.pathing.calc.AStarPathFinder; import baritone.pathing.calc.AbstractNodeCostSearch; import baritone.pathing.calc.IPathFinder; import baritone.pathing.goals.*; +import baritone.pathing.movement.MovementHelper; import baritone.pathing.path.IPath; import baritone.pathing.path.PathExecutor; import baritone.utils.BlockStateInterface; @@ -203,6 +204,12 @@ public class PathingBehavior extends Behavior { * @return true if this call started path calculation, false if it was already calculating or executing a path */ public boolean path() { + if (goal == null) { + return false; + } + if (goal.isInGoal(playerFeet())) { + return false; + } synchronized (pathPlanLock) { if (current != null) { return false; @@ -220,7 +227,7 @@ public class PathingBehavior extends Behavior { public BlockPos pathStart() { BlockPos feet = playerFeet(); - if (BlockStateInterface.get(feet.down()).getBlock().equals(Blocks.AIR)) { + if (BlockStateInterface.get(feet.down()).getBlock().equals(Blocks.AIR) && MovementHelper.canWalkOn(feet.down().down())) { return feet.down(); } return feet; @@ -317,9 +324,15 @@ public class PathingBehavior extends Behavior { goal = new GoalXZ(pos.getX(), pos.getZ()); } } + long timeout; + if (current == null) { + timeout = Baritone.settings().pathTimeoutMS.get(); + } else { + timeout = Baritone.settings().planAheadTimeoutMS.get(); + } try { IPathFinder pf = new AStarPathFinder(start, goal, previous.map(IPath::positions)); - return pf.calculate(); + return pf.calculate(timeout); } catch (Exception e) { displayChatMessageRaw("Pathing exception: " + e); e.printStackTrace(); diff --git a/src/main/java/baritone/chunk/ChunkPacker.java b/src/main/java/baritone/chunk/ChunkPacker.java index 90cdf02a..583dddc0 100644 --- a/src/main/java/baritone/chunk/ChunkPacker.java +++ b/src/main/java/baritone/chunk/ChunkPacker.java @@ -21,12 +21,16 @@ import baritone.pathing.movement.MovementHelper; import baritone.utils.Helper; import baritone.utils.pathing.PathingBlockType; import net.minecraft.block.Block; -import net.minecraft.block.BlockAir; +import net.minecraft.block.BlockDoublePlant; +import net.minecraft.block.BlockFlower; +import net.minecraft.block.BlockTallGrass; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; +import net.minecraft.world.chunk.BlockStateContainer; import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.chunk.storage.ExtendedBlockStorage; import java.util.*; @@ -38,27 +42,67 @@ public final class ChunkPacker implements Helper { private ChunkPacker() {} + private static BitSet originalPacker(Chunk chunk) { + BitSet bitSet = new BitSet(CachedChunk.SIZE); + for (int y = 0; y < 256; y++) { + for (int z = 0; z < 16; z++) { + for (int x = 0; x < 16; x++) { + int index = CachedChunk.getPositionIndex(x, y, z); + IBlockState state = chunk.getBlockState(x, y, z); + boolean[] bits = getPathingBlockType(state).getBits(); + bitSet.set(index, bits[0]); + bitSet.set(index + 1, bits[1]); + } + } + } + return bitSet; + } + public static CachedChunk pack(Chunk chunk) { long start = System.nanoTime() / 1000000L; Map> specialBlocks = new HashMap<>(); BitSet bitSet = new BitSet(CachedChunk.SIZE); try { - for (int y = 0; y < 256; y++) { - for (int z = 0; z < 16; z++) { - for (int x = 0; x < 16; x++) { - int index = CachedChunk.getPositionIndex(x, y, z); - Block block = chunk.getBlockState(x, y, z).getBlock(); - boolean[] bits = getPathingBlockType(block).getBits(); - bitSet.set(index, bits[0]); - bitSet.set(index + 1, bits[1]); - if (CachedChunk.BLOCKS_TO_KEEP_TRACK_OF.contains(block)) { - String name = blockToString(block); - specialBlocks.computeIfAbsent(name, b -> new ArrayList<>()).add(new BlockPos(x, y, z)); + ExtendedBlockStorage[] chunkInternalStorageArray = chunk.getBlockStorageArray(); + for (int y0 = 0; y0 < 16; y0++) { + ExtendedBlockStorage extendedblockstorage = chunkInternalStorageArray[y0]; + if (extendedblockstorage == null) { + // any 16x16x16 area that's all air will have null storage + // for example, in an ocean biome, with air from y=64 to y=256 + // the first 4 extended blocks storages will be full + // and the remaining 12 will be null + + // since the index into the bitset is calculated from the x y and z + // and doesn't function as an append, we can entirely skip the scanning + // since a bitset is initialized to all zero, and air is saved as zeros + continue; + } + BlockStateContainer bsc = extendedblockstorage.getData(); + int yReal = y0 << 4; + // the mapping of BlockStateContainer.getIndex from xyz to index is y << 8 | z << 4 | x; + // for better cache locality, iterate in that order + for (int y1 = 0; y1 < 16; y1++) { + int y = y1 | yReal; + for (int z = 0; z < 16; z++) { + for (int x = 0; x < 16; x++) { + int index = CachedChunk.getPositionIndex(x, y, z); + IBlockState state = bsc.get(x, y1, z); + boolean[] bits = getPathingBlockType(state).getBits(); + bitSet.set(index, bits[0]); + bitSet.set(index + 1, bits[1]); + Block block = state.getBlock(); + if (CachedChunk.BLOCKS_TO_KEEP_TRACK_OF.contains(block)) { + String name = blockToString(block); + specialBlocks.computeIfAbsent(name, b -> new ArrayList<>()).add(new BlockPos(x, y, z)); + } } } } } + /*if (!bitSet.equals(originalPacker(chunk))) { + throw new IllegalStateException(); + }*/ } catch (Exception e) { e.printStackTrace(); } @@ -101,20 +145,21 @@ public final class ChunkPacker implements Helper { return Block.getBlockFromName(name); } - private static PathingBlockType getPathingBlockType(Block block) { + private static PathingBlockType getPathingBlockType(IBlockState state) { + Block block = state.getBlock(); if (block.equals(Blocks.WATER)) { // only water source blocks are plausibly usable, flowing water should be avoid return PathingBlockType.WATER; } - if (MovementHelper.avoidWalkingInto(block) || block.equals(Blocks.FLOWING_WATER)) { + if (MovementHelper.avoidWalkingInto(block) || block.equals(Blocks.FLOWING_WATER) || MovementHelper.isBottomSlab(state)) { return PathingBlockType.AVOID; } // We used to do an AABB check here // however, this failed in the nether when you were near a nether fortress // because fences check their adjacent blocks in the world for their fence connection status to determine AABB shape // this caused a nullpointerexception when we saved chunks on unload, because they were unable to check their neighbors - if (block instanceof BlockAir) { + if (block == Blocks.AIR || block instanceof BlockTallGrass || block instanceof BlockDoublePlant || block instanceof BlockFlower) { return PathingBlockType.AIR; } diff --git a/src/main/java/baritone/chunk/WorldProvider.java b/src/main/java/baritone/chunk/WorldProvider.java index 709ddff8..275b6ac1 100644 --- a/src/main/java/baritone/chunk/WorldProvider.java +++ b/src/main/java/baritone/chunk/WorldProvider.java @@ -18,8 +18,8 @@ package baritone.chunk; import baritone.Baritone; -import baritone.launch.mixins.accessor.IAnvilChunkLoader; -import baritone.launch.mixins.accessor.IChunkProviderServer; +import baritone.utils.accessor.IAnvilChunkLoader; +import baritone.utils.accessor.IChunkProviderServer; import baritone.utils.Helper; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.server.integrated.IntegratedServer; diff --git a/src/main/java/baritone/chunk/WorldScanner.java b/src/main/java/baritone/chunk/WorldScanner.java new file mode 100644 index 00000000..cf4fb117 --- /dev/null +++ b/src/main/java/baritone/chunk/WorldScanner.java @@ -0,0 +1,100 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Baritone. If not, see . + */ + +package baritone.chunk; + +import baritone.utils.Helper; +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.multiplayer.ChunkProviderClient; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.chunk.BlockStateContainer; +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.chunk.storage.ExtendedBlockStorage; + +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; + +public enum WorldScanner implements Helper { + INSTANCE; + + public List scanLoadedChunks(List blockTypes, int max) { + List asBlocks = blockTypes.stream().map(ChunkPacker::stringToBlock).collect(Collectors.toList()); + if (asBlocks.contains(null)) { + throw new IllegalStateException("Invalid block name should have been caught earlier: " + blockTypes.toString()); + } + LinkedList res = new LinkedList<>(); + if (asBlocks.isEmpty()) { + return res; + } + ChunkProviderClient chunkProvider = world().getChunkProvider(); + + int playerChunkX = playerFeet().getX() >> 4; + int playerChunkZ = playerFeet().getZ() >> 4; + + int searchRadius = 0; + while (true) { + boolean allUnloaded = true; + for (int xoff = -searchRadius; xoff <= searchRadius; xoff++) { + for (int zoff = -searchRadius; zoff <= searchRadius; zoff++) { + int distance = xoff * xoff + zoff * zoff; + if (distance != searchRadius) { + continue; + } + int chunkX = xoff + playerChunkX; + int chunkZ = zoff + playerChunkZ; + Chunk chunk = chunkProvider.getLoadedChunk(chunkX, chunkZ); + if (chunk == null) { + continue; + } + allUnloaded = false; + ExtendedBlockStorage[] chunkInternalStorageArray = chunk.getBlockStorageArray(); + chunkX = chunkX << 4; + chunkZ = chunkZ << 4; + for (int y0 = 0; y0 < 16; y0++) { + ExtendedBlockStorage extendedblockstorage = chunkInternalStorageArray[y0]; + if (extendedblockstorage == null) { + continue; + } + int yReal = y0 << 4; + BlockStateContainer bsc = extendedblockstorage.getData(); + // the mapping of BlockStateContainer.getIndex from xyz to index is y << 8 | z << 4 | x; + // for better cache locality, iterate in that order + for (int y = 0; y < 16; y++) { + for (int z = 0; z < 16; z++) { + for (int x = 0; x < 16; x++) { + IBlockState state = bsc.get(x, y, z); + if (asBlocks.contains(state.getBlock())) { + res.add(new BlockPos(chunkX | x, yReal | y, chunkZ | z)); + } + } + } + } + } + } + } + if (allUnloaded) { + return res; + } + if (res.size() >= max) { + return res; + } + searchRadius++; + } + } +} diff --git a/src/main/java/baritone/launch/mixins/MixinAnvilChunkLoader.java b/src/main/java/baritone/launch/mixins/MixinAnvilChunkLoader.java new file mode 100644 index 00000000..96f38b87 --- /dev/null +++ b/src/main/java/baritone/launch/mixins/MixinAnvilChunkLoader.java @@ -0,0 +1,41 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Baritone. If not, see . + */ + +package baritone.launch.mixins; + +import baritone.utils.accessor.IAnvilChunkLoader; +import net.minecraft.world.chunk.storage.AnvilChunkLoader; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; + +import java.io.File; + +/** + * @author Brady + * @since 9/4/2018 + */ +@Mixin(AnvilChunkLoader.class) +public class MixinAnvilChunkLoader implements IAnvilChunkLoader { + + @Shadow @Final private File chunkSaveLocation; + + @Override + public File getChunkSaveLocation() { + return this.chunkSaveLocation; + } +} diff --git a/src/main/java/baritone/launch/mixins/MixinChunkProviderServer.java b/src/main/java/baritone/launch/mixins/MixinChunkProviderServer.java new file mode 100644 index 00000000..9a454d01 --- /dev/null +++ b/src/main/java/baritone/launch/mixins/MixinChunkProviderServer.java @@ -0,0 +1,40 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Baritone. If not, see . + */ + +package baritone.launch.mixins; + +import baritone.utils.accessor.IChunkProviderServer; +import net.minecraft.world.chunk.storage.IChunkLoader; +import net.minecraft.world.gen.ChunkProviderServer; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; + +/** + * @author Brady + * @since 9/4/2018 + */ +@Mixin(ChunkProviderServer.class) +public class MixinChunkProviderServer implements IChunkProviderServer { + + @Shadow @Final private IChunkLoader chunkLoader; + + @Override + public IChunkLoader getChunkLoader() { + return this.chunkLoader; + } +} diff --git a/src/main/java/baritone/pathing/calc/AStarPathFinder.java b/src/main/java/baritone/pathing/calc/AStarPathFinder.java index fbf2f8e8..83f2e179 100644 --- a/src/main/java/baritone/pathing/calc/AStarPathFinder.java +++ b/src/main/java/baritone/pathing/calc/AStarPathFinder.java @@ -53,7 +53,7 @@ public class AStarPathFinder extends AbstractNodeCostSearch implements Helper { } @Override - protected Optional calculate0() { + protected Optional calculate0(long timeout) { startNode = getNodeAtPosition(start); startNode.cost = 0; startNode.combinedCost = startNode.estimatedCostToGoal; @@ -72,7 +72,10 @@ public class AStarPathFinder extends AbstractNodeCostSearch implements Helper { ChunkProviderClient chunkProvider = Minecraft.getMinecraft().world.getChunkProvider(); long startTime = System.nanoTime() / 1000000L; boolean slowPath = Baritone.settings().slowPath.get(); - long timeoutTime = startTime + (slowPath ? Baritone.settings().slowPathTimeoutMS : Baritone.settings().pathTimeoutMS).get(); + if (slowPath) { + displayChatMessageRaw("slowPath is on, path timeout will be " + Baritone.settings().slowPathTimeoutMS.get() + "ms instead of " + timeout + "ms"); + } + long timeoutTime = startTime + (slowPath ? Baritone.settings().slowPathTimeoutMS.get() : timeout); //long lastPrintout = 0; int numNodes = 0; int numMovementsConsidered = 0; @@ -120,10 +123,6 @@ public class AStarPathFinder extends AbstractNodeCostSearch implements Helper { mostRecentConsidered = currentNode; BetterBlockPos currentNodePos = currentNode.pos; numNodes++; - /*if ((lastPrintout + 1000) - System.nanoTime() / 1000000L < 0) {//print once a second - System.out.println("searching... at " + currentNodePos + ", considered " + numNodes + " nodes so far"); - lastPrintout = System.nanoTime() / 1000000L; - }*/ if (goal.isInGoal(currentNodePos)) { currentlyRunning = null; displayChatMessageRaw("Took " + (System.nanoTime() / 1000000L - startTime) + "ms, " + numMovementsConsidered + " movements considered"); @@ -137,7 +136,6 @@ public class AStarPathFinder extends AbstractNodeCostSearch implements Helper { long constructEnd = System.nanoTime(); construction += constructEnd - constructStart; constructionCount++; - //System.out.println(constructEnd - constructStart); for (Movement movementToGetToNeighbor : possibleMovements) { if (movementToGetToNeighbor == null) { continue; @@ -159,7 +157,6 @@ public class AStarPathFinder extends AbstractNodeCostSearch implements Helper { long costStart = System.nanoTime(); chunk += costStart - s; chunkCount++; - //long costStart = System.nanoTime(); // TODO cache cost int numLookupsBefore = BlockStateInterface.numBlockStateLookups; double actionCost = movementToGetToNeighbor.getCost(calcContext); @@ -167,7 +164,6 @@ public class AStarPathFinder extends AbstractNodeCostSearch implements Helper { stateLookup.put(movementToGetToNeighbor.getClass(), BlockStateInterface.numBlockStateLookups - numLookupsBefore + stateLookup.getOrDefault(movementToGetToNeighbor.getClass(), 0)); timeConsumed.put(movementToGetToNeighbor.getClass(), costEnd - costStart + timeConsumed.getOrDefault(movementToGetToNeighbor.getClass(), 0L)); count.put(movementToGetToNeighbor.getClass(), 1 + count.getOrDefault(movementToGetToNeighbor.getClass(), 0)); - //System.out.println(movementToGetToNeighbor.getClass() + "" + (costEnd - costStart)); numMovementsConsidered++; if (actionCost >= ActionCosts.COST_INF) { continue; @@ -215,6 +211,9 @@ public class AStarPathFinder extends AbstractNodeCostSearch implements Helper { for (int i = 0; i < bestSoFar.length; i++) { double heuristic = neighbor.estimatedCostToGoal + neighbor.cost / COEFFICIENTS[i]; if (heuristic < bestHeuristicSoFar[i]) { + if (bestHeuristicSoFar[i] - heuristic < 0.01 && minimumImprovementRepropagation) { + continue; + } bestHeuristicSoFar[i] = heuristic; bestSoFar[i] = neighbor; } @@ -268,7 +267,7 @@ public class AStarPathFinder extends AbstractNodeCostSearch implements Helper { return Optional.of(new Path(startNode, bestSoFar[i], numNodes)); } } - displayChatMessageRaw("Even with a cost coefficient of " + COEFFICIENTS[COEFFICIENTS.length - 1] + ", I couldn't get more than " + bestDist + " blocks"); + displayChatMessageRaw("Even with a cost coefficient of " + COEFFICIENTS[COEFFICIENTS.length - 1] + ", I couldn't get more than " + Math.sqrt(bestDist) + " blocks"); displayChatMessageRaw("No path found =("); currentlyRunning = null; return Optional.empty(); diff --git a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java index b8f13f1e..5804cb1a 100644 --- a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java +++ b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java @@ -17,6 +17,7 @@ package baritone.pathing.calc; +import baritone.behavior.impl.PathingBehavior; import baritone.pathing.goals.Goal; import baritone.pathing.path.IPath; import baritone.utils.pathing.BetterBlockPos; @@ -75,17 +76,27 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { cancelRequested = true; } - public synchronized Optional calculate() { + public synchronized Optional calculate(long timeout) { if (isFinished) { throw new IllegalStateException("Path Finder is currently in use, and cannot be reused!"); } this.cancelRequested = false; - Optional path = calculate0(); - isFinished = true; - return path; + try { + Optional path = calculate0(timeout); + isFinished = true; + return path; + } catch (Exception e) { + currentlyRunning = null; + isFinished = true; + if (e instanceof RuntimeException) { + throw (RuntimeException) e; + } else { + throw new RuntimeException(e); + } + } } - protected abstract Optional calculate0(); + protected abstract Optional calculate0(long timeout); /** * Determines the distance squared from the specified node to the start @@ -121,6 +132,11 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { return node; } + public static void forceCancel() { + PathingBehavior.INSTANCE.cancel(); + currentlyRunning = null; + } + @Override public Optional pathToMostRecentNodeConsidered() { return Optional.ofNullable(mostRecentConsidered).map(node -> new Path(startNode, node, 0)); diff --git a/src/main/java/baritone/pathing/calc/IPathFinder.java b/src/main/java/baritone/pathing/calc/IPathFinder.java index bbcc7bda..dceee65d 100644 --- a/src/main/java/baritone/pathing/calc/IPathFinder.java +++ b/src/main/java/baritone/pathing/calc/IPathFinder.java @@ -39,7 +39,7 @@ public interface IPathFinder { * * @return The final path */ - Optional calculate(); + Optional calculate(long timeout); /** * Intended to be called concurrently with calculatePath from a different thread to tell if it's finished yet diff --git a/src/main/java/baritone/pathing/goals/GoalGetToBlock.java b/src/main/java/baritone/pathing/goals/GoalGetToBlock.java index 9c847918..ed927a12 100644 --- a/src/main/java/baritone/pathing/goals/GoalGetToBlock.java +++ b/src/main/java/baritone/pathing/goals/GoalGetToBlock.java @@ -17,32 +17,47 @@ package baritone.pathing.goals; -import net.minecraft.util.EnumFacing; +import baritone.utils.pathing.BetterBlockPos; import net.minecraft.util.math.BlockPos; + /** * Don't get into the block, but get directly adjacent to it. Useful for chests. * * @author avecowa */ -public class GoalGetToBlock extends GoalComposite { +public class GoalGetToBlock implements Goal { - private final BlockPos pos; + private final int x; + private final int y; + private final int z; public GoalGetToBlock(BlockPos pos) { - super(adjacentBlocks(pos)); - this.pos = pos; - } - - private static BlockPos[] adjacentBlocks(BlockPos pos) { - BlockPos[] sides = new BlockPos[6]; - for (int i = 0; i < 6; i++) { - sides[i] = pos.offset(EnumFacing.values()[i]); - } - return sides; + this.x = pos.getX(); + this.y = pos.getY(); + this.z = pos.getZ(); } public BlockPos getGoalPos() { - return pos; + return new BetterBlockPos(x, y, z); + } + + @Override + public boolean isInGoal(BlockPos pos) { + int xDiff = pos.getX() - this.x; + int yDiff = pos.getY() - this.y; + int zDiff = pos.getZ() - this.z; + if (yDiff == -2 && xDiff == 0 && zDiff == 0) { + return true; + } + return Math.abs(xDiff) + Math.abs(yDiff) + Math.abs(zDiff) <= 1; + } + + @Override + public double heuristic(BlockPos pos) { + int xDiff = pos.getX() - this.x; + int yDiff = pos.getY() - this.y; + int zDiff = pos.getZ() - this.z; + return GoalBlock.calculate(xDiff, yDiff, zDiff); } } diff --git a/src/main/java/baritone/pathing/goals/GoalNear.java b/src/main/java/baritone/pathing/goals/GoalNear.java index d19fadf8..2ec6bf1d 100644 --- a/src/main/java/baritone/pathing/goals/GoalNear.java +++ b/src/main/java/baritone/pathing/goals/GoalNear.java @@ -51,4 +51,14 @@ public class GoalNear implements Goal { public BlockPos getGoalPos() { return new BlockPos(x, y, z); } + + @Override + public String toString() { + return "GoalNear{" + + "x=" + x + + ", y=" + y + + ", z=" + z + + ", rangeSq=" + rangeSq + + '}'; + } } diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index 44c9d5a3..9d2f5869 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -21,13 +21,7 @@ import baritone.Baritone; import baritone.behavior.impl.LookBehavior; import baritone.behavior.impl.LookBehaviorUtils; import baritone.pathing.movement.MovementState.MovementStatus; -import baritone.pathing.movement.movements.MovementDownward; -import baritone.pathing.movement.movements.MovementPillar; -import baritone.pathing.movement.movements.MovementTraverse; import baritone.utils.*; -import net.minecraft.block.Block; -import net.minecraft.block.BlockLadder; -import net.minecraft.block.BlockVine; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; @@ -78,21 +72,11 @@ public abstract class Movement implements Helper, MovementHelper { if (cost == null) { if (context == null) context = new CalculationContext(); - cost = calculateCost0(context); + cost = calculateCost(context); } return cost; } - private double calculateCost0(CalculationContext context) { - if (!(this instanceof MovementPillar) && !(this instanceof MovementTraverse) && !(this instanceof MovementDownward)) { - Block fromDown = BlockStateInterface.get(src.down()).getBlock(); - if (fromDown instanceof BlockLadder || fromDown instanceof BlockVine) { - return COST_INF; - } - } - return calculateCost(context); - } - protected abstract double calculateCost(CalculationContext context); public double recalculateCost() { @@ -100,6 +84,10 @@ public abstract class Movement implements Helper, MovementHelper { return getCost(null); } + public double calculateCostWithoutCaching() { + return calculateCost(new CalculationContext()); + } + /** * Handles the execution of the latest Movement * State, and offers a Status to the calling class. diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 142f5d98..82b20c41 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -186,6 +186,9 @@ public interface MovementHelper extends ActionCosts, Helper { */ static boolean canWalkOn(BlockPos pos, IBlockState state) { Block block = state.getBlock(); + if (block == Blocks.AIR) { + return false; + } if (block instanceof BlockLadder || (Baritone.settings().allowVines.get() && block instanceof BlockVine)) { // TODO reconsider this return true; } @@ -195,17 +198,30 @@ public interface MovementHelper extends ActionCosts, Helper { if (Blocks.FARMLAND.equals(block) || Blocks.GRASS_PATH.equals(block)) { return true; } - if (block instanceof BlockAir) { - return false; + if (Blocks.ENDER_CHEST.equals(block) || Blocks.CHEST.equals(block)) { + return true; + } + if (block instanceof BlockSlab) { + if (!Baritone.settings().allowWalkOnBottomSlab.get()) { + if (((BlockSlab) block).isDouble()) { + return true; + } + return state.getValue(BlockSlab.HALF) != BlockSlab.EnumBlockHalf.BOTTOM; + } + return true; + } + if (block instanceof BlockStairs) { + return true; } if (BlockStateInterface.isWater(block)) { - if (BlockStateInterface.isFlowing(state)) { - return false; - } Block up = BlockStateInterface.get(pos.up()).getBlock(); if (up instanceof BlockLilyPad) { return true; } + if (BlockStateInterface.isFlowing(state)) { + // the only scenario in which we can walk on flowing water is if it's under still water with jesus off + return BlockStateInterface.isWater(up) && !Baritone.settings().assumeWalkOnWater.get(); + } // if assumeWalkOnWater is on, we can only walk on water if there isn't water above it // if assumeWalkOnWater is off, we can only walk on water if there is water above it return BlockStateInterface.isWater(up) ^ Baritone.settings().assumeWalkOnWater.get(); @@ -258,6 +274,16 @@ public interface MovementHelper extends ActionCosts, Helper { return 0; // we won't actually mine it, so don't check fallings above } + static boolean isBottomSlab(IBlockState state) { + return state.getBlock() instanceof BlockSlab + && !((BlockSlab) state.getBlock()).isDouble() + && state.getValue(BlockSlab.HALF) == BlockSlab.EnumBlockHalf.BOTTOM; + } + + static boolean isBottomSlab(BlockPos pos) { + return isBottomSlab(BlockStateInterface.get(pos)); + } + /** * The entity the player is currently looking at * diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index af29a887..d666ff6a 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -53,7 +53,18 @@ public class MovementAscend extends Movement { @Override protected double calculateCost(CalculationContext context) { + IBlockState srcDown = BlockStateInterface.get(src.down()); + if (srcDown.getBlock() == Blocks.LADDER || srcDown.getBlock() == Blocks.VINE) { + return COST_INF; + } + // we can jump from soul sand, but not from a bottom slab + boolean jumpingFromBottomSlab = MovementHelper.isBottomSlab(srcDown); IBlockState toPlace = BlockStateInterface.get(positionToPlace); + boolean jumpingToBottomSlab = MovementHelper.isBottomSlab(toPlace); + + if (jumpingFromBottomSlab && !jumpingToBottomSlab) { + return COST_INF;// the only thing we can ascend onto from a bottom slab is another bottom slab + } if (!MovementHelper.canWalkOn(positionToPlace, toPlace)) { if (!context.hasThrowaway()) { return COST_INF; @@ -96,9 +107,11 @@ public class MovementAscend extends Movement { // it's possible srcUp is AIR from the start, and srcUp2 is falling // and in that scenario, when we arrive and break srcUp2, that lets srcUp3 fall on us and suffocate us } - // TODO maybe change behavior if src.down() is soul sand? double walk = WALK_ONE_BLOCK_COST; - if (toPlace.getBlock().equals(Blocks.SOUL_SAND)) { + if (jumpingToBottomSlab && !jumpingFromBottomSlab) { + return walk + getTotalHardnessOfBlocksToBreak(context); // we don't hit space we just walk into the slab + } + if (!jumpingToBottomSlab && toPlace.getBlock().equals(Blocks.SOUL_SAND)) { walk *= WALK_ONE_OVER_SOUL_SAND_COST / WALK_ONE_BLOCK_COST; } // we hit space immediately on entering this action @@ -123,7 +136,8 @@ public class MovementAscend extends Movement { return state.setStatus(MovementStatus.SUCCESS); } - if (!MovementHelper.canWalkOn(positionToPlace)) { + IBlockState jumpingOnto = BlockStateInterface.get(positionToPlace); + if (!MovementHelper.canWalkOn(positionToPlace, jumpingOnto)) { for (int i = 0; i < 4; i++) { BlockPos anAgainst = positionToPlace.offset(HORIZONTALS[i]); if (anAgainst.equals(src)) { @@ -150,6 +164,8 @@ public class MovementAscend extends Movement { // After 20 ticks without placement, we might be standing in the way, move back state.setInput(InputOverrideHandler.Input.MOVE_BACK, true); } + } else { + state.setInput(InputOverrideHandler.Input.CLICK_LEFT, true); // break whatever replaceable block is in the way } System.out.println("Trying to look at " + anAgainst + ", actually looking at" + selectedBlock); }); @@ -159,6 +175,11 @@ public class MovementAscend extends Movement { return state.setStatus(MovementStatus.UNREACHABLE); } MovementHelper.moveTowards(state, dest); + if (MovementHelper.isBottomSlab(jumpingOnto)) { + if (!MovementHelper.isBottomSlab(src.down())) { + return state; // don't jump while walking from a non double slab into a bottom slab + } + } if (headBonkClear()) { return state.setInput(InputOverrideHandler.Input.JUMP, true); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java index 7a07abb1..8ab66af1 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java @@ -25,8 +25,6 @@ import baritone.pathing.movement.MovementState.MovementStatus; import baritone.utils.BlockStateInterface; import baritone.utils.InputOverrideHandler; import net.minecraft.block.Block; -import net.minecraft.block.BlockLadder; -import net.minecraft.block.BlockVine; import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; @@ -44,18 +42,22 @@ public class MovementDescend extends Movement { @Override protected double calculateCost(CalculationContext context) { + Block fromDown = BlockStateInterface.get(src.down()).getBlock(); + if (fromDown == Blocks.LADDER || fromDown == Blocks.VINE) { + return COST_INF; + } if (!MovementHelper.canWalkOn(positionToPlace)) { return COST_INF; } Block tmp1 = BlockStateInterface.get(dest).getBlock(); - if (tmp1 instanceof BlockLadder || tmp1 instanceof BlockVine) { + if (tmp1 == Blocks.LADDER || tmp1 == Blocks.VINE) { return COST_INF; } // we walk half the block plus 0.3 to get to the edge, then we walk the other 0.2 while simultaneously falling (math.max because of how it's in parallel) double walk = WALK_OFF_BLOCK_COST; - if (BlockStateInterface.get(src.down()).getBlock().equals(Blocks.SOUL_SAND)) { + if (fromDown == Blocks.SOUL_SAND) { // use this ratio to apply the soul sand speed penalty to our 0.8 block distance - walk *= WALK_ONE_OVER_SOUL_SAND_COST / WALK_ONE_BLOCK_COST; + walk = WALK_ONE_OVER_SOUL_SAND_COST; } return walk + Math.max(FALL_N_BLOCKS_COST[1], CENTER_AFTER_FALL_COST) + getTotalHardnessOfBlocksToBreak(context); } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java index 1ce5537f..2bf8bdf1 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java @@ -75,6 +75,10 @@ public class MovementDiagonal extends Movement { @Override protected double calculateCost(CalculationContext context) { + Block fromDown = BlockStateInterface.get(src.down()).getBlock(); + if (fromDown == Blocks.LADDER || fromDown == Blocks.VINE) { + return COST_INF; + } if (!MovementHelper.canWalkThrough(positionsToBreak[4]) || !MovementHelper.canWalkThrough(positionsToBreak[5])) { return COST_INF; } @@ -88,7 +92,7 @@ public class MovementDiagonal extends Movement { if (destWalkOn.getBlock().equals(Blocks.SOUL_SAND)) { multiplier += (WALK_ONE_OVER_SOUL_SAND_COST - WALK_ONE_BLOCK_COST) / 2; } - if (BlockStateInterface.get(src.down()).getBlock().equals(Blocks.SOUL_SAND)) { + if (fromDown == Blocks.SOUL_SAND) { multiplier += (WALK_ONE_OVER_SOUL_SAND_COST - WALK_ONE_BLOCK_COST) / 2; } Block cuttingOver1 = BlockStateInterface.get(positionsToBreak[2].down()).getBlock(); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDownward.java b/src/main/java/baritone/pathing/movement/movements/MovementDownward.java index ece2c8f5..13555399 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDownward.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDownward.java @@ -23,9 +23,8 @@ import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; import baritone.utils.BlockStateInterface; import net.minecraft.block.Block; -import net.minecraft.block.BlockLadder; -import net.minecraft.block.BlockVine; import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; public class MovementDownward extends Movement { @@ -49,7 +48,7 @@ public class MovementDownward extends Movement { } IBlockState d = BlockStateInterface.get(dest); Block td = d.getBlock(); - boolean ladder = td instanceof BlockLadder || td instanceof BlockVine; + boolean ladder = td == Blocks.LADDER || td == Blocks.VINE; if (ladder) { return LADDER_DOWN_ONE_COST; } else { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementFall.java b/src/main/java/baritone/pathing/movement/movements/MovementFall.java index ee019c98..40ff97f5 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementFall.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementFall.java @@ -25,7 +25,11 @@ import baritone.pathing.movement.MovementState; import baritone.pathing.movement.MovementState.MovementStatus; import baritone.pathing.movement.MovementState.MovementTarget; import baritone.utils.*; +import net.minecraft.block.Block; import net.minecraft.block.BlockFalling; +import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; @@ -43,9 +47,17 @@ public class MovementFall extends Movement { @Override protected double calculateCost(CalculationContext context) { - if (!MovementHelper.canWalkOn(dest.down())) { + Block fromDown = BlockStateInterface.get(src.down()).getBlock(); + if (fromDown == Blocks.LADDER || fromDown == Blocks.VINE) { return COST_INF; } + IBlockState fallOnto = BlockStateInterface.get(dest.down()); + if (!MovementHelper.canWalkOn(dest.down(), fallOnto)) { + return COST_INF; + } + if (MovementHelper.isBottomSlab(fallOnto)) { + return COST_INF; // falling onto a half slab is really glitchy, and can cause more fall damage than we'd expect + } double placeBucketCost = 0.0; if (!BlockStateInterface.isWater(dest) && src.getY() - dest.getY() > context.maxFallHeightNoWater()) { if (!context.hasWaterBucket()) { @@ -96,7 +108,7 @@ public class MovementFall extends Movement { BlockPos playerFeet = playerFeet(); Rotation targetRotation = null; if (!BlockStateInterface.isWater(dest) && src.getY() - dest.getY() > Baritone.settings().maxFallHeightNoWater.get() && !playerFeet.equals(dest)) { - if (!player().inventory.hasItemStack(STACK_BUCKET_WATER) || world().provider.isNether()) { + if (!InventoryPlayer.isHotbar(player().inventory.getSlotFor(STACK_BUCKET_WATER)) || world().provider.isNether()) { state.setStatus(MovementStatus.UNREACHABLE); return state; } @@ -119,7 +131,7 @@ public class MovementFall extends Movement { } if (playerFeet.equals(dest) && (player().posY - playerFeet.getY() < 0.094 // lilypads || BlockStateInterface.isWater(dest))) { - if (BlockStateInterface.isWater(dest) && player().inventory.hasItemStack(STACK_BUCKET_EMPTY)) { + if (BlockStateInterface.isWater(dest) && InventoryPlayer.isHotbar(player().inventory.getSlotFor(STACK_BUCKET_EMPTY))) { player().inventory.currentItem = player().inventory.getSlotFor(STACK_BUCKET_EMPTY); if (player().motionY >= 0) { return state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index d7ff3016..481553fa 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -47,11 +47,16 @@ public class MovementPillar extends Movement { protected double calculateCost(CalculationContext context) { Block fromDown = BlockStateInterface.get(src).getBlock(); boolean ladder = fromDown instanceof BlockLadder || fromDown instanceof BlockVine; - Block fromDownDown = BlockStateInterface.get(src.down()).getBlock(); + IBlockState fromDownDown = BlockStateInterface.get(src.down()); if (!ladder) { - if (fromDownDown instanceof BlockLadder || fromDownDown instanceof BlockVine) { + if (fromDownDown.getBlock() instanceof BlockLadder || fromDownDown.getBlock() instanceof BlockVine) { return COST_INF; } + if (fromDownDown.getBlock() instanceof BlockSlab) { + 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 + } + } } if (!context.hasThrowaway() && !ladder) { return COST_INF; @@ -87,7 +92,7 @@ public class MovementPillar extends Movement { //} } } - if (fromDown instanceof BlockLiquid || fromDownDown instanceof BlockLiquid) {//can't pillar on water or in water + if (fromDown instanceof BlockLiquid || fromDownDown.getBlock() instanceof BlockLiquid) {//can't pillar on water or in water return COST_INF; } if (ladder) { @@ -142,9 +147,12 @@ public class MovementPillar extends Movement { return state.setStatus(MovementState.MovementStatus.UNREACHABLE); } - if (playerFeet().equals(against.up()) || playerFeet().equals(dest)) + if (playerFeet().equals(against.up()) || playerFeet().equals(dest)) { return state.setStatus(MovementState.MovementStatus.SUCCESS); - + } + if (MovementHelper.isBottomSlab(src.down())) { + state.setInput(InputOverrideHandler.Input.JUMP, true); + } /* if (thePlayer.getPosition0().getX() != from.getX() || thePlayer.getPosition0().getZ() != from.getZ()) { Baritone.moveTowardsBlock(from); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index b1eac4e9..af0b7b27 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -85,7 +85,7 @@ public class MovementTraverse extends Movement { return WC + hardness1 + hardness2; } else {//this is a bridge, so we need to place a block Block srcDown = BlockStateInterface.get(src.down()).getBlock(); - if (srcDown instanceof BlockLadder || srcDown instanceof BlockVine) { + if (srcDown == Blocks.LADDER || srcDown == Blocks.VINE) { return COST_INF; } if (destOn.getBlock().equals(Blocks.AIR) || MovementHelper.isReplacable(positionToPlace, destOn)) { @@ -107,8 +107,8 @@ public class MovementTraverse extends Movement { return WC + context.placeBlockCost() + getTotalHardnessOfBlocksToBreak(context); } } - if (Blocks.SOUL_SAND.equals(srcDown)) { - return COST_INF; // can't sneak and backplace against soul sand =/ + if (srcDown == Blocks.SOUL_SAND || (srcDown instanceof BlockSlab && !((BlockSlab) srcDown).isDouble())) { + return COST_INF; // can't sneak and backplace against soul sand or half slabs =/ } WC = WC * SNEAK_ONE_BLOCK_COST / WALK_ONE_BLOCK_COST;//since we are placing, we are sneaking return WC + context.placeBlockCost() + getTotalHardnessOfBlocksToBreak(context); @@ -206,6 +206,17 @@ public class MovementTraverse extends Movement { return state.setStatus(MovementState.MovementStatus.UNREACHABLE); } state.setInput(InputOverrideHandler.Input.SNEAK, true); + Block standingOn = BlockStateInterface.get(playerFeet().down()).getBlock(); + if (standingOn.equals(Blocks.SOUL_SAND) || standingOn instanceof BlockSlab) { // see issue #118 + double dist = Math.max(Math.abs(dest.getX() + 0.5 - player().posX), Math.abs(dest.getZ() + 0.5 - player().posZ)); + if (dist < 0.85) { // 0.5 + 0.3 + epsilon + MovementHelper.moveTowards(state, dest); + state.setInput(InputOverrideHandler.Input.MOVE_FORWARD, false); + state.setInput(InputOverrideHandler.Input.MOVE_BACK, true); + return state; + } + } + state.setInput(InputOverrideHandler.Input.MOVE_BACK, false); double faceX = (dest.getX() + against1.getX() + 1.0D) * 0.5D; double faceY = (dest.getY() + against1.getY()) * 0.5D; double faceZ = (dest.getZ() + against1.getZ() + 1.0D) * 0.5D; @@ -245,7 +256,7 @@ public class MovementTraverse extends Movement { return state; } // Out.log("Trying to look at " + goalLook + ", actually looking at" + Baritone.whatAreYouLookingAt()); - return state; + return state.setInput(InputOverrideHandler.Input.CLICK_LEFT, true); } else { MovementHelper.moveTowards(state, positionsToBreak[0]); return state; diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 76fcc3c1..818f9bbb 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -19,12 +19,10 @@ package baritone.pathing.path; import baritone.Baritone; import baritone.api.event.events.TickEvent; -import baritone.pathing.movement.ActionCosts; -import baritone.pathing.movement.Movement; -import baritone.pathing.movement.MovementHelper; -import baritone.pathing.movement.MovementState; +import baritone.pathing.movement.*; import baritone.pathing.movement.movements.MovementDescend; import baritone.pathing.movement.movements.MovementDiagonal; +import baritone.pathing.movement.movements.MovementFall; import baritone.pathing.movement.movements.MovementTraverse; import baritone.utils.BlockStateInterface; import baritone.utils.Helper; @@ -46,6 +44,7 @@ import static baritone.pathing.movement.MovementState.MovementStatus.*; * @author leijurv */ public class PathExecutor implements Helper { + private static final double MAX_MAX_DIST_FROM_PATH = 3; private static final double MAX_DIST_FROM_PATH = 2; private static final double MAX_TICKS_AWAY = 200; // ten seconds. ok to decrease this, but it must be at least 110, see issue #102 private final IPath path; @@ -132,6 +131,17 @@ public class PathExecutor implements Helper { } else { ticksAway = 0; } + if (distanceFromPath > MAX_MAX_DIST_FROM_PATH) { + if (!(path.movements().get(pathPosition) instanceof MovementFall)) { // might be midair + if (pathPosition == 0 || !(path.movements().get(pathPosition - 1) instanceof MovementFall)) { // might have overshot the landing + displayChatMessageRaw("too far from path"); + pathPosition = path.length() + 3; + Baritone.INSTANCE.getInputOverrideHandler().clearAllKeys(); + failed = true; + return false; + } + } + } //this commented block is literally cursed. /*Out.log(actions.get(pathPosition)); if (pathPosition < actions.size() - 1) {//if there are two ActionBridges in a row and they are at right angles, walk diagonally. This makes it so you walk at 45 degrees along a zigzag path instead of doing inefficient zigging and zagging @@ -204,19 +214,12 @@ public class PathExecutor implements Helper { //displayChatMessageRaw("Recalculating break and place took " + (end - start) + "ms"); } Movement movement = path.movements().get(pathPosition); - double currentCost = movement.recalculateCost(); - if (currentCost >= ActionCosts.COST_INF) { - displayChatMessageRaw("Something has changed in the world and this movement has become impossible. Cancelling."); - pathPosition = path.length() + 3; - failed = true; - Baritone.INSTANCE.getInputOverrideHandler().clearAllKeys(); - return true; - } if (costEstimateIndex == null || costEstimateIndex != pathPosition) { costEstimateIndex = pathPosition; - currentMovementInitialCostEstimate = currentCost; // do this only once, when the movement starts + // do this only once, when the movement starts, and deliberately get the cost as cached when this path was calculated, not the cost as it is right now + currentMovementInitialCostEstimate = movement.getCost(null); for (int i = 1; i < Baritone.settings().costVerificationLookahead.get() && pathPosition + i < path.length() - 1; i++) { - if (path.movements().get(pathPosition + i).recalculateCost() >= ActionCosts.COST_INF) { + if (path.movements().get(pathPosition + i).calculateCostWithoutCaching() >= ActionCosts.COST_INF) { displayChatMessageRaw("Something has changed in the world and a future movement has become impossible. Cancelling."); pathPosition = path.length() + 3; failed = true; @@ -225,6 +228,14 @@ public class PathExecutor implements Helper { } } } + double currentCost = movement.recalculateCost(); + if (currentCost >= ActionCosts.COST_INF) { + displayChatMessageRaw("Something has changed in the world and this movement has become impossible. Cancelling."); + pathPosition = path.length() + 3; + failed = true; + Baritone.INSTANCE.getInputOverrideHandler().clearAllKeys(); + return true; + } MovementState.MovementStatus movementStatus = movement.update(); if (movementStatus == UNREACHABLE || movementStatus == FAILED) { displayChatMessageRaw("Movement returns status " + movementStatus); @@ -260,7 +271,7 @@ public class PathExecutor implements Helper { } private void sprintIfRequested() { - if (!Baritone.settings().allowSprint.get()) { + if (!new CalculationContext().canSprint()) { player().setSprinting(false); return; } diff --git a/src/main/java/baritone/utils/BlockStateInterface.java b/src/main/java/baritone/utils/BlockStateInterface.java index 5e562033..d436c4c7 100644 --- a/src/main/java/baritone/utils/BlockStateInterface.java +++ b/src/main/java/baritone/utils/BlockStateInterface.java @@ -69,6 +69,10 @@ public class BlockStateInterface implements Helper { return Blocks.AIR.getDefaultState(); } + public static void clearCachedChunk() { + prev = null; + } + public static Block getBlock(BlockPos pos) { return get(pos).getBlock(); } diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 542ea323..16dabf4f 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -28,6 +28,7 @@ import baritone.chunk.ChunkPacker; import baritone.chunk.Waypoint; import baritone.chunk.WorldProvider; import baritone.pathing.calc.AStarPathFinder; +import baritone.pathing.calc.AbstractNodeCostSearch; import baritone.pathing.goals.*; import baritone.pathing.movement.ActionCosts; import baritone.pathing.movement.CalculationContext; @@ -54,7 +55,9 @@ public class ExampleBaritoneControl extends Behavior { @Override public void onSendChatMessage(ChatEvent event) { if (!Baritone.settings().chatControl.get()) { - return; + if (!Baritone.settings().removePrefix.get()) { + return; + } } String msg = event.getMessage(); if (Baritone.settings().prefix.get()) { @@ -115,6 +118,12 @@ public class ExampleBaritoneControl extends Behavior { displayChatMessageRaw("ok canceled"); return; } + if (msg.toLowerCase().equals("forcecancel")) { + AbstractNodeCostSearch.forceCancel(); + event.cancel(); + displayChatMessageRaw("ok force canceled"); + return; + } if (msg.toLowerCase().equals("invert")) { Goal goal = PathingBehavior.INSTANCE.getGoal(); BlockPos runAwayFrom; @@ -177,9 +186,16 @@ public class ExampleBaritoneControl extends Behavior { return; } if (msg.toLowerCase().startsWith("mine")) { - String blockType = msg.toLowerCase().substring(4).trim(); - MineBehavior.INSTANCE.mine(blockType); - displayChatMessageRaw("Started mining blocks of type" + blockType); + String[] blockTypes = msg.toLowerCase().substring(4).trim().split(" "); + for (String s : blockTypes) { + if (ChunkPacker.stringToBlock(s) == null) { + displayChatMessageRaw(s + " isn't a valid block name"); + event.cancel(); + return; + } + } + MineBehavior.INSTANCE.mine(blockTypes); + displayChatMessageRaw("Started mining blocks of type " + Arrays.toString(blockTypes)); event.cancel(); return; } @@ -215,14 +231,26 @@ public class ExampleBaritoneControl extends Behavior { } if (msg.toLowerCase().startsWith("goto")) { String waypointType = msg.toLowerCase().substring(4).trim(); - if (waypointType.endsWith("s")) { + if (waypointType.endsWith("s") && Waypoint.Tag.fromString(waypointType.substring(0, waypointType.length() - 1)) != null) { // for example, "show deaths" waypointType = waypointType.substring(0, waypointType.length() - 1); } Waypoint.Tag tag = Waypoint.Tag.fromString(waypointType); if (tag == null) { - displayChatMessageRaw("Not a valid tag. Tags are: " + Arrays.asList(Waypoint.Tag.values()).toString().toLowerCase()); + String mining = waypointType; + //displayChatMessageRaw("Not a valid tag. Tags are: " + Arrays.asList(Waypoint.Tag.values()).toString().toLowerCase()); event.cancel(); + if (ChunkPacker.stringToBlock(mining) == null) { + displayChatMessageRaw("No locations for " + mining + " known, cancelling"); + return; + } + List locs = MineBehavior.scanFor(Arrays.asList(mining), 64); + if (locs.isEmpty()) { + displayChatMessageRaw("No locations for " + mining + " known, cancelling"); + return; + } + PathingBehavior.INSTANCE.setGoal(new GoalComposite(locs.stream().map(GoalGetToBlock::new).toArray(Goal[]::new))); + PathingBehavior.INSTANCE.path(); return; } Waypoint waypoint = WorldProvider.INSTANCE.getCurrentWorld().waypoints.getMostRecentByTag(tag); diff --git a/src/main/java/baritone/utils/Helper.java b/src/main/java/baritone/utils/Helper.java index c973b1ca..383e7bf0 100755 --- a/src/main/java/baritone/utils/Helper.java +++ b/src/main/java/baritone/utils/Helper.java @@ -18,6 +18,7 @@ package baritone.utils; import baritone.Baritone; +import net.minecraft.block.BlockSlab; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.multiplayer.WorldClient; @@ -33,7 +34,13 @@ import net.minecraft.util.text.TextFormatting; */ public interface Helper { - ITextComponent MESSAGE_PREFIX = new TextComponentString("§5[§dBaritone§5]§7"); + ITextComponent MESSAGE_PREFIX = new TextComponentString(String.format( + "%s[%sBaritone%s]%s", + TextFormatting.DARK_PURPLE, + TextFormatting.LIGHT_PURPLE, + TextFormatting.DARK_PURPLE, + TextFormatting.GRAY + )); Minecraft mc = Minecraft.getMinecraft(); @@ -47,10 +54,11 @@ public interface Helper { default BlockPos playerFeet() { // TODO find a better way to deal with soul sand!!!!! - return new BlockPos(player().posX, player().posY + 0.1251, player().posZ); - /*if (BlockStateInterface.get(feet).getBlock().equals(Blocks.SOUL_SAND) && player().posY > feet.getY() + 0.874999) { + BlockPos feet = new BlockPos(player().posX, player().posY + 0.1251, player().posZ); + if (BlockStateInterface.get(feet).getBlock() instanceof BlockSlab) { return feet.up(); - }*/ + } + return feet; } default Vec3d playerFeetAsVec() { diff --git a/src/main/java/baritone/utils/RayTraceUtils.java b/src/main/java/baritone/utils/RayTraceUtils.java index f6547454..123e283d 100644 --- a/src/main/java/baritone/utils/RayTraceUtils.java +++ b/src/main/java/baritone/utils/RayTraceUtils.java @@ -18,6 +18,9 @@ package baritone.utils; import net.minecraft.util.math.RayTraceResult; +import net.minecraft.util.math.Vec3d; + +import static baritone.behavior.impl.LookBehaviorUtils.calcVec3dFromRotation; /** * @author Brady @@ -44,4 +47,16 @@ public final class RayTraceUtils implements Helper { return result; } + + public static RayTraceResult rayTraceTowards(Rotation rotation) { + double blockReachDistance = mc.playerController.getBlockReachDistance(); + Vec3d start = mc.player.getPositionEyes(1.0F); + Vec3d direction = calcVec3dFromRotation(rotation); + Vec3d end = start.add( + direction.x * blockReachDistance, + direction.y * blockReachDistance, + direction.z * blockReachDistance + ); + return mc.world.rayTraceBlocks(start, end, false, false, true); + } } diff --git a/src/main/java/baritone/utils/ToolSet.java b/src/main/java/baritone/utils/ToolSet.java index 415d8ebd..e8243ba6 100644 --- a/src/main/java/baritone/utils/ToolSet.java +++ b/src/main/java/baritone/utils/ToolSet.java @@ -17,7 +17,6 @@ package baritone.utils; -import baritone.Baritone; import baritone.api.event.events.ItemSlotEvent; import baritone.api.event.listener.AbstractGameEventListener; import net.minecraft.block.Block; @@ -46,11 +45,7 @@ public class ToolSet implements Helper { /** * Instance of the internal event listener used to hook into Baritone's event bus */ - private static final InternalEventListener INTERNAL_EVENT_LISTENER = new InternalEventListener(); - - static { - Baritone.INSTANCE.getGameEventHandler().registerEventListener(INTERNAL_EVENT_LISTENER); - } + public static final InternalEventListener INTERNAL_EVENT_LISTENER = new InternalEventListener(); /** * A list of tools on the hotbar that should be considered. @@ -72,10 +67,10 @@ public class ToolSet implements Helper { private Map slotCache = new HashMap<>(); /** - * A cache mapping a {@link IBlockState} to how long it will take to break + * A cache mapping a {@link Block} to how long it will take to break * with this toolset, given the optimum tool is used. */ - private Map breakStrengthCache = new HashMap<>(); + private Map breakStrengthCache = new HashMap<>(); /** * Create a toolset from the current player's inventory (but don't calculate any hardness values just yet) @@ -146,7 +141,7 @@ public class ToolSet implements Helper { * @return how long it would take in ticks */ public double getStrVsBlock(IBlockState state, BlockPos pos) { - return this.breakStrengthCache.computeIfAbsent(state, s -> calculateStrVsBlock(s, pos)); + return this.breakStrengthCache.computeIfAbsent(state.getBlock(), b -> calculateStrVsBlock(state, pos)); } /** diff --git a/src/main/java/baritone/launch/mixins/accessor/IAnvilChunkLoader.java b/src/main/java/baritone/utils/accessor/IAnvilChunkLoader.java similarity index 74% rename from src/main/java/baritone/launch/mixins/accessor/IAnvilChunkLoader.java rename to src/main/java/baritone/utils/accessor/IAnvilChunkLoader.java index 3972ff32..900e3fb4 100644 --- a/src/main/java/baritone/launch/mixins/accessor/IAnvilChunkLoader.java +++ b/src/main/java/baritone/utils/accessor/IAnvilChunkLoader.java @@ -15,11 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.launch.mixins.accessor; - -import net.minecraft.world.chunk.storage.AnvilChunkLoader; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; +package baritone.utils.accessor; import java.io.File; @@ -27,8 +23,7 @@ import java.io.File; * @author Brady * @since 8/4/2018 11:36 AM */ -@Mixin(AnvilChunkLoader.class) public interface IAnvilChunkLoader { - @Accessor File getChunkSaveLocation(); + File getChunkSaveLocation(); } diff --git a/src/main/java/baritone/launch/mixins/accessor/IChunkProviderServer.java b/src/main/java/baritone/utils/accessor/IChunkProviderServer.java similarity index 76% rename from src/main/java/baritone/launch/mixins/accessor/IChunkProviderServer.java rename to src/main/java/baritone/utils/accessor/IChunkProviderServer.java index 460014fc..bb3dcb5e 100644 --- a/src/main/java/baritone/launch/mixins/accessor/IChunkProviderServer.java +++ b/src/main/java/baritone/utils/accessor/IChunkProviderServer.java @@ -15,19 +15,15 @@ * along with Baritone. If not, see . */ -package baritone.launch.mixins.accessor; +package baritone.utils.accessor; import net.minecraft.world.chunk.storage.IChunkLoader; -import net.minecraft.world.gen.ChunkProviderServer; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; /** * @author Brady * @since 8/4/2018 11:33 AM */ -@Mixin(ChunkProviderServer.class) public interface IChunkProviderServer { - @Accessor IChunkLoader getChunkLoader(); + IChunkLoader getChunkLoader(); } diff --git a/src/main/java/baritone/utils/pathing/BetterBlockPos.java b/src/main/java/baritone/utils/pathing/BetterBlockPos.java index 6e4fc599..ec8891f4 100644 --- a/src/main/java/baritone/utils/pathing/BetterBlockPos.java +++ b/src/main/java/baritone/utils/pathing/BetterBlockPos.java @@ -26,7 +26,7 @@ import net.minecraft.util.math.Vec3i; * * @author leijurv */ -public class BetterBlockPos extends BlockPos { +public final class BetterBlockPos extends BlockPos { public final int x; public final int y; public final int z; diff --git a/src/main/resources/mixins.baritone.json b/src/main/resources/mixins.baritone.json index c0b5d3bb..989c9355 100755 --- a/src/main/resources/mixins.baritone.json +++ b/src/main/resources/mixins.baritone.json @@ -8,7 +8,9 @@ "maxShiftBy": 2 }, "client": [ + "MixinAnvilChunkLoader", "MixinBlockPos", + "MixinChunkProviderServer", "MixinEntity", "MixinEntityPlayerSP", "MixinEntityRenderer", @@ -20,9 +22,6 @@ "MixinMinecraft", "MixinNetHandlerPlayClient", "MixinNetworkManager", - "MixinWorldClient", - - "accessor.IAnvilChunkLoader", - "accessor.IChunkProviderServer" + "MixinWorldClient" ] } \ No newline at end of file diff --git a/src/test/java/baritone/pathing/goals/GoalGetToBlockTest.java b/src/test/java/baritone/pathing/goals/GoalGetToBlockTest.java new file mode 100644 index 00000000..3c3905aa --- /dev/null +++ b/src/test/java/baritone/pathing/goals/GoalGetToBlockTest.java @@ -0,0 +1,49 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Baritone. If not, see . + */ + +package baritone.pathing.goals; + +import net.minecraft.util.math.BlockPos; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertTrue; + +public class GoalGetToBlockTest { + + @Test + public void isInGoal() { + List acceptableOffsets = new ArrayList<>(Arrays.asList("0,0,0", "0,0,1", "0,0,-1", "1,0,0", "-1,0,0", "0,1,0", "0,-1,0", "0,-2,0")); + for (int x = -10; x <= 10; x++) { + for (int y = -10; y <= 10; y++) { + for (int z = -10; z <= 10; z++) { + boolean inGoal = new GoalGetToBlock(new BlockPos(0, 0, 0)).isInGoal(new BlockPos(x, y, z)); + String repr = x + "," + y + "," + z; + System.out.println(repr + " " + inGoal); + if (inGoal) { + assertTrue(repr, acceptableOffsets.contains(repr)); + acceptableOffsets.remove(repr); + } + } + } + } + assertTrue(acceptableOffsets.toString(), acceptableOffsets.isEmpty()); + } +} \ No newline at end of file