Compare commits

..

1 Commits

Author SHA1 Message Date
Leijurv
21b0f74a76 spaghetti to export list of canWalkThrough and canWalkOn 2018-08-17 14:12:35 -07:00
157 changed files with 8197 additions and 7027 deletions

43
.circleci/config.yml Normal file
View File

@@ -0,0 +1,43 @@
# 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

View File

@@ -1 +0,0 @@
language: java

View File

@@ -1,49 +0,0 @@
# 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. <a href="https://www.youtube.com/watch?v=dyfYKSubhdc">Example</a>
- **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. <a href="https://www.youtube.com/watch?v=F6FbI1L9UmU">Example</a>
- **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.
- **Parkour** Sprint jumping over 1, 2, or 3 block gaps
# 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 <a href="https://docs.google.com/document/d/1WVHHXKXFdCR1Oz__KtK8sFqyvSwJN_H4lftkHFgmzlc/edit">write-up</a> 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. <a href="https://www.youtube.com/watch?v=CGiMcb8-99Y">Example</a>
# Configuring Baritone
All the settings and documentation are <a href="https://github.com/cabaletta/baritone/blob/master/src/main/java/baritone/Settings.java">here</a>.
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
- Parkour (jumping over gaps of any length) [IN PROGRESS]
See <a href="https://github.com/cabaletta/baritone/issues">issues</a> for more.
Things it may not ever have, from most likely to least likely =(
- Pigs
- Boats
- Horses (2x3 path instead of 1x2)
- Elytra

View File

@@ -1,16 +0,0 @@
# 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 <a href="https://www.dropbox.com/s/imc6xwwpwsh3i0y/baritone-1.0.0.jar?dl=0">here</a>
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.

View File

@@ -1,57 +1,3 @@
# 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.
<a href="https://github.com/cabaletta/baritone/blob/master/FEATURES.md">Features</a>
<a href="https://github.com/cabaletta/baritone/blob/master/IMPACT.md">Baritone + Impact</a>
# Setup
- Open the project in IntelliJ as a Gradle project
- Run the Gradle task `setupDecompWorkspace`
- Run the Gradle task `genIntellijRuns`
- Refresh the Gradle project (or just restart IntelliJ)
- Select the "Minecraft Client" launch config and run
## Command Line
On Mac OSX and Linux, use `./gradlew` instead of `gradlew`.
Running Baritone:
```
$ gradlew run
```
Setting up for IntelliJ:
```
$ gradlew setupDecompWorkspace
$ gradlew --refresh-dependencies
$ gradlew genIntellijRuns
```
# Chat control
<a href="https://github.com/cabaletta/baritone/blob/master/src/main/java/baritone/utils/ExampleBaritoneControl.java">Defined here</a>
Quick start example: `thisway 1000` or `goal 70` to set the goal, `path` to actually start pathing. Also try `mine diamond_ore`. `cancel` to cancel.
# API example
```
Baritone.settings().allowSprint.value = true;
Baritone.settings().pathTimeoutMS.value = 2000L;
PathingBehavior.INSTANCE.setGoal(new GoalXZ(10000, 20000));
PathingBehavior.INSTANCE.path();
```
# FAQ
## Can I use Baritone as a library in my hacked client?
Sure! (As long as usage is in compliance with the GPL 3 License)
## How is it so fast?
Magic
the original version of the bot for Minecraft 1.8, rebuilt for 1.12.2.

View File

@@ -16,7 +16,7 @@
*/
group 'baritone'
version '1.0.0'
version '1.0'
buildscript {
repositories {
@@ -38,19 +38,14 @@ buildscript {
}
apply plugin: 'java'
apply plugin: 'net.minecraftforge.gradle.tweaker-client'
apply plugin: 'org.spongepowered.mixin'
sourceCompatibility = targetCompatibility = '1.8'
compileJava {
sourceCompatibility = targetCompatibility = '1.8'
}
sourceSets {
launch {
compileClasspath += main.compileClasspath + main.runtimeClasspath + main.output
}
}
apply plugin: 'net.minecraftforge.gradle.tweaker-client'
apply plugin: 'org.spongepowered.mixin'
minecraft {
version = '1.12.2'
@@ -70,7 +65,7 @@ repositories {
}
dependencies {
runtime launchCompile('org.spongepowered:mixin:0.7.11-SNAPSHOT') {
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'
@@ -80,12 +75,3 @@ dependencies {
}
testImplementation 'junit:junit:4.12'
}
mixin {
defaultObfuscationEnv notch
add sourceSets.launch, 'mixins.baritone.refmap.json'
}
jar {
from sourceSets.launch.output
}

369
proguard.pro vendored
View File

@@ -1,369 +0,0 @@
-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 <fields>;
}
# 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 <methods>;
}
# 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);
}

View File

@@ -1,58 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 <https://www.gnu.org/licenses/>.
*/
/*
* 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 <https://www.gnu.org/licenses/>.
*/
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;
}
}

View File

@@ -1,57 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 <https://www.gnu.org/licenses/>.
*/
/*
* 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 <https://www.gnu.org/licenses/>.
*/
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;
}
}

View File

@@ -1,56 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 <https://www.gnu.org/licenses/>.
*/
package baritone.launch.mixins;
import baritone.Baritone;
import baritone.api.event.events.RelativeMoveEvent;
import baritone.api.event.events.type.EventState;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
/**
* @author Brady
* @since 8/21/2018
*/
@Mixin(Entity.class)
public class MixinEntity {
@Inject(
method = "moveRelative",
at = @At("HEAD")
)
private void preMoveRelative(float strafe, float up, float forward, float friction, CallbackInfo ci) {
Entity _this = (Entity) (Object) this;
if (_this == Minecraft.getMinecraft().player)
Baritone.INSTANCE.getGameEventHandler().onPlayerRelativeMove(new RelativeMoveEvent(EventState.PRE));
}
@Inject(
method = "moveRelative",
at = @At("RETURN")
)
private void postMoveRelative(float strafe, float up, float forward, float friction, CallbackInfo ci) {
Entity _this = (Entity) (Object) this;
if (_this == Minecraft.getMinecraft().player)
Baritone.INSTANCE.getGameEventHandler().onPlayerRelativeMove(new RelativeMoveEvent(EventState.POST));
}
}

View File

@@ -1,372 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 <https://www.gnu.org/licenses/>.
*/
package baritone;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import java.lang.reflect.Field;
import java.util.*;
/**
* Baritone's settings
*
* @author leijurv
*/
public class Settings {
/**
* Allow Baritone to break blocks
*/
public Setting<Boolean> allowBreak = new Setting<>(true);
/**
* Allow Baritone to sprint
*/
public Setting<Boolean> allowSprint = new Setting<>(true);
/**
* Allow Baritone to place blocks
*/
public Setting<Boolean> allowPlace = new Setting<>(true);
/**
* It doesn't actually take twenty ticks to place a block, this cost is so high
* because we want to generally conserve blocks which might be limited
*/
public Setting<Double> blockPlacementPenalty = new Setting<>(20D);
/**
* Allow Baritone to fall arbitrary distances and place a water bucket beneath it.
* Reliability: questionable.
*/
public Setting<Boolean> allowWaterBucketFall = new Setting<>(true);
/**
* Allow Baritone to assume it can walk on still water just like any other block.
* This functionality is assumed to be provided by a separate library that might have imported Baritone.
*/
public Setting<Boolean> assumeWalkOnWater = new Setting<>(false);
/**
* Blocks that Baritone is allowed to place (as throwaway, for sneak bridging, pillaring, etc.)
*/
public Setting<List<Item>> acceptableThrowawayItems = new Setting<>(new ArrayList<>(Arrays.asList(
Item.getItemFromBlock(Blocks.DIRT),
Item.getItemFromBlock(Blocks.COBBLESTONE),
Item.getItemFromBlock(Blocks.NETHERRACK)
)));
/**
* Enables some more advanced vine features. They're honestly just gimmicks and won't ever be needed in real
* pathing scenarios. And they can cause Baritone to get trapped indefinitely in a strange scenario.
*/
public Setting<Boolean> 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<Boolean> allowWalkOnBottomSlab = new Setting<>(true);
/**
* You know what it is
* <p>
* But it's very unreliable and falls off when cornering like all the time so.
*/
public Setting<Boolean> allowParkour = new Setting<>(false);
/**
* For example, if you have Mining Fatigue or Haste, adjust the costs of breaking blocks accordingly.
*/
public Setting<Boolean> considerPotionEffects = 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.
* 3.5 is always an underestimate, even if you are sprinting.
* If you're walking only (with allowSprint off) 4.6 is safe.
* Any value below 3.5 is never worth it. It's just more computation to find the same path, guaranteed.
* (specifically, it needs to be strictly slightly less than ActionCosts.WALK_ONE_BLOCK_COST, which is about 3.56)
* <p>
* Setting it at 3.57 or above with sprinting, or to 4.64 or above without sprinting, will result in
* faster computation, at the cost of a suboptimal path. Any value above the walk / sprint cost will result
* in it going straight at its goal, and not investigating alternatives, because the combined cost / heuristic
* metric gets better and better with each block, instead of slightly worse.
* <p>
* Finding the optimal path is worth it, so it's the default.
*/
public Setting<Double> costHeuristic = this.new <Double>Setting<Double>(3.5D);
// a bunch of obscure internal A* settings that you probably don't want to change
/**
* The maximum number of times it will fetch outside loaded or cached chunks before assuming that
* pathing has reached the end of the known area, and should therefore stop.
*/
public Setting<Integer> pathingMaxChunkBorderFetch = new Setting<>(50);
/**
* See issue #18
* Set to 1.0 to effectively disable this feature
*/
public Setting<Double> backtrackCostFavoringCoefficient = new Setting<>(0.9);
/**
* Don't repropagate cost improvements below 0.01 ticks. They're all just floating point inaccuracies,
* and there's no point.
*/
public Setting<Boolean> minimumImprovementRepropagation = new Setting<>(true);
/**
* Use a pythagorean metric (as opposed to the more accurate hybrid diagonal / traverse).
* You probably don't want this. It roughly triples nodes considered for no real advantage.
*/
public Setting<Boolean> pythagoreanMetric = new Setting<>(false);
/**
* 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<Boolean> cutoffAtLoadBoundary = new Setting<>(false);
/**
* Stop 5 movements before anything that made the path COST_INF.
* For example, if lava has spread across the path, don't walk right up to it then recalculate, it might
* still be spreading lol
*/
public Setting<Integer> costVerificationLookahead = new Setting<>(5);
/**
* Static cutoff factor. 0.9 means cut off the last 10% of all paths, regardless of chunk load state
*/
public Setting<Double> pathCutoffFactor = new Setting<>(0.9);
/**
* Only apply static cutoff for paths of at least this length (in terms of number of movements)
*/
public Setting<Integer> pathCutoffMinimumLength = new Setting<>(30);
/**
* Start planning the next path once the remaining movements tick estimates sum up to less than this value
*/
public Setting<Integer> planningTickLookAhead = new Setting<>(100);
/**
* How far are you allowed to fall onto solid ground (without a water bucket)?
* 3 won't deal any damage. But if you just want to get down the mountain quickly and you have
* Feather Falling IV, you might set it a bit higher, like 4 or 5.
*/
public Setting<Integer> maxFallHeightNoWater = new Setting<>(3);
/**
* How far are you allowed to fall onto solid ground (with a water bucket)?
* It's not that reliable, so I've set it below what would kill an unarmored player (23)
*/
public Setting<Integer> maxFallHeightBucket = new Setting<>(20);
/**
* Is it okay to sprint through a descend followed by a diagonal?
* The player overshoots the landing, but not enough to fall off. And the diagonal ensures that there isn't
* lava or anything that's !canWalkInto in that space, so it's technically safe, just a little sketchy.
*/
public Setting<Boolean> allowOvershootDiagonalDescend = new Setting<>(true);
/**
* If your goal is a GoalBlock in an unloaded chunk, assume it's far enough away that the Y coord
* doesn't matter yet, and replace it with a GoalXZ to the same place before calculating a path.
* Once a segment ends within chunk load range of the GoalBlock, it will go back to normal behavior
* of considering the Y coord. The reasoning is that if your X and Z are 10,000 blocks away,
* your Y coordinate's accuracy doesn't matter at all until you get much much closer.
*/
public Setting<Boolean> simplifyUnloadedYCoord = new Setting<>(true);
/**
* If a movement takes this many ticks more than its initial cost estimate, cancel it
*/
public Setting<Integer> movementTimeoutTicks = new Setting<>(100);
/**
* Pathing can never take longer than this
*/
public Setting<Number> pathTimeoutMS = new Setting<>(2000L);
/**
* Planning ahead while executing a segment can never take longer than this
*/
public Setting<Number> planAheadTimeoutMS = new Setting<>(4000L);
/**
* For debugging, consider nodes much much slower
*/
public Setting<Boolean> slowPath = new Setting<>(false);
/**
* Milliseconds between each node
*/
public Setting<Number> slowPathTimeDelayMS = new Setting<>(100L);
/**
* The alternative timeout number when slowPath is on
*/
public Setting<Number> slowPathTimeoutMS = new Setting<>(40000L);
/**
* The big one. Download all chunks in simplified 2-bit format and save them for better very-long-distance pathing.
*/
public Setting<Boolean> chunkCaching = new Setting<>(true);
/**
* Print all the debug messages to chat
*/
public Setting<Boolean> chatDebug = new Setting<>(true);
/**
* Allow chat based control of Baritone. Most likely should be disabled when Baritone is imported for use in
* something else
*/
public Setting<Boolean> chatControl = new Setting<>(true);
/**
* A second override over chatControl to force it on
*/
public Setting<Boolean> removePrefix = new Setting<>(false);
/**
* Render the path
*/
public Setting<Boolean> renderPath = new Setting<>(true);
/**
* Render the goal
*/
public Setting<Boolean> renderGoal = new Setting<>(true);
/**
* Line width of the path when rendered, in pixels
*/
public Setting<Float> pathRenderLineWidthPixels = new Setting<>(5F);
/**
* Line width of the goal when rendered, in pixels
*/
public Setting<Float> goalRenderLineWidthPixels = new Setting<>(3F);
/**
* Start fading out the path at 20 movements ahead, and stop rendering it entirely 30 movements ahead.
* Improves FPS.
*/
public Setting<Boolean> fadePath = new Setting<>(false);
/**
* Move without having to force the client-sided rotations
*/
public Setting<Boolean> freeLook = new Setting<>(true);
/**
* Will cause some minor behavioral differences to ensure that Baritone works on anticheats.
* <p>
* At the moment this will silently set the player's rotations when using freeLook so you're not sprinting in
* directions other than forward, which is picken up by more "advanced" anticheats like AAC, but not NCP.
*/
public Setting<Boolean> antiCheatCompatibility = new Setting<>(true);
/**
* Exclusively use cached chunks for pathing
*/
public Setting<Boolean> pathThroughCachedOnly = new Setting<>(false);
/**
* Whether or not to use the "#" command prefix
*/
public Setting<Boolean> prefix = new Setting<>(false);
public final Map<String, Setting<?>> byLowerName;
public final List<Setting<?>> allSettings;
public class Setting<T> {
public T value;
private String name;
private final Class<T> klass;
@SuppressWarnings("unchecked")
private Setting(T value) {
if (value == null) {
throw new IllegalArgumentException("Cannot determine value type class from null");
}
this.value = value;
this.klass = (Class<T>) value.getClass();
}
@SuppressWarnings("unchecked")
public final <K extends T> K get() {
return (K) value;
}
public final String getName() {
return name;
}
public Class<T> getValueClass() {
return klass;
}
public String toString() {
return name + ": " + value;
}
}
// here be dragons
{
Field[] temp = getClass().getFields();
HashMap<String, Setting<?>> tmpByName = new HashMap<>();
List<Setting<?>> tmpAll = new ArrayList<>();
try {
for (Field field : temp) {
if (field.getType().equals(Setting.class)) {
Setting<?> setting = (Setting<?>) field.get(this);
String name = field.getName();
setting.name = name;
name = name.toLowerCase();
if (tmpByName.containsKey(name)) {
throw new IllegalStateException("Duplicate setting name");
}
tmpByName.put(name, setting);
tmpAll.add(setting);
}
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
byLowerName = Collections.unmodifiableMap(tmpByName);
allSettings = Collections.unmodifiableList(tmpAll);
}
@SuppressWarnings("unchecked")
public <T> List<Setting<T>> getAllValuesByType(Class<T> klass) {
List<Setting<T>> result = new ArrayList<>();
for (Setting<?> setting : allSettings) {
if (setting.getValueClass().equals(klass)) {
result.add((Setting<T>) setting);
}
}
return result;
}
Settings() { }
}

View File

@@ -1,235 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 <https://www.gnu.org/licenses/>.
*/
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package baritone.api.event;
import baritone.Baritone;
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;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.world.chunk.Chunk;
import org.lwjgl.input.Keyboard;
import java.util.ArrayList;
/**
* @author Brady
* @since 7/31/2018 11:04 PM
*/
public final class GameEventHandler implements IGameEventListener, Helper {
private final ArrayList<IGameEventListener> listeners = new ArrayList<>();
@Override
public final void onTick(TickEvent event) {
listeners.forEach(l -> {
if (canDispatch(l)) {
l.onTick(event);
}
});
}
@Override
public final void onPlayerUpdate(PlayerUpdateEvent event) {
listeners.forEach(l -> {
if (canDispatch(l)) {
l.onPlayerUpdate(event);
}
});
}
@Override
public final void onProcessKeyBinds() {
InputOverrideHandler inputHandler = Baritone.INSTANCE.getInputOverrideHandler();
// Simulate the key being held down this tick
for (InputOverrideHandler.Input input : InputOverrideHandler.Input.values()) {
KeyBinding keyBinding = input.getKeyBinding();
if (inputHandler.isInputForcedDown(keyBinding) && !keyBinding.isKeyDown()) {
int keyCode = keyBinding.getKeyCode();
if (keyCode < Keyboard.KEYBOARD_SIZE) {
KeyBinding.onTick(keyCode < 0 ? keyCode + 100 : keyCode);
}
}
}
listeners.forEach(l -> {
if (canDispatch(l)) {
l.onProcessKeyBinds();
}
});
}
@Override
public final void onSendChatMessage(ChatEvent event) {
listeners.forEach(l -> {
if (canDispatch(l)) {
l.onSendChatMessage(event);
}
});
}
@Override
public final void onChunkEvent(ChunkEvent event) {
EventState state = event.getState();
ChunkEvent.Type type = event.getType();
boolean isPostPopulate = state == EventState.POST
&& type == ChunkEvent.Type.POPULATE;
// Whenever the server sends us to another dimension, chunks are unloaded
// technically after the new world has been loaded, so we perform a check
// to make sure the chunk being unloaded is already loaded.
boolean isPreUnload = state == EventState.PRE
&& type == ChunkEvent.Type.UNLOAD
&& mc.world.getChunkProvider().isChunkGeneratedAt(event.getX(), event.getZ());
if (isPostPopulate || isPreUnload) {
WorldProvider.INSTANCE.ifWorldLoaded(world -> {
Chunk chunk = mc.world.getChunk(event.getX(), event.getZ());
world.cache.queueForPacking(chunk);
});
}
listeners.forEach(l -> {
if (canDispatch(l)) {
l.onChunkEvent(event);
}
});
}
@Override
public final void onRenderPass(RenderEvent event) {
listeners.forEach(l -> {
if (canDispatch(l)) {
l.onRenderPass(event);
}
});
}
@Override
public final void onWorldEvent(WorldEvent event) {
WorldProvider cache = WorldProvider.INSTANCE;
BlockStateInterface.clearCachedChunk();
switch (event.getState()) {
case PRE:
break;
case POST:
cache.closeWorld();
if (event.getWorld() != null) {
cache.initWorld(event.getWorld());
}
break;
}
listeners.forEach(l -> {
if (canDispatch(l)) {
l.onWorldEvent(event);
}
});
}
@Override
public final void onSendPacket(PacketEvent event) {
listeners.forEach(l -> {
if (canDispatch(l)) {
l.onSendPacket(event);
}
});
}
@Override
public final void onReceivePacket(PacketEvent event) {
listeners.forEach(l -> {
if (canDispatch(l)) {
l.onReceivePacket(event);
}
});
}
@Override
public void onPlayerRelativeMove(RelativeMoveEvent event) {
listeners.forEach(l -> {
if (canDispatch(l)) {
l.onPlayerRelativeMove(event);
}
});
}
@Override
public void onBlockInteract(BlockInteractEvent event) {
listeners.forEach(l -> {
if (canDispatch(l)) {
l.onBlockInteract(event);
}
});
}
@Override
public void onPlayerDeath() {
listeners.forEach(l -> {
if (canDispatch(l)) {
l.onPlayerDeath();
}
});
}
@Override
public void onPathEvent(PathEvent event) {
listeners.forEach(l -> {
if (canDispatch(l)) {
l.onPathEvent(event);
}
});
}
public final void registerEventListener(IGameEventListener listener) {
this.listeners.add(listener);
}
private boolean canDispatch(IGameEventListener listener) {
return !(listener instanceof Toggleable) || ((Toggleable) listener).isEnabled();
}
}

View File

@@ -1,69 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 <https://www.gnu.org/licenses/>.
*/
package baritone.api.event.events;
import net.minecraft.util.math.BlockPos;
/**
* @author Brady
* @since 8/22/2018
*/
public final class BlockInteractEvent {
/**
* The position of the block interacted with
*/
private final BlockPos pos;
/**
* The type of interaction that occurred
*/
private final Type type;
public BlockInteractEvent(BlockPos pos, Type type) {
this.pos = pos;
this.type = type;
}
/**
* @return The position of the block interacted with
*/
public final BlockPos getPos() {
return this.pos;
}
/**
* @return The type of interaction with the target block
*/
public final Type getType() {
return this.type;
}
public enum Type {
/**
* We're breaking the target block.
*/
BREAK,
/**
* We're right clicking on the target block. Either placing or interacting with.
*/
USE
}
}

View File

@@ -1,56 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 <https://www.gnu.org/licenses/>.
*/
package baritone.api.event.events;
import baritone.api.event.listener.IGameEventListener;
/**
* Called in some cases where a player's inventory has it's current slot queried.
* <p>
* @see IGameEventListener#onQueryItemSlotForBlocks()
*
* @author Brady
* @since 8/20/2018
*/
public final class ItemSlotEvent {
/**
* The current slot index
*/
private int slot;
public ItemSlotEvent(int slot) {
this.slot = slot;
}
/**
* Sets the new slot index that will be used
*
* @param slot The slot index
*/
public final void setSlot(int slot) {
this.slot = slot;
}
/**
* @return The current slot index
*/
public final int getSlot() {
return this.slot;
}
}

View File

@@ -1,32 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 <https://www.gnu.org/licenses/>.
*/
package baritone.api.event.events;
public enum PathEvent {
CALC_STARTED,
CALC_FINISHED_NOW_EXECUTING,
CALC_FAILED,
NEXT_SEGMENT_CALC_STARTED,
NEXT_SEGMENT_CALC_FINISHED,
CONTINUING_ONTO_PLANNED_NEXT,
SPLICING_ONTO_NEXT_EARLY,
AT_GOAL,
PATH_FINISHED_NEXT_STILL_CALCULATING,
NEXT_CALC_FAILED,
DISCARD_NEXT
}

View File

@@ -1,43 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 <https://www.gnu.org/licenses/>.
*/
package baritone.api.event.events;
import baritone.api.event.events.type.EventState;
/**
* @author Brady
* @since 8/21/2018
*/
public final class RelativeMoveEvent {
/**
* The state of the event
*/
private final EventState state;
public RelativeMoveEvent(EventState state) {
this.state = state;
}
/**
* @return The state of the event
*/
public final EventState getState() {
return this.state;
}
}

View File

@@ -1,60 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 <https://www.gnu.org/licenses/>.
*/
package baritone.behavior.impl;
import baritone.api.event.events.TickEvent;
import baritone.behavior.Behavior;
import baritone.pathing.goals.GoalNear;
import net.minecraft.entity.Entity;
import net.minecraft.util.math.BlockPos;
/**
* Follow an entity
*
* @author leijurv
*/
public class FollowBehavior extends Behavior {
public static final FollowBehavior INSTANCE = new FollowBehavior();
private FollowBehavior() {
}
Entity following;
@Override
public void onTick(TickEvent event) {
if (event.getType() == TickEvent.Type.OUT) {
return;
}
if (following == null) {
return;
}
// lol this is trashy but it works
PathingBehavior.INSTANCE.setGoal(new GoalNear(new BlockPos(following), 3));
PathingBehavior.INSTANCE.path();
}
public void follow(Entity follow) {
this.following = follow;
}
public void cancel() {
PathingBehavior.INSTANCE.cancel();
follow(null);
}
}

View File

@@ -1,53 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 <https://www.gnu.org/licenses/>.
*/
package baritone.behavior.impl;
import baritone.behavior.Behavior;
import baritone.chunk.Waypoint;
import baritone.chunk.WorldProvider;
import baritone.api.event.events.BlockInteractEvent;
import baritone.utils.BlockStateInterface;
import net.minecraft.block.BlockBed;
/**
* A collection of event methods that are used to interact with Baritone's
* waypoint system. This class probably needs a better name.
*
* @see Waypoint
*
* @author Brady
* @since 8/22/2018
*/
public final class LocationTrackingBehavior extends Behavior {
public static final LocationTrackingBehavior INSTANCE = new LocationTrackingBehavior();
private LocationTrackingBehavior() {}
@Override
public void onBlockInteract(BlockInteractEvent event) {
if (event.getType() == BlockInteractEvent.Type.USE && BlockStateInterface.getBlock(event.getPos()) instanceof BlockBed) {
WorldProvider.INSTANCE.getCurrentWorld().waypoints.addWaypoint(new Waypoint("bed", Waypoint.Tag.BED, event.getPos()));
}
}
@Override
public void onPlayerDeath() {
WorldProvider.INSTANCE.getCurrentWorld().waypoints.addWaypoint(new Waypoint("death", Waypoint.Tag.DEATH, playerFeet()));
}
}

View File

@@ -1,121 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 <https://www.gnu.org/licenses/>.
*/
package baritone.behavior.impl;
import baritone.Baritone;
import baritone.Settings;
import baritone.api.event.events.PlayerUpdateEvent;
import baritone.api.event.events.RelativeMoveEvent;
import baritone.behavior.Behavior;
import baritone.utils.Rotation;
public class LookBehavior extends Behavior {
public static final LookBehavior INSTANCE = new LookBehavior();
private LookBehavior() {}
/**
* Target's values are as follows:
* <p>
* getFirst() -> yaw
* getSecond() -> pitch
*/
private Rotation target;
/**
* Whether or not rotations are currently being forced
*/
private boolean force;
/**
* The last player yaw angle. Used when free looking
*
* @see Settings#freeLook
*/
private float lastYaw;
public void updateTarget(Rotation target, boolean force) {
this.target = target;
this.force = force || !Baritone.settings().freeLook.get();
}
@Override
public void onPlayerUpdate(PlayerUpdateEvent event) {
if (this.target == null) {
return;
}
// Whether or not we're going to silently set our angles
boolean silent = Baritone.settings().antiCheatCompatibility.get();
switch (event.getState()) {
case PRE: {
if (this.force) {
player().rotationYaw = this.target.getFirst();
float oldPitch = player().rotationPitch;
float desiredPitch = this.target.getSecond();
player().rotationPitch = desiredPitch;
if (desiredPitch == oldPitch) {
nudgeToLevel();
}
this.target = null;
} else if (silent) {
this.lastYaw = player().rotationYaw;
player().rotationYaw = this.target.getFirst();
}
break;
}
case POST: {
if (!this.force && silent) {
player().rotationYaw = this.lastYaw;
this.target = null;
}
break;
}
}
}
@Override
public void onPlayerRelativeMove(RelativeMoveEvent event) {
if (this.target != null && !this.force) {
switch (event.getState()) {
case PRE:
this.lastYaw = player().rotationYaw;
player().rotationYaw = this.target.getFirst();
break;
case POST:
player().rotationYaw = this.lastYaw;
// If we have antiCheatCompatibility on, we're going to use the target value later in onPlayerUpdate()
if (!Baritone.settings().antiCheatCompatibility.get()) {
this.target = null;
}
break;
}
}
}
private void nudgeToLevel() {
if (player().rotationPitch < -20) {
player().rotationPitch++;
} else if (player().rotationPitch > 10) {
player().rotationPitch--;
}
}
}

View File

@@ -1,111 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 <https://www.gnu.org/licenses/>.
*/
package baritone.behavior.impl;
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;
import baritone.utils.BlockStateInterface;
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;
/**
* Mine blocks of a certain type
*
* @author leijurv
*/
public class MineBehavior extends Behavior {
public static final MineBehavior INSTANCE = new MineBehavior();
private MineBehavior() {
}
List<String> mining;
@Override
public void onPathEvent(PathEvent event) {
updateGoal();
}
public void updateGoal() {
if (mining == null) {
return;
}
List<BlockPos> locs = scanFor(mining, 64);
if (locs.isEmpty()) {
displayChatMessageRaw("No locations for " + mining + " known, cancelling");
cancel();
return;
}
PathingBehavior.INSTANCE.setGoal(new GoalComposite(locs.stream().map(GoalTwoBlocks::new).toArray(Goal[]::new)));
PathingBehavior.INSTANCE.path();
}
public static List<BlockPos> scanFor(List<String> mining, int max) {
List<BlockPos> locs = new ArrayList<>();
List<String> 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();
}
}

View File

@@ -15,20 +15,22 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone;
package baritone.bot;
import baritone.api.event.GameEventHandler;
import baritone.behavior.Behavior;
import baritone.behavior.impl.*;
import baritone.utils.InputOverrideHandler;
import net.minecraft.client.Minecraft;
import baritone.bot.behavior.Behavior;
import baritone.bot.behavior.impl.LookBehavior;
import baritone.bot.behavior.impl.MemoryBehavior;
import baritone.bot.behavior.impl.PathingBehavior;
import baritone.bot.event.GameEventHandler;
import baritone.bot.pathing.movement.MovementHelper;
import baritone.bot.utils.InputOverrideHandler;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
/**
* @author Brady
@@ -50,22 +52,12 @@ public enum Baritone {
private InputOverrideHandler inputOverrideHandler;
private Settings settings;
private List<Behavior> behaviors;
private File dir;
/**
* List of consumers to be called after Baritone has initialized
*/
private List<Consumer<Baritone>> onInitConsumers;
/**
* Whether or not Baritone is active
*/
private boolean active;
Baritone() {
this.onInitConsumers = new ArrayList<>();
}
public synchronized void init() {
if (initialized) {
return;
@@ -74,25 +66,46 @@ public enum Baritone {
this.inputOverrideHandler = new InputOverrideHandler();
this.settings = new Settings();
this.behaviors = new ArrayList<>();
{
registerBehavior(PathingBehavior.INSTANCE);
registerBehavior(LookBehavior.INSTANCE);
registerBehavior(MemoryBehavior.INSTANCE);
registerBehavior(LocationTrackingBehavior.INSTANCE);
registerBehavior(FollowBehavior.INSTANCE);
registerBehavior(MineBehavior.INSTANCE);
}
this.dir = new File(Minecraft.getMinecraft().gameDir, "baritone");
if (!Files.exists(dir.toPath())) {
try {
Files.createDirectories(dir.toPath());
} catch (IOException ignored) {}
}
behaviors.add(PathingBehavior.INSTANCE);
behaviors.add(LookBehavior.INSTANCE);
behaviors.add(MemoryBehavior.INSTANCE);
this.active = true;
this.initialized = true;
Field[] temp = Blocks.class.getFields();
try {
for (Field field : temp) {
if (field.getType().equals(Block.class)) {
Block block = (Block) field.get(null);
System.out.print(block);
IBlockState state = block.getDefaultState();
System.out.print(',');
try {
if (MovementHelper.canWalkThrough(null, state)) {
System.out.print("true");
} else {
System.out.print("false");
}
} catch (Exception e) {
System.out.print("unknown");
}
System.out.print(',');
try {
if (MovementHelper.canWalkOn(null, state)) {
System.out.print("true");
} else {
System.out.print("false");
}
} catch (Exception e) {
System.out.print("unknown");
}
this.onInitConsumers.forEach(consumer -> consumer.accept(this));
System.out.println();
}
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public final boolean isInitialized() {
@@ -113,7 +126,6 @@ public enum Baritone {
public void registerBehavior(Behavior behavior) {
this.behaviors.add(behavior);
this.gameEventHandler.registerEventListener(behavior);
}
public final boolean isActive() {
@@ -127,12 +139,4 @@ public enum Baritone {
public static Settings settings() {
return Baritone.INSTANCE.settings; // yolo
}
public final File getDir() {
return this.dir;
}
public final void registerInitListener(Consumer<Baritone> runnable) {
this.onInitConsumers.add(runnable);
}
}

View File

@@ -0,0 +1,133 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package baritone.bot;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import java.lang.reflect.Field;
import java.util.*;
/**
* Baritone's settings
*
* @author leijurv
*/
public class Settings {
public Setting<Boolean> allowBreak = new Setting<>(true);
public Setting<Boolean> allowPlaceThrowaway = new Setting<>(true);
/**
* It doesn't actually take twenty ticks to place a block, this cost is so high
* because we want to generally conserve blocks which might be limited
*/
public Setting<Double> blockPlacementPenalty = new Setting<>(20D);
public Setting<Boolean> allowSprint = new Setting<>(true);
public Setting<Double> costHeuristic = new <Double>Setting<Double>(4D);
public Setting<Boolean> chuckCaching = new Setting<>(false);
public Setting<Boolean> allowWaterBucketFall = new Setting<>(true);
public Setting<Integer> planningTickLookAhead = new Setting<>(150);
public Setting<Boolean> chatDebug = new Setting<>(true);
public Setting<Boolean> chatControl = new Setting<>(true); // probably false in impact
public Setting<Boolean> renderPath = new Setting<>(true);
public Setting<Boolean> fadePath = new Setting<>(false); // give this a better name in the UI, like "better path fps" idk
public Setting<Number> pathTimeoutMS = new Setting<>(4000L);
public Setting<Boolean> slowPath = new Setting<>(false);
public Setting<Number> slowPathTimeDelayMS = new Setting<>(100L);
public Setting<Number> slowPathTimeoutMS = new Setting<>(40000L);
public Setting<List<Item>> acceptableThrowawayItems = new Setting<>(Arrays.asList(
Item.getItemFromBlock(Blocks.DIRT),
Item.getItemFromBlock(Blocks.COBBLESTONE),
Item.getItemFromBlock(Blocks.NETHERRACK)
));
public Setting<Boolean> renderGoal = new Setting<>(true);
public Setting<Integer> pathingMaxChunkBorderFetch = new Setting<>(50);
public Setting<Double> backtrackCostFavoringCoefficient = new Setting<>(0.9); // see issue #18
public Setting<Float> pathRenderLineWidth = new Setting<>(5F);
public Setting<Float> goalRenderLineWidth = new Setting<>(3F);
public final Map<String, Setting<?>> byName;
public final List<Setting<?>> allSettings;
public class Setting<T> {
public T value;
private String name;
private final Class<T> klass;
private Setting(T value) {
if (value == null) {
throw new IllegalArgumentException("Cannot determine value type class from null");
}
this.value = value;
this.klass = (Class<T>) value.getClass();
}
public final <K extends T> K get() {
return (K) value;
}
public final String getName() {
return name;
}
public Class<T> getValueClass() {
return klass;
}
public String toString() {
return name + ": " + value;
}
}
// here be dragons
{
Field[] temp = getClass().getFields();
HashMap<String, Setting<?>> tmpByName = new HashMap<>();
List<Setting<?>> tmpAll = new ArrayList<>();
try {
for (Field field : temp) {
if (field.getType().equals(Setting.class)) {
Setting<?> setting = (Setting<? extends Object>) field.get(this);
String name = field.getName();
setting.name = name;
if (tmpByName.containsKey(name)) {
throw new IllegalStateException("Duplicate setting name");
}
tmpByName.put(name, setting);
tmpAll.add(setting);
}
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
byName = Collections.unmodifiableMap(tmpByName);
allSettings = Collections.unmodifiableList(tmpAll);
}
public <T> List<Setting<T>> getByValueType(Class<T> klass) {
ArrayList<Setting<T>> result = new ArrayList<>();
for (Setting<?> setting : allSettings) {
if (setting.klass.equals(klass)) {
result.add((Setting<T>) setting);
}
}
return result;
}
Settings() { }
}

View File

@@ -15,11 +15,10 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.behavior;
package baritone.bot.behavior;
import baritone.api.event.listener.AbstractGameEventListener;
import baritone.utils.Helper;
import baritone.utils.interfaces.Toggleable;
import baritone.bot.event.listener.AbstractGameEventListener;
import baritone.bot.utils.Helper;
/**
* A generic bot behavior.
@@ -27,7 +26,7 @@ import baritone.utils.interfaces.Toggleable;
* @author Brady
* @since 8/1/2018 6:29 PM
*/
public class Behavior implements AbstractGameEventListener, Toggleable, Helper {
public class Behavior implements AbstractGameEventListener, Helper {
/**
* Whether or not this behavior is enabled
@@ -39,7 +38,6 @@ public class Behavior implements AbstractGameEventListener, Toggleable, Helper {
*
* @return The new state.
*/
@Override
public final boolean toggle() {
return this.setEnabled(!this.enabled);
}
@@ -49,12 +47,10 @@ public class Behavior implements AbstractGameEventListener, Toggleable, Helper {
*
* @return The new state.
*/
@Override
public final boolean setEnabled(boolean enabled) {
boolean newState = getNewState(this.enabled, enabled);
if (newState == this.enabled) {
if (newState == this.enabled)
return this.enabled;
}
if (this.enabled = newState) {
onStart();
@@ -83,7 +79,6 @@ public class Behavior implements AbstractGameEventListener, Toggleable, Helper {
/**
* @return Whether or not this {@link Behavior} is active.
*/
@Override
public final boolean isEnabled() {
return this.enabled;
}

View File

@@ -0,0 +1,62 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package baritone.bot.behavior.impl;
import baritone.bot.behavior.Behavior;
import baritone.bot.utils.Rotation;
public class LookBehavior extends Behavior {
public static final LookBehavior INSTANCE = new LookBehavior();
private LookBehavior() {}
/**
* Target's values are as follows:
* <p>
* getFirst() -> yaw
* getSecond() -> pitch
*/
private Rotation target;
public void updateTarget(Rotation target) {
this.target = target;
}
@Override
public void onPlayerUpdate() {
if (target != null) {
player().rotationYaw = target.getFirst();
float oldPitch = player().rotationPitch;
float desiredPitch = target.getSecond();
player().rotationPitch = desiredPitch;
if (desiredPitch == oldPitch) {
nudgeToLevel();
}
target = null;
}
}
private void nudgeToLevel() {
if (player().rotationPitch < -20) {
player().rotationPitch++;
} else if (player().rotationPitch > 10) {
player().rotationPitch--;
}
}
}

View File

@@ -15,16 +15,19 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.behavior.impl;
package baritone.bot.behavior.impl;
import baritone.utils.*;
import baritone.bot.utils.BlockStateInterface;
import baritone.bot.utils.Helper;
import baritone.bot.utils.Rotation;
import baritone.bot.utils.Utils;
import net.minecraft.block.BlockFire;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.*;
import java.util.Optional;
import static baritone.utils.Utils.DEG_TO_RAD;
import static baritone.bot.utils.Utils.DEG_TO_RAD;
public final class LookBehaviorUtils implements Helper {
@@ -67,10 +70,9 @@ public final class LookBehaviorUtils implements Helper {
return Optional.of(new Rotation(mc.player.rotationYaw, mc.player.rotationPitch + 0.0001f));
}
Optional<Rotation> possibleRotation = reachableCenter(pos);
//System.out.println("center: " + possibleRotation);
if (possibleRotation.isPresent()) {
System.out.println("center: " + possibleRotation);
if (possibleRotation.isPresent())
return possibleRotation;
}
IBlockState state = BlockStateInterface.get(pos);
AxisAlignedBB aabb = state.getBoundingBox(mc.world, pos);
@@ -79,13 +81,24 @@ public final class LookBehaviorUtils implements Helper {
double yDiff = aabb.minY * sideOffset.y + aabb.maxY * (1 - sideOffset.y);
double zDiff = aabb.minZ * sideOffset.z + aabb.maxZ * (1 - sideOffset.z);
possibleRotation = reachableOffset(pos, new Vec3d(pos).add(xDiff, yDiff, zDiff));
if (possibleRotation.isPresent()) {
if (possibleRotation.isPresent())
return possibleRotation;
}
}
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
*
@@ -95,7 +108,7 @@ public final class LookBehaviorUtils implements Helper {
*/
protected static Optional<Rotation> reachableOffset(BlockPos pos, Vec3d offsetPos) {
Rotation rotation = Utils.calcRotationFromVec3d(mc.player.getPositionEyes(1.0F), offsetPos);
RayTraceResult result = RayTraceUtils.rayTraceTowards(rotation);
RayTraceResult result = rayTraceTowards(rotation);
System.out.println(result);
if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK) {
if (result.getBlockPos().equals(pos)) {

View File

@@ -1,9 +1,7 @@
package baritone.behavior.impl;
package baritone.bot.behavior.impl;
import baritone.api.event.events.PacketEvent;
import baritone.api.event.events.PlayerUpdateEvent;
import baritone.api.event.events.type.EventState;
import baritone.behavior.Behavior;
import baritone.bot.behavior.Behavior;
import baritone.bot.event.events.PacketEvent;
import net.minecraft.item.ItemStack;
import net.minecraft.network.Packet;
import net.minecraft.network.play.client.CPacketCloseWindow;
@@ -37,10 +35,8 @@ public class MemoryBehavior extends Behavior {
private final Map<BlockPos, RememberedInventory> rememberedInventories = new HashMap<>();
@Override
public void onPlayerUpdate(PlayerUpdateEvent event) {
if (event.getState() == EventState.PRE) {
updateInventory();
}
public void onPlayerUpdate() {
updateInventory();
}
@Override
@@ -60,7 +56,7 @@ public class MemoryBehavior extends Behavior {
TileEntityLockable lockable = (TileEntityLockable) tileEntity;
int size = lockable.getSizeInventory();
this.futureInventories.add(new FutureInventory(System.nanoTime() / 1000000L, size, lockable.getGuiID(), tileEntity.getPos()));
this.futureInventories.add(new FutureInventory(System.currentTimeMillis(), size, lockable.getGuiID(), tileEntity.getPos()));
}
}
@@ -82,18 +78,18 @@ public class MemoryBehavior extends Behavior {
SPacketOpenWindow packet = event.cast();
// Remove any entries that were created over a second ago, this should make up for INSANE latency
this.futureInventories.removeIf(i -> System.nanoTime() / 1000000L - i.time > 1000);
this.futureInventories.removeIf(i -> System.currentTimeMillis() - i.time > 1000);
this.futureInventories.stream()
.filter(i -> i.type.equals(packet.getGuiId()) && i.slots == packet.getSlotCount())
.findFirst().ifPresent(matched -> {
// Remove the future inventory
this.futureInventories.remove(matched);
// Remove the future inventory
this.futureInventories.remove(matched);
// Setup the remembered inventory
RememberedInventory inventory = this.rememberedInventories.computeIfAbsent(matched.pos, pos -> new RememberedInventory());
inventory.windowId = packet.getWindowId();
inventory.size = packet.getSlotCount();
// Setup the remembered inventory
RememberedInventory inventory = this.rememberedInventories.computeIfAbsent(matched.pos, pos -> new RememberedInventory());
inventory.windowId = packet.getWindowId();
inventory.size = packet.getSlotCount();
});
}

View File

@@ -15,26 +15,20 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.behavior.impl;
package baritone.bot.behavior.impl;
import baritone.Baritone;
import baritone.api.event.events.PathEvent;
import baritone.api.event.events.PlayerUpdateEvent;
import baritone.api.event.events.RenderEvent;
import baritone.api.event.events.TickEvent;
import baritone.behavior.Behavior;
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;
import baritone.utils.PathRenderer;
import net.minecraft.init.Blocks;
import baritone.bot.Baritone;
import baritone.bot.behavior.Behavior;
import baritone.bot.event.events.RenderEvent;
import baritone.bot.event.events.TickEvent;
import baritone.bot.pathing.calc.AStarPathFinder;
import baritone.bot.pathing.calc.AbstractNodeCostSearch;
import baritone.bot.pathing.calc.IPathFinder;
import baritone.bot.pathing.goals.Goal;
import baritone.bot.pathing.path.IPath;
import baritone.bot.pathing.path.PathExecutor;
import baritone.bot.utils.PathRenderer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.chunk.EmptyChunk;
import java.awt.*;
import java.util.Collections;
@@ -57,16 +51,11 @@ public class PathingBehavior extends Behavior {
private final Object pathPlanLock = new Object();
private boolean lastAutoJump;
private void dispatchPathEvent(PathEvent event) {
new Thread(() -> Baritone.INSTANCE.getGameEventHandler().onPathEvent(event)).start();
}
@Override
public void onTick(TickEvent event) {
if (event.getType() == TickEvent.Type.OUT) {
this.cancel();
current = null;
next = null;
return;
}
if (current == null) {
@@ -78,7 +67,6 @@ public class PathingBehavior extends Behavior {
current = null;
if (goal == null || goal.isInGoal(playerFeet())) {
displayChatMessageRaw("All done. At " + goal);
dispatchPathEvent(PathEvent.AT_GOAL);
next = null;
return;
}
@@ -90,12 +78,10 @@ public class PathingBehavior extends Behavior {
// but if we fail in the middle of current
// we're nowhere close to our planned ahead path
// so need to discard it sadly.
dispatchPathEvent(PathEvent.DISCARD_NEXT);
next = null;
}
if (next != null) {
displayChatMessageRaw("Continuing on to planned next path");
dispatchPathEvent(PathEvent.CONTINUING_ONTO_PLANNED_NEXT);
current = next;
next = null;
return;
@@ -103,12 +89,10 @@ public class PathingBehavior extends Behavior {
// at this point, current just ended, but we aren't in the goal and have no plan for the future
synchronized (pathCalcLock) {
if (isPathCalcInProgress) {
dispatchPathEvent(PathEvent.PATH_FINISHED_NEXT_STILL_CALCULATING);
// if we aren't calculating right now
return;
}
dispatchPathEvent(PathEvent.CALC_STARTED);
findPathInNewThread(pathStart(), true, Optional.empty());
findPathInNewThread(playerFeet(), true, Optional.empty());
}
return;
}
@@ -119,7 +103,6 @@ public class PathingBehavior extends Behavior {
if (next.getPath().positions().contains(playerFeet())) {
// jump directly onto the next path
displayChatMessageRaw("Splicing into planned next path early...");
dispatchPathEvent(PathEvent.SPLICING_ONTO_NEXT_EARLY);
current = next;
next = null;
return;
@@ -142,28 +125,12 @@ public class PathingBehavior extends Behavior {
if (ticksRemainingInSegment().get() < Baritone.settings().planningTickLookAhead.get()) {
// and this path has 5 seconds or less left
displayChatMessageRaw("Path almost over. Planning ahead...");
dispatchPathEvent(PathEvent.NEXT_SEGMENT_CALC_STARTED);
findPathInNewThread(current.getPath().getDest(), false, Optional.of(current.getPath()));
}
}
}
}
@Override
public void onPlayerUpdate(PlayerUpdateEvent event) {
if (current != null) {
switch (event.getState()) {
case PRE:
lastAutoJump = mc.gameSettings.autoJump;
mc.gameSettings.autoJump = false;
break;
case POST:
mc.gameSettings.autoJump = lastAutoJump;
break;
}
}
}
public Optional<Double> ticksRemainingInSegment() {
if (current == null) {
return Optional.empty();
@@ -175,17 +142,11 @@ public class PathingBehavior extends Behavior {
this.goal = goal;
}
public Goal getGoal() {
return goal;
}
public PathExecutor getCurrent() {
return current;
}
public PathExecutor getNext() {
return next;
}
public PathExecutor getNext() {return next;}
public Optional<IPath> getPath() {
return Optional.ofNullable(current).map(PathExecutor::getPath);
@@ -195,44 +156,23 @@ public class PathingBehavior extends Behavior {
current = null;
next = null;
Baritone.INSTANCE.getInputOverrideHandler().clearAllKeys();
AbstractNodeCostSearch.getCurrentlyRunning().ifPresent(AbstractNodeCostSearch::cancel);
}
/**
* Start calculating a path if we aren't already
*
* @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;
}
public void path() {
synchronized (pathPlanLock) {
if (current != null) {
return false;
displayChatMessageRaw("Currently executing a path. Please cancel it first.");
return;
}
synchronized (pathCalcLock) {
if (isPathCalcInProgress) {
return false;
return;
}
dispatchPathEvent(PathEvent.CALC_STARTED);
findPathInNewThread(pathStart(), true, Optional.empty());
return true;
findPathInNewThread(playerFeet(), true, Optional.empty());
}
}
}
public BlockPos pathStart() {
BlockPos feet = playerFeet();
if (BlockStateInterface.get(feet.down()).getBlock().equals(Blocks.AIR) && MovementHelper.canWalkOn(feet.down().down())) {
return feet.down();
}
return feet;
}
/**
* In a new thread, pathfind to target blockpos
*
@@ -251,33 +191,19 @@ public class PathingBehavior extends Behavior {
displayChatMessageRaw("Starting to search for path from " + start + " to " + goal);
}
Optional<IPath> path = findPath(start, previous);
if (Baritone.settings().cutoffAtLoadBoundary.get()) {
path = path.map(IPath::cutoffAtLoadedChunks);
}
Optional<PathExecutor> executor = path.map(p -> p.staticCutoff(goal)).map(PathExecutor::new);
synchronized (pathPlanLock) {
if (current == null) {
if (executor.isPresent()) {
dispatchPathEvent(PathEvent.CALC_FINISHED_NOW_EXECUTING);
current = executor.get();
findPath(start, previous).map(IPath::cutoffAtLoadedChunks).map(PathExecutor::new).ifPresent(path -> {
synchronized (pathPlanLock) {
if (current == null) {
current = path;
} else {
dispatchPathEvent(PathEvent.CALC_FAILED);
}
} else {
if (next == null) {
if (executor.isPresent()) {
dispatchPathEvent(PathEvent.NEXT_SEGMENT_CALC_FINISHED);
next = executor.get();
if (next == null) {
next = path;
} else {
dispatchPathEvent(PathEvent.NEXT_CALC_FAILED);
throw new IllegalStateException("I have no idea what to do with this path");
}
} else {
throw new IllegalStateException("I have no idea what to do with this path");
}
}
}
});
if (talkAboutIt && current != null && current.getPath() != null) {
if (goal == null || goal.isInGoal(current.getPath().getDest())) {
displayChatMessageRaw("Finished finding a path from " + start + " to " + goal + ". " + current.getPath().getNumNodesConsidered() + " nodes considered");
@@ -299,42 +225,15 @@ public class PathingBehavior extends Behavior {
* @return
*/
private Optional<IPath> findPath(BlockPos start, Optional<IPath> previous) {
Goal goal = this.goal;
if (goal == null) {
displayChatMessageRaw("no goal");
return Optional.empty();
}
if (Baritone.settings().simplifyUnloadedYCoord.get()) {
BlockPos pos = null;
if (goal instanceof GoalBlock) {
pos = ((GoalBlock) goal).getGoalPos();
}
if (goal instanceof GoalTwoBlocks) {
pos = ((GoalTwoBlocks) goal).getGoalPos();
}
if (goal instanceof GoalNear) {
pos = ((GoalNear) goal).getGoalPos();
}
if (goal instanceof GoalGetToBlock) {
pos = ((GoalGetToBlock) goal).getGoalPos();
}
// TODO simplify each individual goal in a GoalComposite
if (pos != null && world().getChunk(pos) instanceof EmptyChunk) {
displayChatMessageRaw("Simplifying " + goal.getClass() + " to GoalXZ due to distance");
goal = new GoalXZ(pos.getX(), pos.getZ());
}
}
long timeout;
if (current == null) {
timeout = Baritone.settings().pathTimeoutMS.<Long>get();
} else {
timeout = Baritone.settings().planAheadTimeoutMS.<Long>get();
}
try {
IPathFinder pf = new AStarPathFinder(start, goal, previous.map(IPath::positions));
return pf.calculate(timeout);
return pf.calculate();
} catch (Exception e) {
displayChatMessageRaw("Pathing exception: " + e);
displayChatMessageRaw("Exception: " + e);
e.printStackTrace();
return Optional.empty();
}
@@ -366,7 +265,7 @@ public class PathingBehavior extends Behavior {
PathRenderer.drawPath(current.getPath(), renderBegin, player(), partialTicks, Color.RED, Baritone.settings().fadePath.get(), 10, 20);
}
if (next != null && next.getPath() != null) {
PathRenderer.drawPath(next.getPath(), 0, player(), partialTicks, Color.MAGENTA, Baritone.settings().fadePath.get(), 10, 20);
PathRenderer.drawPath(next.getPath(), 0, player(), partialTicks, Color.GREEN, Baritone.settings().fadePath.get(), 10, 20);
}
long split = System.nanoTime();
@@ -389,9 +288,8 @@ public class PathingBehavior extends Behavior {
});
long end = System.nanoTime();
//System.out.println((end - split) + " " + (split - start));
// if (end - start > 0) {
// if (end - start > 0)
// System.out.println("Frame took " + (split - start) + " " + (end - split));
//}
}
}

View File

@@ -0,0 +1,131 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package baritone.bot.chunk;
import baritone.bot.utils.pathing.IBlockTypeAccess;
import baritone.bot.utils.pathing.PathingBlockType;
import java.util.BitSet;
/**
* @author Brady
* @since 8/3/2018 1:04 AM
*/
public final class CachedChunk implements IBlockTypeAccess {
/**
* The size of the chunk data in bits. Equal to 16 KiB.
* <p>
* Chunks are 16x16x256, each block requires 2 bits.
*/
public static final int SIZE = 2 * 16 * 16 * 256;
/**
* The size of the chunk data in bytes. Equal to 16 KiB.
*/
public static final int SIZE_IN_BYTES = SIZE / 8;
/**
* An array of just 0s with the length of {@link CachedChunk#SIZE_IN_BYTES}
*/
public static final byte[] EMPTY_CHUNK = new byte[SIZE_IN_BYTES];
/**
* The chunk x coordinate
*/
private final int x;
/**
* The chunk z coordinate
*/
private final int z;
/**
* The actual raw data of this packed chunk.
* <p>
* Each block is expressed as 2 bits giving a total of 16 KiB
*/
private final BitSet data;
CachedChunk(int x, int z, BitSet data) {
validateSize(data);
this.x = x;
this.z = z;
this.data = data;
}
@Override
public final PathingBlockType getBlockType(int x, int y, int z) {
int index = getPositionIndex(x, y, z);
return PathingBlockType.fromBits(data.get(index), data.get(index + 1));
}
void updateContents(BitSet data) {
validateSize(data);
for (int i = 0; i < data.length(); i++)
this.data.set(i, data.get(i));
}
/**
* @return Thee chunk x coordinat
*/
public final int getX() {
return this.x;
}
/**
* @return The chunk z coordinate
*/
public final int getZ() {
return this.z;
}
/**
* @return Returns the raw packed chunk data as a byte array
*/
public final byte[] toByteArray() {
return this.data.toByteArray();
}
/**
* Returns the raw bit index of the specified position
*
* @param x The x position
* @param y The y position
* @param z The z position
* @return The bit index
*/
public static int getPositionIndex(int x, int y, int z) {
return (x + (z << 4) + (y << 8)) * 2;
}
/**
* Validates the size of an input {@link BitSet} containing the raw
* packed chunk data. Sizes that exceed {@link CachedChunk#SIZE} are
* considered invalid, and thus, an exception will be thrown.
*
* @param data The raw data
* @throws IllegalArgumentException if the bitset size exceeds the maximum size
*/
private static void validateSize(BitSet data) {
if (data.size() > SIZE)
throw new IllegalArgumentException("BitSet of invalid length provided");
}
}

View File

@@ -0,0 +1,180 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package baritone.bot.chunk;
import baritone.bot.utils.pathing.PathingBlockType;
import baritone.bot.utils.GZIPUtils;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.BitSet;
import java.util.function.Consumer;
import java.util.zip.GZIPOutputStream;
/**
* @author Brady
* @since 8/3/2018 9:35 PM
*/
public final class CachedRegion implements ICachedChunkAccess {
/**
* All of the chunks in this region: A 32x32 array of them.
*/
private final CachedChunk[][] chunks = new CachedChunk[32][32];
/**
* The region x coordinate
*/
private final int x;
/**
* The region z coordinate
*/
private final int z;
CachedRegion(int x, int z) {
this.x = x;
this.z = z;
}
@Override
public final PathingBlockType getBlockType(int x, int y, int z) {
CachedChunk chunk = this.getChunk(x >> 4, z >> 4);
if (chunk != null) {
return chunk.getBlockType(x & 15, y, z & 15);
}
return null;
}
@Override
public final void updateCachedChunk(int chunkX, int chunkZ, BitSet data) {
CachedChunk chunk = this.getChunk(chunkX, chunkZ);
if (chunk == null) {
this.chunks[chunkX][chunkZ] = new CachedChunk(chunkX, chunkZ, data);
} else {
chunk.updateContents(data);
}
}
private CachedChunk getChunk(int chunkX, int chunkZ) {
return this.chunks[chunkX][chunkZ];
}
public void forEachChunk(Consumer<CachedChunk> consumer) {
for (int x = 0; x < 32; x++) {
for (int z = 0; z < 32; z++) {
CachedChunk chunk = getChunk(x, z);
if (chunk != null) {
consumer.accept(chunk);
}
}
}
}
public final void save(String directory) {
try {
Path path = Paths.get(directory);
if (!Files.exists(path))
Files.createDirectories(path);
Path regionFile = getRegionFile(path, this.x, this.z);
if (!Files.exists(regionFile))
Files.createFile(regionFile);
try (FileOutputStream fileOut = new FileOutputStream(regionFile.toFile()); GZIPOutputStream out = new GZIPOutputStream(fileOut)) {
for (int z = 0; z < 32; z++) {
for (int x = 0; x < 32; x++) {
CachedChunk chunk = this.chunks[x][z];
if (chunk == null) {
out.write(CachedChunk.EMPTY_CHUNK);
} else {
byte[] chunkBytes = chunk.toByteArray();
out.write(chunkBytes);
// Messy, but fills the empty 0s that should be trailing to fill up the space.
out.write(new byte[CachedChunk.SIZE_IN_BYTES - chunkBytes.length]);
}
}
}
}
} catch (IOException ignored) {}
}
public void load(String directory) {
try {
Path path = Paths.get(directory);
if (!Files.exists(path))
Files.createDirectories(path);
Path regionFile = getRegionFile(path, this.x, this.z);
if (!Files.exists(regionFile))
return;
byte[] decompressed;
try (FileInputStream in = new FileInputStream(regionFile.toFile())) {
decompressed = GZIPUtils.decompress(in);
}
if (decompressed == null)
return;
for (int z = 0; z < 32; z++) {
for (int x = 0; x < 32; x++) {
int index = (x + (z << 5)) * CachedChunk.SIZE_IN_BYTES;
byte[] bytes = Arrays.copyOfRange(decompressed, index, index + CachedChunk.SIZE_IN_BYTES);
if (isAllZeros(bytes)) {
this.chunks[x][z] = null;
} else {
BitSet bits = BitSet.valueOf(bytes);
updateCachedChunk(x, z, bits);
}
}
}
} catch (IOException ignored) {}
}
private static boolean isAllZeros(final byte[] array) {
for (byte b : array) {
if (b != 0) {
return false;
}
}
return true;
}
/**
* @return The region x coordinate
*/
public final int getX() {
return this.x;
}
/**
* @return The region z coordinate
*/
public final int getZ() {
return this.z;
}
private static Path getRegionFile(Path cacheDir, int regionX, int regionZ) {
return Paths.get(cacheDir.toString(), "r." + regionX + "." + regionZ + ".bcr");
}
}

View File

@@ -0,0 +1,144 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package baritone.bot.chunk;
import baritone.bot.utils.pathing.PathingBlockType;
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import java.util.BitSet;
import java.util.function.Consumer;
/**
* @author Brady
* @since 8/4/2018 12:02 AM
*/
public final class CachedWorld implements ICachedChunkAccess {
/**
* The maximum number of regions in any direction from (0,0)
*/
private static final int REGION_MAX = 117188;
/**
* A map of all of the cached regions.
*/
private Long2ObjectMap<CachedRegion> cachedRegions = new Long2ObjectOpenHashMap<>();
/**
* The directory that the cached region files are saved to
*/
private final String directory;
public CachedWorld(String directory) {
this.directory = directory;
// Insert an invalid region element
cachedRegions.put(0, null);
}
@Override
public final PathingBlockType getBlockType(int x, int y, int z) {
CachedRegion region = getRegion(x >> 9, z >> 9);
if (region != null) {
return region.getBlockType(x & 511, y, z & 511);
}
return null;
}
@Override
public final void updateCachedChunk(int chunkX, int chunkZ, BitSet data) {
CachedRegion region = getOrCreateRegion(chunkX >> 5, chunkZ >> 5);
if (region != null) {
region.updateCachedChunk(chunkX & 31, chunkZ & 31, data);
}
}
public final void save() {
this.cachedRegions.values().forEach(region -> {
if (region != null)
region.save(this.directory);
});
}
public final void load() {
this.cachedRegions.values().forEach(region -> {
if (region != null)
region.load(this.directory);
});
}
/**
* Returns the region at the specified region coordinates
*
* @param regionX The region X coordinate
* @param regionZ The region Z coordinate
* @return The region located at the specified coordinates
*/
public final CachedRegion getRegion(int regionX, int regionZ) {
return cachedRegions.get(getRegionID(regionX, regionZ));
}
/**
* Returns the region at the specified region coordinates. If a
* region is not found, then a new one is created.
*
* @param regionX The region X coordinate
* @param regionZ The region Z coordinate
* @return The region located at the specified coordinates
*/
CachedRegion getOrCreateRegion(int regionX, int regionZ) {
return cachedRegions.computeIfAbsent(getRegionID(regionX, regionZ), id -> {
CachedRegion newRegion = new CachedRegion(regionX, regionZ);
newRegion.load(this.directory);
return newRegion;
});
}
public void forEachRegion(Consumer<CachedRegion> consumer) {
this.cachedRegions.forEach((id, r) -> {
if (r != null)
consumer.accept(r);
});
}
/**
* Returns the region ID based on the region coordinates. 0 will be
* returned if the specified region coordinates are out of bounds.
*
* @param regionX The region X coordinate
* @param regionZ The region Z coordinate
* @return The region ID
*/
private long getRegionID(int regionX, int regionZ) {
if (!isRegionInWorld(regionX, regionZ))
return 0;
return (long) regionX & 0xFFFFFFFFL | ((long) regionZ & 0xFFFFFFFFL) << 32;
}
/**
* Returns whether or not the specified region coordinates is within the world bounds.
*
* @param regionX The region X coordinate
* @param regionZ The region Z coordinate
* @return Whether or not the region is in world bounds
*/
private boolean isRegionInWorld(int regionX, int regionZ) {
return regionX <= REGION_MAX && regionX >= -REGION_MAX && regionZ <= REGION_MAX && regionZ >= -REGION_MAX;
}
}

View File

@@ -0,0 +1,98 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package baritone.bot.chunk;
import baritone.bot.utils.Helper;
import baritone.launch.mixins.accessor.IAnvilChunkLoader;
import baritone.launch.mixins.accessor.IChunkProviderServer;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.server.integrated.IntegratedServer;
import net.minecraft.world.WorldServer;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Brady
* @since 8/4/2018 11:06 AM
*/
public enum CachedWorldProvider implements Helper {
INSTANCE;
private static final Pattern REGION_REGEX = Pattern.compile("r\\.(-?[0-9]+)\\.(-?[0-9]+)\\.bcr");
private final Map<String, CachedWorld> singlePlayerWorldCache = new HashMap<>();
private CachedWorld currentWorld;
public final CachedWorld getCurrentWorld() {
return this.currentWorld;
}
public final void initWorld(WorldClient world) {
IntegratedServer integratedServer;
if ((integratedServer = mc.getIntegratedServer()) != null) {
WorldServer localServerWorld = integratedServer.getWorld(world.provider.getDimensionType().getId());
IChunkProviderServer provider = (IChunkProviderServer) localServerWorld.getChunkProvider();
IAnvilChunkLoader loader = (IAnvilChunkLoader) provider.getChunkLoader();
Path dir = new File(new File(loader.getChunkSaveLocation(), "region"), "cache").toPath();
if (!Files.exists(dir)) {
try {
Files.createDirectories(dir);
} catch (IOException ignored) {}
}
this.currentWorld = this.singlePlayerWorldCache.computeIfAbsent(dir.toString(), CachedWorld::new);
try {
Files.list(dir).forEach(path -> {
String file = path.getFileName().toString();
Matcher matcher = REGION_REGEX.matcher(file);
if (matcher.matches()) {
int rx = Integer.parseInt(matcher.group(1));
int ry = Integer.parseInt(matcher.group(2));
// Recognize the region for when we load from file
this.currentWorld.getOrCreateRegion(rx, ry);
}
});
} catch (Exception ignored) {}
this.currentWorld.load();
}
// TODO: Store server worlds
}
public final void closeWorld() {
this.currentWorld = null;
}
public final void ifWorldLoaded(Consumer<CachedWorld> currentWorldConsumer) {
if (this.currentWorld != null)
currentWorldConsumer.accept(this.currentWorld);
}
}

View File

@@ -0,0 +1,78 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package baritone.bot.chunk;
import baritone.bot.pathing.movement.MovementHelper;
import baritone.bot.utils.pathing.PathingBlockType;
import baritone.bot.utils.BlockStateInterface;
import baritone.bot.utils.Helper;
import net.minecraft.block.Block;
import net.minecraft.block.BlockAir;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.chunk.Chunk;
import java.util.BitSet;
import static net.minecraft.block.Block.NULL_AABB;
/**
* @author Brady
* @since 8/3/2018 1:09 AM
*/
public final class ChunkPacker implements Helper {
private ChunkPacker() {}
public static BitSet createPackedChunk(Chunk chunk) {
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);
boolean[] bits = getPathingBlockType(new BlockPos(x, y, z), chunk.getBlockState(x, y, z)).getBits();
bitSet.set(index, bits[0]);
bitSet.set(index + 1, bits[1]);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return bitSet;
}
private static PathingBlockType getPathingBlockType(BlockPos pos, IBlockState state) {
Block block = state.getBlock();
if (BlockStateInterface.isWater(block)) {
return PathingBlockType.WATER;
}
if (MovementHelper.avoidWalkingInto(block)) {
return PathingBlockType.AVOID;
}
if (block instanceof BlockAir || state.getCollisionBoundingBox(mc.world, pos) == NULL_AABB) {
return PathingBlockType.AIR;
}
return PathingBlockType.SOLID;
}
}

View File

@@ -15,10 +15,17 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.utils.interfaces;
package baritone.bot.chunk;
import net.minecraft.util.math.BlockPos;
import baritone.bot.utils.pathing.IBlockTypeAccess;
public interface IGoalRenderPos {
BlockPos getGoalPos();
import java.util.BitSet;
/**
* @author Brady
* @since 8/4/2018 1:10 AM
*/
public interface ICachedChunkAccess extends IBlockTypeAccess {
void updateCachedChunk(int chunkX, int chunkZ, BitSet data);
}

View File

@@ -0,0 +1,189 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package baritone.bot.event;
import baritone.bot.Baritone;
import baritone.bot.behavior.Behavior;
import baritone.bot.chunk.CachedWorld;
import baritone.bot.chunk.CachedWorldProvider;
import baritone.bot.chunk.ChunkPacker;
import baritone.bot.event.events.*;
import baritone.bot.event.events.type.EventState;
import baritone.bot.event.listener.IGameEventListener;
import baritone.bot.utils.Helper;
import baritone.bot.utils.InputOverrideHandler;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.client.settings.KeyBinding;
import org.lwjgl.input.Keyboard;
import java.util.function.Consumer;
/**
* @author Brady
* @since 7/31/2018 11:04 PM
*/
public final class GameEventHandler implements IGameEventListener, Helper {
@Override
public final void onTick(TickEvent event) {
dispatch(behavior -> behavior.onTick(event));
}
@Override
public void onPlayerUpdate() {
dispatch(Behavior::onPlayerUpdate);
}
@Override
public void onProcessKeyBinds() {
InputOverrideHandler inputHandler = Baritone.INSTANCE.getInputOverrideHandler();
// Simulate the key being held down this tick
for (InputOverrideHandler.Input input : InputOverrideHandler.Input.values()) {
KeyBinding keyBinding = input.getKeyBinding();
if (inputHandler.isInputForcedDown(keyBinding) && !keyBinding.isKeyDown()) {
int keyCode = keyBinding.getKeyCode();
if (keyCode < Keyboard.KEYBOARD_SIZE)
KeyBinding.onTick(keyCode < 0 ? keyCode + 100 : keyCode);
}
}
dispatch(Behavior::onProcessKeyBinds);
}
@Override
public void onSendChatMessage(ChatEvent event) {
dispatch(behavior -> behavior.onSendChatMessage(event));
}
@Override
public void onChunkEvent(ChunkEvent event) {
EventState state = event.getState();
ChunkEvent.Type type = event.getType();
boolean isPostPopulate = state == EventState.POST
&& type == ChunkEvent.Type.POPULATE;
// Whenever the server sends us to another dimension, chunks are unloaded
// technically after the new world has been loaded, so we perform a check
// to make sure the chunk being unloaded is already loaded.
boolean isPreUnload = state == EventState.PRE
&& type == ChunkEvent.Type.UNLOAD
&& mc.world.getChunkProvider().isChunkGeneratedAt(event.getX(), event.getZ());
if (Baritone.settings().chuckCaching.get()) {
if (isPostPopulate || isPreUnload) {
CachedWorldProvider.INSTANCE.ifWorldLoaded(world ->
world.updateCachedChunk(event.getX(), event.getZ(),
ChunkPacker.createPackedChunk(mc.world.getChunk(event.getX(), event.getZ()))));
}
}
dispatch(behavior -> behavior.onChunkEvent(event));
}
@Override
public void onRenderPass(RenderEvent event) {
/*
CachedWorldProvider.INSTANCE.ifWorldLoaded(world -> world.forEachRegion(region -> region.forEachChunk(chunk -> {
drawChunkLine(region.getX() * 512 + chunk.getX() * 16, region.getZ() * 512 + chunk.getZ() * 16, event.getPartialTicks());
})));
*/
dispatch(behavior -> behavior.onRenderPass(event));
}
@Override
public void onWorldEvent(WorldEvent event) {
if (Baritone.settings().chuckCaching.get()) {
CachedWorldProvider cache = CachedWorldProvider.INSTANCE;
switch (event.getState()) {
case PRE:
cache.ifWorldLoaded(CachedWorld::save);
break;
case POST:
cache.closeWorld();
if (event.getWorld() != null)
cache.initWorld(event.getWorld());
break;
}
}
dispatch(behavior -> behavior.onWorldEvent(event));
}
@Override
public void onSendPacket(PacketEvent event) {
dispatch(behavior -> behavior.onSendPacket(event));
}
@Override
public void onReceivePacket(PacketEvent event) {
dispatch(behavior -> behavior.onReceivePacket(event));
}
private void dispatch(Consumer<Behavior> dispatchFunction) {
Baritone.INSTANCE.getBehaviors().stream().filter(Behavior::isEnabled).forEach(dispatchFunction);
}
private void drawChunkLine(int posX, int posZ, float partialTicks) {
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0);
GlStateManager.color(1.0F, 1.0F, 0.0F, 0.4F);
GlStateManager.glLineWidth(2.0F);
GlStateManager.disableTexture2D();
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder buffer = tessellator.getBuffer();
double d0 = mc.getRenderManager().viewerPosX;
double d1 = mc.getRenderManager().viewerPosY;
double d2 = mc.getRenderManager().viewerPosZ;
buffer.begin(3, DefaultVertexFormats.POSITION);
buffer.pos(posX - d0, 0 - d1, posZ - d2).endVertex();
buffer.pos(posX - d0, 256 - d1, posZ - d2).endVertex();
tessellator.draw();
GlStateManager.enableDepth();
GlStateManager.depthMask(true);
GlStateManager.enableTexture2D();
GlStateManager.disableBlend();
}
}

View File

@@ -15,9 +15,9 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.event.events;
package baritone.bot.event.events;
import baritone.api.event.events.type.Cancellable;
import baritone.bot.event.events.type.Cancellable;
/**
* @author Brady

View File

@@ -15,9 +15,9 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.event.events;
package baritone.bot.event.events;
import baritone.api.event.events.type.EventState;
import baritone.bot.event.events.type.EventState;
/**
* @author Brady

View File

@@ -15,9 +15,9 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.event.events;
package baritone.bot.event.events;
import baritone.api.event.events.type.EventState;
import baritone.bot.event.events.type.EventState;
import net.minecraft.network.Packet;
/**

View File

@@ -15,7 +15,7 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.event.events;
package baritone.bot.event.events;
/**
* @author Brady

View File

@@ -15,9 +15,9 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.event.events;
package baritone.bot.event.events;
import baritone.api.event.events.type.EventState;
import baritone.bot.event.events.type.EventState;
public final class TickEvent {

View File

@@ -15,9 +15,9 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.event.events;
package baritone.bot.event.events;
import baritone.api.event.events.type.EventState;
import baritone.bot.event.events.type.EventState;
import net.minecraft.client.multiplayer.WorldClient;
/**

View File

@@ -15,7 +15,7 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.event.events.type;
package baritone.bot.event.events.type;
/**
* @author Brady

View File

@@ -15,7 +15,7 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.event.events.type;
package baritone.bot.event.events.type;
/**
* @author Brady

View File

@@ -32,17 +32,18 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.event.listener;
package baritone.bot.event.listener;
import baritone.api.event.events.*;
import baritone.bot.event.events.*;
/**
* An implementation of {@link IGameEventListener} that has all methods
* overridden with empty bodies, allowing inheritors of this class to choose
* which events they would like to listen in on.
*
* @author Brady
* @see IGameEventListener
*
* @author Brady
* @since 8/1/2018 6:29 PM
*/
public interface AbstractGameEventListener extends IGameEventListener {
@@ -51,7 +52,7 @@ public interface AbstractGameEventListener extends IGameEventListener {
default void onTick(TickEvent event) {}
@Override
default void onPlayerUpdate(PlayerUpdateEvent event) {}
default void onPlayerUpdate() {}
@Override
default void onProcessKeyBinds() {}
@@ -73,16 +74,4 @@ public interface AbstractGameEventListener extends IGameEventListener {
@Override
default void onReceivePacket(PacketEvent event) {}
@Override
default void onPlayerRelativeMove(RelativeMoveEvent event) {}
@Override
default void onBlockInteract(BlockInteractEvent event) {}
@Override
default void onPlayerDeath() {}
@Override
default void onPathEvent(PathEvent event) {}
}

View File

@@ -32,20 +32,17 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.event.listener;
package baritone.bot.event.listener;
import baritone.api.event.events.*;
import baritone.bot.event.events.*;
import io.netty.util.concurrent.GenericFutureListener;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.gui.GuiGameOver;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.entity.Entity;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.util.text.ITextComponent;
/**
* @author Brady
@@ -61,11 +58,10 @@ public interface IGameEventListener {
void onTick(TickEvent event);
/**
* Run once per game tick from before and after the player rotation is sent to the server.
*
* Run once per game tick from before the player rotation is sent to the server.
* @see EntityPlayerSP#onUpdate()
*/
void onPlayerUpdate(PlayerUpdateEvent event);
void onPlayerUpdate();
/**
* Run once per game tick from before keybinds are processed.
@@ -118,32 +114,5 @@ public interface IGameEventListener {
*/
void onReceivePacket(PacketEvent event);
/**
* Run once per game tick from before and after the player's moveRelative method is called
*
* @see Entity#moveRelative(float, float, float, float)
*/
void onPlayerRelativeMove(RelativeMoveEvent event);
/**
* Called when the local player interacts with a block, whether it is breaking or opening/placing.
*
* @see Minecraft#clickMouse()
* @see Minecraft#rightClickMouse()
*/
void onBlockInteract(BlockInteractEvent event);
/**
* Called when the local player dies, as indicated by the creation of the {@link GuiGameOver} screen.
*
* @see GuiGameOver(ITextComponent)
*/
void onPlayerDeath();
/**
* When the pathfinder's state changes
*
* @param event
*/
void onPathEvent(PathEvent event);
}

View File

@@ -15,25 +15,42 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.calc;
/*
* 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 <https://www.gnu.org/licenses/>.
*/
import baritone.Baritone;
import baritone.chunk.CachedWorld;
import baritone.chunk.WorldProvider;
import baritone.pathing.calc.openset.BinaryHeapOpenSet;
import baritone.pathing.goals.Goal;
import baritone.pathing.movement.ActionCosts;
import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.Movement;
import baritone.pathing.movement.MovementHelper;
import baritone.pathing.movement.movements.*;
import baritone.pathing.path.IPath;
import baritone.utils.BlockStateInterface;
import baritone.utils.Helper;
package baritone.bot.pathing.calc;
import baritone.bot.Baritone;
import baritone.bot.chunk.CachedWorldProvider;
import baritone.bot.pathing.calc.openset.BinaryHeapOpenSet;
import baritone.bot.pathing.calc.openset.IOpenSet;
import baritone.bot.pathing.goals.Goal;
import baritone.bot.pathing.movement.ActionCosts;
import baritone.bot.pathing.movement.CalculationContext;
import baritone.bot.pathing.movement.Movement;
import baritone.bot.pathing.movement.MovementHelper;
import baritone.bot.pathing.movement.movements.*;
import baritone.bot.pathing.path.IPath;
import baritone.bot.utils.Helper;
import baritone.bot.utils.pathing.BetterBlockPos;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ChunkProviderClient;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.chunk.EmptyChunk;
import java.util.Collection;
import java.util.HashSet;
@@ -47,19 +64,19 @@ import java.util.Random;
*/
public class AStarPathFinder extends AbstractNodeCostSearch implements Helper {
private final Optional<HashSet<BlockPos>> favoredPositions;
private final Optional<HashSet<BetterBlockPos>> favoredPositions;
public AStarPathFinder(BlockPos start, Goal goal, Optional<Collection<BlockPos>> favoredPositions) {
public AStarPathFinder(BlockPos start, Goal goal, Optional<Collection<BetterBlockPos>> favoredPositions) {
super(start, goal);
this.favoredPositions = favoredPositions.map(HashSet::new); // <-- okay this is epic
}
@Override
protected Optional<IPath> calculate0(long timeout) {
protected Optional<IPath> calculate0() {
startNode = getNodeAtPosition(start);
startNode.cost = 0;
startNode.combinedCost = startNode.estimatedCostToGoal;
BinaryHeapOpenSet openSet = new BinaryHeapOpenSet();
IOpenSet openSet = new BinaryHeapOpenSet();
openSet.insert(startNode);
startNode.isOpen = true;
bestSoFar = new PathNode[COEFFICIENTS.length];//keep track of the best node by the metric of (estimatedCostToGoal + cost / COEFFICIENTS[i])
@@ -68,26 +85,19 @@ public class AStarPathFinder extends AbstractNodeCostSearch implements Helper {
bestHeuristicSoFar[i] = Double.MAX_VALUE;
}
CalculationContext calcContext = new CalculationContext();
HashSet<BlockPos> favored = favoredPositions.orElse(null);
HashSet<BetterBlockPos> favored = favoredPositions.orElse(null);
currentlyRunning = this;
CachedWorld cachedWorld = Optional.ofNullable(WorldProvider.INSTANCE.getCurrentWorld()).map(w -> w.cache).orElse(null);
ChunkProviderClient chunkProvider = Minecraft.getMinecraft().world.getChunkProvider();
BlockStateInterface.clearCachedChunk();
long startTime = System.nanoTime() / 1000000L;
long startTime = System.currentTimeMillis();
boolean slowPath = Baritone.settings().slowPath.get();
if (slowPath) {
displayChatMessageRaw("slowPath is on, path timeout will be " + Baritone.settings().slowPathTimeoutMS.<Long>get() + "ms instead of " + timeout + "ms");
}
long timeoutTime = startTime + (slowPath ? Baritone.settings().slowPathTimeoutMS.<Long>get() : timeout);
//long lastPrintout = 0;
long timeoutTime = startTime + (slowPath ? Baritone.settings().slowPathTimeoutMS : Baritone.settings().pathTimeoutMS).<Long>get();
long lastPrintout = 0;
int numNodes = 0;
int numMovementsConsidered = 0;
int numEmptyChunk = 0;
boolean favoring = favoredPositions.isPresent();
int pathingMaxChunkBorderFetch = Baritone.settings().pathingMaxChunkBorderFetch.get(); // grab all settings beforehand so that changing settings during pathing doesn't cause a crash or unpredictable behavior
boolean favoring = favoredPositions.isPresent(); // grab all settings beforehand so that changing settings during pathing doesn't cause a crash or unpredictable behavior
boolean cache = Baritone.settings().chuckCaching.get();
int pathingMaxChunkBorderFetch = Baritone.settings().pathingMaxChunkBorderFetch.get();
double favorCoeff = Baritone.settings().backtrackCostFavoringCoefficient.get();
boolean minimumImprovementRepropagation = Baritone.settings().minimumImprovementRepropagation.get();
while (!openSet.isEmpty() && numEmptyChunk < pathingMaxChunkBorderFetch && System.nanoTime() / 1000000L - timeoutTime < 0 && !cancelRequested) {
while (!openSet.isEmpty() && numEmptyChunk < pathingMaxChunkBorderFetch && System.currentTimeMillis() < timeoutTime) {
if (slowPath) {
try {
Thread.sleep(Baritone.settings().slowPathTimeDelayMS.<Long>get());
@@ -97,35 +107,43 @@ public class AStarPathFinder extends AbstractNodeCostSearch implements Helper {
PathNode currentNode = openSet.removeLowest();
currentNode.isOpen = false;
mostRecentConsidered = currentNode;
BlockPos currentNodePos = currentNode.pos;
BetterBlockPos currentNodePos = currentNode.pos;
numNodes++;
if (System.currentTimeMillis() > lastPrintout + 1000) {//print once a second
System.out.println("searching... at " + currentNodePos + ", considered " + numNodes + " nodes so far");
lastPrintout = System.currentTimeMillis();
}
if (goal.isInGoal(currentNodePos)) {
currentlyRunning = null;
displayChatMessageRaw("Took " + (System.nanoTime() / 1000000L - startTime) + "ms, " + numMovementsConsidered + " movements considered");
return Optional.of(new Path(startNode, currentNode, numNodes));
}
//long constructStart = System.nanoTime();
Movement[] possibleMovements = getConnectedPositions(currentNodePos, calcContext);//movement that we could take that start at currentNodePos, in random order
shuffle(possibleMovements);
//long constructEnd = System.nanoTime();
//System.out.println(constructEnd - constructStart);
for (Movement movementToGetToNeighbor : possibleMovements) {
if (movementToGetToNeighbor == null) {
continue;
}
BlockPos dest = movementToGetToNeighbor.getDest();
int chunkX = currentNodePos.getX() >> 4;
int chunkZ = currentNodePos.getZ() >> 4;
if (dest.getX() >> 4 != chunkX || dest.getZ() >> 4 != chunkZ) {
// only need to check if the destination is a loaded chunk if it's in a different chunk than the start of the movement
if (chunkProvider.getLoadedChunk(chunkX, chunkZ) == null) {
// see issue #106
if (cachedWorld == null || !cachedWorld.isCached(dest)) {
numEmptyChunk++;
continue;
BetterBlockPos dest = (BetterBlockPos) movementToGetToNeighbor.getDest();
boolean isPositionCached = false;
if (cache) {
if (CachedWorldProvider.INSTANCE.getCurrentWorld() != null) {
if (CachedWorldProvider.INSTANCE.getCurrentWorld().getBlockType(dest) != null) {
isPositionCached = true;
}
}
}
if (!isPositionCached && Minecraft.getMinecraft().world.getChunk(dest) instanceof EmptyChunk) {
numEmptyChunk++;
continue;
}
//long costStart = System.nanoTime();
// TODO cache cost
double actionCost = movementToGetToNeighbor.getCost(calcContext);
numMovementsConsidered++;
//long costEnd = System.nanoTime();
//System.out.println(movementToGetToNeighbor.getClass() + "" + (costEnd - costStart));
if (actionCost >= ActionCosts.COST_INF) {
continue;
}
@@ -142,14 +160,6 @@ public class AStarPathFinder extends AbstractNodeCostSearch implements Helper {
if (tentativeCost < 0) {
throw new IllegalStateException(movementToGetToNeighbor.getClass() + " " + movementToGetToNeighbor + " overflowed into negative " + actionCost + " " + neighbor.cost + " " + tentativeCost);
}
double improvementBy = neighbor.cost - tentativeCost;
// there are floating point errors caused by random combinations of traverse and diagonal over a flat area
// that means that sometimes there's a cost improvement of like 10 ^ -16
// it's not worth the time to update the costs, decrease-key the heap, potentially repropagate, etc
if (improvementBy < 0.01 && minimumImprovementRepropagation) {
// who cares about a hundredth of a tick? that's half a millisecond for crying out loud!
continue;
}
neighbor.previous = currentNode;
neighbor.previousMovement = movementToGetToNeighbor;
neighbor.cost = tentativeCost;
@@ -163,9 +173,6 @@ 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;
}
@@ -173,13 +180,6 @@ public class AStarPathFinder extends AbstractNodeCostSearch implements Helper {
}
}
}
if (cancelRequested) {
currentlyRunning = null;
return Optional.empty();
}
System.out.println(numMovementsConsidered + " movements considered");
System.out.println("Open set size: " + openSet.size());
System.out.println((int) (numNodes * 1.0 / ((System.nanoTime() / 1000000L - startTime) / 1000F)) + " nodes per second");
double bestDist = 0;
for (int i = 0; i < bestSoFar.length; i++) {
if (bestSoFar[i] == null) {
@@ -190,55 +190,51 @@ public class AStarPathFinder extends AbstractNodeCostSearch implements Helper {
bestDist = dist;
}
if (dist > MIN_DIST_PATH * MIN_DIST_PATH) { // square the comparison since distFromStartSq is squared
displayChatMessageRaw("Took " + (System.nanoTime() / 1000000L - startTime) + "ms, A* cost coefficient " + COEFFICIENTS[i] + ", " + numMovementsConsidered + " movements considered");
displayChatMessageRaw("A* cost coefficient " + COEFFICIENTS[i]);
if (COEFFICIENTS[i] >= 3) {
System.out.println("Warning: cost coefficient is greater than three! Probably means that");
System.out.println("the path I found is pretty terrible (like sneak-bridging for dozens of blocks)");
System.out.println("But I'm going to do it anyway, because yolo");
}
System.out.println("Path goes for " + Math.sqrt(dist) + " blocks");
System.out.println("Path goes for " + dist + " blocks");
currentlyRunning = null;
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 " + Math.sqrt(bestDist) + " blocks");
displayChatMessageRaw("Even with a cost coefficient of " + COEFFICIENTS[COEFFICIENTS.length - 1] + ", I couldn't get more than " + bestDist + " blocks =(");
displayChatMessageRaw("No path found =(");
currentlyRunning = null;
return Optional.empty();
}
public static Movement[] getConnectedPositions(BlockPos pos, CalculationContext calcContext) {
private static Movement[] getConnectedPositions(BetterBlockPos pos, CalculationContext calcContext) {
int x = pos.getX();
int y = pos.getY();
int z = pos.getZ();
BlockPos east = new BlockPos(x + 1, y, z);
BlockPos west = new BlockPos(x - 1, y, z);
BlockPos south = new BlockPos(x, y, z + 1);
BlockPos north = new BlockPos(x, y, z - 1);
BetterBlockPos east = new BetterBlockPos(x + 1, y, z);
BetterBlockPos west = new BetterBlockPos(x - 1, y, z);
BetterBlockPos south = new BetterBlockPos(x, y, z + 1);
BetterBlockPos north = new BetterBlockPos(x, y, z - 1);
return new Movement[]{
new MovementTraverse(pos, east),
new MovementTraverse(pos, west),
new MovementTraverse(pos, north),
new MovementTraverse(pos, south),
new MovementAscend(pos, new BlockPos(x + 1, y + 1, z)),
new MovementAscend(pos, new BlockPos(x - 1, y + 1, z)),
new MovementAscend(pos, new BlockPos(x, y + 1, z + 1)),
new MovementAscend(pos, new BlockPos(x, y + 1, z - 1)),
new MovementAscend(pos, new BetterBlockPos(x + 1, y + 1, z)),
new MovementAscend(pos, new BetterBlockPos(x - 1, y + 1, z)),
new MovementAscend(pos, new BetterBlockPos(x, y + 1, z + 1)),
new MovementAscend(pos, new BetterBlockPos(x, y + 1, z - 1)),
MovementHelper.generateMovementFallOrDescend(pos, east, calcContext),
MovementHelper.generateMovementFallOrDescend(pos, west, calcContext),
MovementHelper.generateMovementFallOrDescend(pos, north, calcContext),
MovementHelper.generateMovementFallOrDescend(pos, south, calcContext),
new MovementDownward(pos, new BlockPos(x, y - 1, z)),
new MovementDownward(pos, new BetterBlockPos(x, y - 1, z)),
new MovementDiagonal(pos, EnumFacing.NORTH, EnumFacing.WEST),
new MovementDiagonal(pos, EnumFacing.NORTH, EnumFacing.EAST),
new MovementDiagonal(pos, EnumFacing.SOUTH, EnumFacing.WEST),
new MovementDiagonal(pos, EnumFacing.SOUTH, EnumFacing.EAST),
new MovementPillar(pos, new BlockPos(x, y + 1, z)),
MovementParkour.calculate(pos, EnumFacing.NORTH),
MovementParkour.calculate(pos, EnumFacing.SOUTH),
MovementParkour.calculate(pos, EnumFacing.EAST),
MovementParkour.calculate(pos, EnumFacing.WEST),
new MovementPillar(pos, new BetterBlockPos(x, y + 1, z))
};
}

View File

@@ -15,14 +15,15 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.calc;
package baritone.bot.pathing.calc;
import baritone.behavior.impl.PathingBehavior;
import baritone.pathing.goals.Goal;
import baritone.pathing.path.IPath;
import baritone.bot.pathing.goals.Goal;
import baritone.bot.pathing.path.IPath;
import baritone.bot.utils.pathing.BetterBlockPos;
import net.minecraft.util.math.BlockPos;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
@@ -37,11 +38,11 @@ public abstract class AbstractNodeCostSearch implements IPathFinder {
*/
protected static AbstractNodeCostSearch currentlyRunning = null;
protected final BlockPos start;
protected final BetterBlockPos start;
protected final Goal goal;
private final HashMap<BlockPos, PathNode> map; // see issue #107
protected final Map<BetterBlockPos, PathNode> map;
protected PathNode startNode;
@@ -51,51 +52,34 @@ public abstract class AbstractNodeCostSearch implements IPathFinder {
private volatile boolean isFinished;
protected boolean cancelRequested;
/**
* This is really complicated and hard to explain. I wrote a comment in the old version of MineBot but it was so
* long it was easier as a Google Doc (because I could insert charts).
*
* @see <a href="https://docs.google.com/document/d/1WVHHXKXFdCR1Oz__KtK8sFqyvSwJN_H4lftkHFgmzlc/edit"></a>
*/
protected static final double[] COEFFICIENTS = {1.5, 2, 2.5, 3, 4, 5, 10}; // big TODO tune
protected static final double[] COEFFICIENTS = {1.25, 1.5, 2, 2.5, 3, 4, 5, 10}; // big TODO tune
/**
* If a path goes less than 5 blocks and doesn't make it to its goal, it's not worth considering.
*/
protected final static double MIN_DIST_PATH = 5;
AbstractNodeCostSearch(BlockPos start, Goal goal) {
this.start = new BlockPos(start.getX(), start.getY(), start.getZ());
this.start = new BetterBlockPos(start.getX(), start.getY(), start.getZ());
this.goal = goal;
this.map = new HashMap<>();
}
public void cancel() {
cancelRequested = true;
}
public synchronized Optional<IPath> calculate(long timeout) {
public synchronized Optional<IPath> calculate() {
if (isFinished) {
throw new IllegalStateException("Path Finder is currently in use, and cannot be reused!");
}
this.cancelRequested = false;
try {
Optional<IPath> 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);
}
}
Optional<IPath> path = calculate0();
isFinished = true;
return path;
}
protected abstract Optional<IPath> calculate0(long timeout);
protected abstract Optional<IPath> calculate0();
/**
* Determines the distance squared from the specified node to the start
@@ -120,19 +104,8 @@ public abstract class AbstractNodeCostSearch implements IPathFinder {
* @param pos The pos to lookup
* @return The associated node
*/
protected PathNode getNodeAtPosition(BlockPos pos) {
// see issue #107
PathNode node = map.get(pos);
if (node == null) {
node = new PathNode(pos, goal);
map.put(pos, node);
}
return node;
}
public static void forceCancel() {
PathingBehavior.INSTANCE.cancel();
currentlyRunning = null;
protected PathNode getNodeAtPosition(BetterBlockPos pos) {
return map.computeIfAbsent(pos, p -> new PathNode(p, goal));
}
@Override
@@ -142,20 +115,10 @@ public abstract class AbstractNodeCostSearch implements IPathFinder {
@Override
public Optional<IPath> bestPathSoFar() {
if (startNode == null || bestSoFar[0] == null) {
if (startNode == null || bestSoFar[0] == null)
return Optional.empty();
}
for (int i = 0; i < bestSoFar.length; i++) {
if (bestSoFar[i] == null) {
continue;
}
if (getDistFromStartSq(bestSoFar[i]) > MIN_DIST_PATH * MIN_DIST_PATH) { // square the comparison since distFromStartSq is squared
return Optional.of(new Path(startNode, bestSoFar[i], 0));
}
}
// instead of returning bestSoFar[0], be less misleading
// if it actually won't find any path, don't make them think it will by rendering a dark blue that will never actually happen
return Optional.empty();
return Optional.of(new Path(startNode, bestSoFar[0], 0));
}
@Override

View File

@@ -15,10 +15,10 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.calc;
package baritone.bot.pathing.calc;
import baritone.pathing.goals.Goal;
import baritone.pathing.path.IPath;
import baritone.bot.pathing.goals.Goal;
import baritone.bot.pathing.path.IPath;
import net.minecraft.util.math.BlockPos;
import java.util.Optional;
@@ -39,7 +39,7 @@ public interface IPathFinder {
*
* @return The final path
*/
Optional<IPath> calculate(long timeout);
Optional<IPath> calculate();
/**
* Intended to be called concurrently with calculatePath from a different thread to tell if it's finished yet

View File

@@ -15,11 +15,11 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.calc;
package baritone.bot.pathing.calc;
import baritone.pathing.movement.Movement;
import baritone.pathing.path.IPath;
import net.minecraft.util.math.BlockPos;
import baritone.bot.pathing.movement.Movement;
import baritone.bot.pathing.path.IPath;
import baritone.bot.utils.pathing.BetterBlockPos;
import net.minecraft.util.math.BlockPos;
import java.util.ArrayList;
@@ -37,18 +37,18 @@ class Path implements IPath {
/**
* The start position of this path
*/
final BlockPos start;
final BetterBlockPos start;
/**
* The end position of this path
*/
final BlockPos end;
final BetterBlockPos end;
/**
* The blocks on the path. Guaranteed that path.get(0) equals start and
* path.get(path.size()-1) equals end
*/
final List<BlockPos> path;
final List<BetterBlockPos> path;
final List<Movement> movements;
@@ -75,7 +75,7 @@ class Path implements IPath {
throw new IllegalStateException();
}
PathNode current = end;
LinkedList<BlockPos> tempPath = new LinkedList<>(); // Repeatedly inserting to the beginning of an arraylist is O(n^2)
LinkedList<BetterBlockPos> tempPath = new LinkedList<>(); // Repeatedly inserting to the beginning of an arraylist is O(n^2)
LinkedList<Movement> tempMovements = new LinkedList<>(); // Instead, do it into a linked list, then convert at the end
while (!current.equals(start)) {
tempPath.addFirst(current.pos);
@@ -122,7 +122,7 @@ class Path implements IPath {
}
@Override
public List<BlockPos> positions() {
public List<BetterBlockPos> positions() {
return Collections.unmodifiableList(path);
}
@@ -132,12 +132,12 @@ class Path implements IPath {
}
@Override
public BlockPos getSrc() {
public BetterBlockPos getSrc() {
return start;
}
@Override
public BlockPos getDest() {
public BetterBlockPos getDest() {
return end;
}
}

View File

@@ -15,23 +15,23 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.calc;
package baritone.bot.pathing.calc;
import baritone.pathing.goals.Goal;
import baritone.pathing.movement.Movement;
import net.minecraft.util.math.BlockPos;
import baritone.bot.pathing.goals.Goal;
import baritone.bot.pathing.movement.Movement;
import baritone.bot.utils.pathing.BetterBlockPos;
/**
* A node in the path, containing the cost and steps to get to it.
*
* @author leijurv
*/
public final class PathNode {
public class PathNode {
/**
* The position of this node
*/
final BlockPos pos;
final BetterBlockPos pos;
/**
* The goal it's going towards
@@ -78,7 +78,7 @@ public final class PathNode {
*/
public int heapPosition;
public PathNode(BlockPos pos, Goal goal) {
public PathNode(BetterBlockPos pos, Goal goal) {
this.pos = pos;
this.previous = null;
this.cost = Short.MAX_VALUE;
@@ -95,7 +95,7 @@ public final class PathNode {
*/
@Override
public int hashCode() {
return pos.hashCode() * 7 + 3;
throw new IllegalStateException();
}
@Override
@@ -103,9 +103,8 @@ public final class PathNode {
// GOTTA GO FAST
// ALL THESE CHECKS ARE FOR PEOPLE WHO WANT SLOW CODE
// SKRT SKRT
//if (obj == null || !(obj instanceof PathNode)) {
//if (obj == null || !(obj instanceof PathNode))
// return false;
//}
//final PathNode other = (PathNode) obj;
//return Objects.equals(this.pos, other.pos) && Objects.equals(this.goal, other.goal);

View File

@@ -15,9 +15,9 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.calc.openset;
package baritone.bot.pathing.calc.openset;
import baritone.pathing.calc.PathNode;
import baritone.bot.pathing.calc.PathNode;
import java.util.Arrays;
@@ -26,7 +26,7 @@ import java.util.Arrays;
*
* @author leijurv
*/
public final class BinaryHeapOpenSet implements IOpenSet {
public class BinaryHeapOpenSet implements IOpenSet {
/**
* The initial capacity of the heap (2^10)
@@ -52,45 +52,28 @@ public final class BinaryHeapOpenSet implements IOpenSet {
this.array = new PathNode[size];
}
public int size() {
return size;
}
@Override
public final void insert(PathNode value) {
public void insert(PathNode value) {
if (size >= array.length - 1) {
array = Arrays.copyOf(array, array.length * 2);
}
size++;
value.heapPosition = size;
array[size] = value;
update(value);
upHeap(size);
}
public void update(PathNode node) {
upHeap(node.heapPosition);
}
@Override
public final void update(PathNode val) {
int index = val.heapPosition;
int parentInd = index >>> 1;
double cost = val.combinedCost;
PathNode parentNode = array[parentInd];
while (index > 1 && parentNode.combinedCost > cost) {
array[index] = parentNode;
array[parentInd] = val;
val.heapPosition = parentInd;
parentNode.heapPosition = index;
index = parentInd;
parentInd = index >>> 1;
parentNode = array[parentInd];
}
}
@Override
public final boolean isEmpty() {
public boolean isEmpty() {
return size == 0;
}
@Override
public final PathNode removeLowest() {
public PathNode removeLowest() {
if (size == 0) {
throw new IllegalStateException();
}
@@ -108,13 +91,14 @@ public final class BinaryHeapOpenSet implements IOpenSet {
int smallerChild = 2;
double cost = val.combinedCost;
do {
int right = smallerChild + 1;
PathNode smallerChildNode = array[smallerChild];
double smallerChildCost = smallerChildNode.combinedCost;
if (smallerChild < size) {
PathNode rightChildNode = array[smallerChild + 1];
if (right <= size) {
PathNode rightChildNode = array[right];
double rightChildCost = rightChildNode.combinedCost;
if (smallerChildCost > rightChildCost) {
smallerChild++;
smallerChild = right;
smallerChildCost = rightChildCost;
smallerChildNode = rightChildNode;
}
@@ -127,7 +111,24 @@ public final class BinaryHeapOpenSet implements IOpenSet {
val.heapPosition = smallerChild;
smallerChildNode.heapPosition = index;
index = smallerChild;
} while ((smallerChild <<= 1) <= size);
smallerChild = index << 1;
} while (smallerChild <= size);
return result;
}
private void upHeap(int index) {
int parentInd = index >>> 1;
PathNode val = array[index];
double cost = val.combinedCost;
PathNode parentNode = array[parentInd];
while (index > 1 && parentNode.combinedCost > cost) {
array[index] = parentNode;
array[parentInd] = val;
val.heapPosition = parentInd;
parentNode.heapPosition = index;
index = parentInd;
parentInd = index >>> 1;
parentNode = array[parentInd];
}
}
}

View File

@@ -15,9 +15,9 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.calc.openset;
package baritone.bot.pathing.calc.openset;
import baritone.pathing.calc.PathNode;
import baritone.bot.pathing.calc.PathNode;
/**
* An open set for A* or similar graph search algorithm

View File

@@ -15,18 +15,17 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.calc.openset;
package baritone.bot.pathing.calc.openset;
import baritone.pathing.calc.PathNode;
import baritone.bot.pathing.calc.PathNode;
/**
* A linked list implementation of an open set. This is the original implementation from MineBot.
* It has incredibly fast insert performance, at the cost of O(n) removeLowest.
* It sucks. BinaryHeapOpenSet results in more than 10x more nodes considered in 4 seconds.
*
* @author leijurv
*/
class LinkedListOpenSet implements IOpenSet {
public class LinkedListOpenSet implements IOpenSet {
private Node first = null;
@Override

View File

@@ -15,9 +15,9 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.goals;
package baritone.bot.pathing.goals;
import baritone.pathing.movement.ActionCosts;
import baritone.bot.pathing.movement.ActionCosts;
import net.minecraft.util.math.BlockPos;
/**

View File

@@ -15,9 +15,8 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.goals;
package baritone.bot.pathing.goals;
import baritone.utils.interfaces.IGoalRenderPos;
import net.minecraft.util.math.BlockPos;
/**
@@ -25,7 +24,7 @@ import net.minecraft.util.math.BlockPos;
*
* @author leijurv
*/
public class GoalBlock implements Goal, IGoalRenderPos {
public class GoalBlock implements Goal {
/**
* The X block position of this goal
@@ -88,12 +87,23 @@ public class GoalBlock implements Goal, IGoalRenderPos {
}
public static double calculate(double xDiff, int yDiff, double zDiff) {
double pythaDist = Math.sqrt(xDiff * xDiff + zDiff * zDiff);
double heuristic = 0;
if (pythaDist < MAX) {//if we are more than MAX away, ignore the Y coordinate. It really doesn't matter how far away your Y coordinate is if you X coordinate is 1000 blocks away.
//as we get closer, slowly reintroduce the Y coordinate as a heuristic cost
double multiplier;
if (pythaDist < MIN) {
multiplier = 1;
} else {
multiplier = 1 - (pythaDist - MIN) / (MAX - MIN);
}
// if yDiff is 1 that means that pos.getY()-this.y==1 which means that we're 1 block below where we should be
// therefore going from 0,0,0 to a GoalYLevel of pos.getY()-this.y is accurate
heuristic += new GoalYLevel(yDiff).heuristic(new BlockPos(0, 0, 0));
// if yDiff is 1 that means that pos.getY()-this.y==1 which means that we're 1 block below where we should be
// therefore going from 0,0,0 to a GoalYLevel of pos.getY()-this.y is accurate
heuristic += new GoalYLevel(yDiff).heuristic(new BlockPos(0, 0, 0));
heuristic *= multiplier;
}
//use the pythagorean and manhattan mixture from GoalXZ
heuristic += GoalXZ.calculate(xDiff, zDiff);
return heuristic;

View File

@@ -15,7 +15,7 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.goals;
package baritone.bot.pathing.goals;
import java.util.Arrays;
import java.util.Collection;

View File

@@ -15,29 +15,27 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.event.events;
package baritone.bot.pathing.goals;
import baritone.api.event.events.type.EventState;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
/**
* @author Brady
* @since 8/21/2018
* Don't get into the block, but get directly adjacent to it. Useful for chests.
*
* @author avecowa
*/
public final class PlayerUpdateEvent {
public class GoalGetToBlock extends GoalComposite {
/**
* The state of the event
*/
private final EventState state;
public PlayerUpdateEvent(EventState state) {
this.state = state;
public GoalGetToBlock(BlockPos pos) {
super(adjacentBlocks(pos));
}
/**
* @return The state of the event
*/
public final EventState getState() {
return this.state;
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;
}
}

View File

@@ -15,7 +15,7 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.goals;
package baritone.bot.pathing.goals;
import java.util.Arrays;
import net.minecraft.util.math.BlockPos;

View File

@@ -15,9 +15,8 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.goals;
package baritone.bot.pathing.goals;
import baritone.utils.interfaces.IGoalRenderPos;
import net.minecraft.util.math.BlockPos;
/**
@@ -26,7 +25,7 @@ import net.minecraft.util.math.BlockPos;
*
* @author leijurv
*/
public class GoalTwoBlocks implements Goal, IGoalRenderPos {
public class GoalTwoBlocks implements Goal {
/**
* The X block position of this goal
@@ -69,10 +68,6 @@ public class GoalTwoBlocks implements Goal, IGoalRenderPos {
return GoalBlock.calculate(xDiff, yDiff, zDiff);
}
public BlockPos getGoalPos() {
return new BlockPos(x, y, z);
}
@Override
public String toString() {
return "GoalTwoBlocks{x=" + x + ",y=" + y + ",z=" + z + "}";

View File

@@ -15,12 +15,11 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.goals;
package baritone.bot.pathing.goals;
import baritone.Baritone;
import baritone.utils.Utils;
import baritone.bot.Baritone;
import baritone.bot.utils.Utils;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
/**
@@ -65,9 +64,6 @@ public class GoalXZ implements Goal {
}
public static double calculate(double xDiff, double zDiff) {
if (Baritone.settings().pythagoreanMetric.get()) {
return Math.sqrt(xDiff * xDiff + zDiff * zDiff) * Baritone.settings().costHeuristic.get();
}
//This is a combination of pythagorean and manhattan distance
//It takes into account the fact that pathing can either walk diagonally or forwards
@@ -89,9 +85,9 @@ public class GoalXZ implements Goal {
}
public static GoalXZ fromDirection(Vec3d origin, float yaw, double distance) {
float theta = (float) Utils.degToRad(yaw);
double x = origin.x - MathHelper.sin(theta) * distance;
double z = origin.z + MathHelper.cos(theta) * distance;
double theta = Utils.degToRad(yaw);
double x = origin.x - Math.sin(theta) * distance;
double z = origin.z + Math.cos(theta) * distance;
return new GoalXZ((int) x, (int) z);
}

View File

@@ -15,7 +15,7 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.goals;
package baritone.bot.pathing.goals;
import net.minecraft.util.math.BlockPos;
@@ -44,7 +44,7 @@ public class GoalYLevel implements Goal {
public double heuristic(BlockPos pos) {
if (pos.getY() > level) {
// need to descend
return FALL_N_BLOCKS_COST[2] / 2 * (pos.getY() - level);
return FALL_N_BLOCKS_COST[pos.getY() - level];
}
if (pos.getY() < level) {
// need to ascend

View File

@@ -15,7 +15,7 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.movement;
package baritone.bot.pathing.movement;
public interface ActionCosts extends ActionCostsButOnlyTheOnesThatMakeMickeyDieInside {
@@ -24,8 +24,7 @@ public interface ActionCosts extends ActionCostsButOnlyTheOnesThatMakeMickeyDieI
*/
double WALK_ONE_BLOCK_COST = 20 / 4.317; // 4.633
double WALK_ONE_IN_WATER_COST = 20 / 2.2;
double WALK_ONE_OVER_SOUL_SAND_COST = WALK_ONE_BLOCK_COST * 0.5; // 0.4 in BlockSoulSand but effectively about half
double SPRINT_ONE_OVER_SOUL_SAND_COST = WALK_ONE_OVER_SOUL_SAND_COST / 0.75;
double WALK_ONE_OVER_SOUL_SAND_COST = WALK_ONE_IN_WATER_COST; // TODO issue #7
double LADDER_UP_ONE_COST = 20 / 2.35;
double LADDER_DOWN_ONE_COST = 20 / 3.0;
double SNEAK_ONE_BLOCK_COST = 20 / 1.3;

View File

@@ -15,7 +15,7 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.movement;
package baritone.bot.pathing.movement;
public interface ActionCostsButOnlyTheOnesThatMakeMickeyDieInside {
double[] FALL_N_BLOCKS_COST = generateFallNBlocksCost();

View File

@@ -15,11 +15,11 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.movement;
package baritone.bot.pathing.movement;
import baritone.Baritone;
import baritone.utils.Helper;
import baritone.utils.ToolSet;
import baritone.bot.Baritone;
import baritone.bot.utils.Helper;
import baritone.bot.utils.ToolSet;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
@@ -38,22 +38,19 @@ public class CalculationContext implements Helper {
private final boolean canSprint;
private final double placeBlockCost;
private final boolean allowBreak;
private final int maxFallHeightNoWater;
private final int maxFallHeightBucket;
public CalculationContext() {
this(new ToolSet());
}
public CalculationContext(ToolSet toolSet) {
player().setSprinting(true);
this.toolSet = toolSet;
this.hasThrowaway = Baritone.settings().allowPlace.get() && MovementHelper.throwaway(false);
this.hasThrowaway = Baritone.settings().allowPlaceThrowaway.get() && MovementHelper.throwaway(false);
this.hasWaterBucket = Baritone.settings().allowWaterBucketFall.get() && InventoryPlayer.isHotbar(player().inventory.getSlotFor(STACK_BUCKET_WATER)) && !world().provider.isNether();
this.canSprint = Baritone.settings().allowSprint.get() && player().getFoodStats().getFoodLevel() > 6;
this.placeBlockCost = Baritone.settings().blockPlacementPenalty.get();
this.allowBreak = Baritone.settings().allowBreak.get();
this.maxFallHeightNoWater = Baritone.settings().maxFallHeightNoWater.get();
this.maxFallHeightBucket = Baritone.settings().maxFallHeightBucket.get();
// why cache these things here, why not let the movements just get directly from settings?
// because if some movements are calculated one way and others are calculated another way,
// then you get a wildly inconsistent path that isn't optimal for either scenario.
@@ -82,13 +79,4 @@ public class CalculationContext implements Helper {
public boolean allowBreak() {
return allowBreak;
}
public int maxFallHeightNoWater() {
return maxFallHeightNoWater;
}
public int maxFallHeightBucket() {
return maxFallHeightBucket;
}
}

View File

@@ -15,29 +15,32 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.movement;
package baritone.bot.pathing.movement;
import baritone.Baritone;
import baritone.behavior.impl.LookBehavior;
import baritone.behavior.impl.LookBehaviorUtils;
import baritone.pathing.movement.MovementState.MovementStatus;
import baritone.utils.*;
import baritone.bot.Baritone;
import baritone.bot.behavior.impl.LookBehavior;
import baritone.bot.behavior.impl.LookBehaviorUtils;
import baritone.bot.pathing.movement.MovementState.MovementStatus;
import baritone.bot.pathing.movement.movements.MovementDownward;
import baritone.bot.pathing.movement.movements.MovementPillar;
import baritone.bot.pathing.movement.movements.MovementTraverse;
import baritone.bot.utils.BlockStateInterface;
import baritone.bot.utils.Helper;
import baritone.bot.utils.Rotation;
import baritone.bot.utils.ToolSet;
import net.minecraft.block.Block;
import net.minecraft.block.BlockLadder;
import net.minecraft.block.BlockVine;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static baritone.utils.InputOverrideHandler.Input;
import static baritone.bot.utils.InputOverrideHandler.Input;
public abstract class Movement implements Helper, MovementHelper {
protected static final EnumFacing[] HORIZONTALS = {EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.WEST};
private MovementState currentState = new MovementState().setStatus(MovementStatus.PREPPING);
protected final BlockPos src;
@@ -50,35 +53,42 @@ public abstract class Movement implements Helper, MovementHelper {
protected final BlockPos[] positionsToBreak;
/**
* The position where we need to place a block before this movement can ensue
* The positions where we need to place a block before this movement can ensue
*/
protected final BlockPos positionToPlace;
private boolean didBreakLastTick;
protected final BlockPos[] positionsToPlace;
private Double cost;
protected Movement(BlockPos src, BlockPos dest, BlockPos[] toBreak, BlockPos toPlace) {
protected Movement(BlockPos src, BlockPos dest, BlockPos[] toBreak, BlockPos[] toPlace) {
this.src = src;
this.dest = dest;
this.positionsToBreak = toBreak;
this.positionToPlace = toPlace;
this.positionsToPlace = toPlace;
}
protected Movement(BlockPos src, BlockPos dest, BlockPos[] toBreak) {
this(src, dest, toBreak, null);
protected Movement(BlockPos src, BlockPos dest, BlockPos[] toBreak, BlockPos[] toPlace, Vec3d rotationTarget) {
this(src, dest, toBreak, toPlace);
}
public double getCost(CalculationContext context) {
if (cost == null) {
if (context == null) {
if (context == null)
context = new CalculationContext();
}
cost = calculateCost(context);
cost = calculateCost0(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() {
@@ -86,14 +96,6 @@ public abstract class Movement implements Helper, MovementHelper {
return getCost(null);
}
protected void override(double cost) {
this.cost = cost;
}
public double calculateCostWithoutCaching() {
return calculateCost(new CalculationContext());
}
/**
* Handles the execution of the latest Movement
* State, and offers a Status to the calling class.
@@ -101,74 +103,40 @@ public abstract class Movement implements Helper, MovementHelper {
* @return Status
*/
public MovementStatus update() {
player().setSprinting(false);
MovementState latestState = updateState(currentState);
if (BlockStateInterface.isLiquid(playerFeet())) {
latestState.setInput(Input.JUMP, true);
}
// If the movement target has to force the new rotations, or we aren't using silent move, then force the rotations
latestState.getTarget().getRotation().ifPresent(rotation ->
LookBehavior.INSTANCE.updateTarget(
rotation,
latestState.getTarget().hasToForceRotations()));
latestState.getTarget().getRotation().ifPresent(LookBehavior.INSTANCE::updateTarget);
// TODO: calculate movement inputs from latestState.getGoal().position
// latestState.getTarget().position.ifPresent(null); NULL CONSUMER REALLY SHOULDN'T BE THE FINAL THING YOU SHOULD REALLY REPLACE THIS WITH ALMOST ACTUALLY ANYTHING ELSE JUST PLEASE DON'T LEAVE IT AS IT IS THANK YOU KANYE
this.didBreakLastTick = false;
latestState.getInputStates().forEach((input, forced) -> {
RayTraceResult trace = mc.objectMouseOver;
boolean isBlockTrace = trace != null && trace.typeOfHit == RayTraceResult.Type.BLOCK;
boolean isLeftClick = forced && input == Input.CLICK_LEFT;
// If we're forcing left click, we're in a gui screen, and we're looking
// at a block, break the block without a direct game input manipulation.
if (mc.currentScreen != null && isLeftClick && isBlockTrace) {
BlockBreakHelper.tryBreakBlock(trace.getBlockPos(), trace.sideHit);
this.didBreakLastTick = true;
return;
}
Baritone.INSTANCE.getInputOverrideHandler().setInputForceState(input, forced);
});
latestState.getInputStates().replaceAll((input, forced) -> false);
if (!this.didBreakLastTick) {
BlockBreakHelper.stopBreakingBlock();
}
currentState = latestState;
if (isFinished()) {
if (isFinished())
onFinish(latestState);
}
return currentState.getStatus();
}
protected boolean prepared(MovementState state) {
if (state.getStatus() == MovementStatus.WAITING) {
if (state.getStatus() == MovementStatus.WAITING)
return true;
}
boolean somethingInTheWay = false;
for (BlockPos blockPos : positionsToBreak) {
if (!MovementHelper.canWalkThrough(blockPos)) {
somethingInTheWay = true;
Optional<Rotation> reachable = LookBehaviorUtils.reachable(blockPos);
if (reachable.isPresent()) {
MovementHelper.switchToBestToolFor(BlockStateInterface.get(blockPos));
state.setTarget(new MovementState.MovementTarget(reachable.get(), true)).setInput(Input.CLICK_LEFT, true);
player().inventory.currentItem = new ToolSet().getBestSlot(BlockStateInterface.get(blockPos));
state.setTarget(new MovementState.MovementTarget(reachable.get())).setInput(Input.CLICK_LEFT, true);
return false;
}
//get rekt minecraft
//i'm doing it anyway
//i dont care if theres snow in the way!!!!!!!
//you dont own me!!!!
state.setTarget(new MovementState.MovementTarget(Utils.calcRotationFromVec3d(mc.player.getPositionEyes(1.0F),
Utils.getBlockPosCenter(blockPos)), true)
).setInput(InputOverrideHandler.Input.CLICK_LEFT, true);
return false;
}
}
if (somethingInTheWay) {
@@ -200,6 +168,7 @@ public abstract class Movement implements Helper, MovementHelper {
public void onFinish(MovementState state) {
state.getInputStates().replaceAll((input, forced) -> false);
state.getInputStates().forEach((input, forced) -> Baritone.INSTANCE.getInputOverrideHandler().setInputForceState(input, forced));
state.setStatus(MovementStatus.SUCCESS);
}
public void cancel() {
@@ -208,58 +177,41 @@ public abstract class Movement implements Helper, MovementHelper {
currentState.setStatus(MovementStatus.CANCELED);
}
public void reset() {
currentState = new MovementState().setStatus(MovementStatus.PREPPING);
}
public double getTotalHardnessOfBlocksToBreak(CalculationContext ctx) {
if (positionsToBreak.length == 0) {
return 0;
}
if (positionsToBreak.length == 1) {
return MovementHelper.getMiningDurationTicks(ctx, positionsToBreak[0], true);
}
int firstColumnX = positionsToBreak[0].getX();
int firstColumnZ = positionsToBreak[0].getZ();
int firstColumnMaxY = positionsToBreak[0].getY();
int firstColumnMaximalIndex = 0;
boolean hasSecondColumn = false;
int secondColumnX = -1;
int secondColumnZ = -1;
int secondColumnMaxY = -1;
int secondColumnMaximalIndex = -1;
for (int i = 0; i < positionsToBreak.length; i++) {
BlockPos pos = positionsToBreak[i];
if (pos.getX() == firstColumnX && pos.getZ() == firstColumnZ) {
if (pos.getY() > firstColumnMaxY) {
firstColumnMaxY = pos.getY();
firstColumnMaximalIndex = i;
}
} else {
if (!hasSecondColumn || (pos.getX() == secondColumnX && pos.getZ() == secondColumnZ)) {
if (hasSecondColumn) {
if (pos.getY() > secondColumnMaxY) {
secondColumnMaxY = pos.getY();
secondColumnMaximalIndex = i;
}
} else {
hasSecondColumn = true;
secondColumnX = pos.getX();
secondColumnZ = pos.getZ();
secondColumnMaxY = pos.getY();
secondColumnMaximalIndex = i;
}
} else {
throw new IllegalStateException("I literally have no idea " + Arrays.asList(positionsToBreak));
}
/*
double sum = 0;
HashSet<BlockPos> toBreak = new HashSet();
for (BlockPos positionsToBreak1 : positionsToBreak) {
toBreak.add(positionsToBreak1);
if (this instanceof ActionFall) {//if we are digging straight down, assume we have already broken the sand above us
continue;
}
BlockPos tmp = positionsToBreak1.up();
while (canFall(tmp)) {
toBreak.add(tmp);
tmp = tmp.up();
}
}
double sum = 0;
for (int i = 0; i < positionsToBreak.length; i++) {
sum += MovementHelper.getMiningDurationTicks(ctx, positionsToBreak[i], firstColumnMaximalIndex == i || secondColumnMaximalIndex == i);
for (BlockPos pos : toBreak) {
sum += getHardness(ts, Baritone.get(pos), pos);
if (sum >= COST_INF) {
break;
return COST_INF;
}
}
if (!Baritone.allowBreakOrPlace || !Baritone.hasThrowaway) {
for (int i = 0; i < blocksToPlace.length; i++) {
if (!canWalkOn(positionsToPlace[i])) {
return COST_INF;
}
}
}*/
//^ the above implementation properly deals with falling blocks, TODO integrate
double sum = 0;
for (BlockPos pos : positionsToBreak) {
sum += MovementHelper.getMiningDurationTicks(ctx, pos);
if (sum >= COST_INF) {
return COST_INF;
}
}
return sum;
@@ -273,32 +225,23 @@ public abstract class Movement implements Helper, MovementHelper {
* @return
*/
public MovementState updateState(MovementState state) {
if (!prepared(state)) {
if (!prepared(state))
return state.setStatus(MovementStatus.PREPPING);
} else if (state.getStatus() == MovementStatus.PREPPING) {
else if (state.getStatus() == MovementStatus.PREPPING) {
state.setStatus(MovementStatus.WAITING);
}
if (state.getStatus() == MovementStatus.WAITING) {
state.setStatus(MovementStatus.RUNNING);
}
return state;
}
public BlockPos getDirection() {
return getDest().subtract(getSrc());
}
public ArrayList<BlockPos> toBreakCached = null;
public ArrayList<BlockPos> toPlaceCached = null;
public ArrayList<BlockPos> toWalkIntoCached = null;
public List<BlockPos> toBreakCached = null;
public List<BlockPos> toPlaceCached = null;
public List<BlockPos> toWalkIntoCached = null;
public List<BlockPos> toBreak() {
public ArrayList<BlockPos> toBreak() {
if (toBreakCached != null) {
return toBreakCached;
}
List<BlockPos> result = new ArrayList<>();
ArrayList<BlockPos> result = new ArrayList<>();
for (BlockPos positionToBreak : positionsToBreak) {
if (!MovementHelper.canWalkThrough(positionToBreak)) {
result.add(positionToBreak);
@@ -308,19 +251,21 @@ public abstract class Movement implements Helper, MovementHelper {
return result;
}
public List<BlockPos> toPlace() {
public ArrayList<BlockPos> toPlace() {
if (toPlaceCached != null) {
return toPlaceCached;
}
List<BlockPos> result = new ArrayList<>();
if (positionToPlace != null && !MovementHelper.canWalkOn(positionToPlace)) {
result.add(positionToPlace);
ArrayList<BlockPos> result = new ArrayList<>();
for (BlockPos positionToBreak : positionsToPlace) {
if (!MovementHelper.canWalkOn(positionToBreak)) {
result.add(positionToBreak);
}
}
toPlaceCached = result;
return result;
}
public List<BlockPos> toWalkInto() { // overridden by movementdiagonal
public ArrayList<BlockPos> toWalkInto() { // overridden by movementdiagonal
if (toWalkIntoCached == null) {
toWalkIntoCached = new ArrayList<>();
}

View File

@@ -0,0 +1,302 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package baritone.bot.pathing.movement;
import baritone.bot.Baritone;
import baritone.bot.behavior.impl.LookBehaviorUtils;
import baritone.bot.pathing.movement.MovementState.MovementTarget;
import baritone.bot.pathing.movement.movements.MovementDescend;
import baritone.bot.pathing.movement.movements.MovementFall;
import baritone.bot.utils.*;
import net.minecraft.block.*;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.entity.Entity;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import java.util.Optional;
/**
* Static helpers for cost calculation
*
* @author leijurv
*/
public interface MovementHelper extends ActionCosts, Helper {
static boolean avoidBreaking(BlockPos pos, IBlockState state) {
Block b = state.getBlock();
BlockPos below = new BlockPos(pos.getX(), pos.getY() - 1, pos.getZ());
return Blocks.ICE.equals(b) // ice becomes water, and water can mess up the path
|| b instanceof BlockSilverfish
|| BlockStateInterface.isLiquid(new BlockPos(pos.getX(), pos.getY() + 1, pos.getZ()))//don't break anything touching liquid on any side
|| BlockStateInterface.isLiquid(new BlockPos(pos.getX() + 1, pos.getY(), pos.getZ()))
|| BlockStateInterface.isLiquid(new BlockPos(pos.getX() - 1, pos.getY(), pos.getZ()))
|| BlockStateInterface.isLiquid(new BlockPos(pos.getX(), pos.getY(), pos.getZ() + 1))
|| BlockStateInterface.isLiquid(new BlockPos(pos.getX(), pos.getY(), pos.getZ() - 1))
|| (!(b instanceof BlockLilyPad && BlockStateInterface.isWater(below)) && BlockStateInterface.isLiquid(below));//if it's a lilypad above water, it's ok to break, otherwise don't break if its liquid
}
/**
* Can I walk through this block? e.g. air, saplings, torches, etc
*
* @param pos
* @return
*/
static boolean canWalkThrough(BlockPos pos) {
return canWalkThrough(pos, BlockStateInterface.get(pos));
}
static boolean canWalkThrough(BlockPos pos, IBlockState state) {
Block block = state.getBlock();
if (block instanceof BlockLilyPad
|| block instanceof BlockFire
|| block instanceof BlockTripWire
|| block instanceof BlockWeb
|| block instanceof BlockEndPortal) {//you can't actually walk through a lilypad from the side, and you shouldn't walk through fire
return false;
}
if (BlockStateInterface.isFlowing(state) || BlockStateInterface.isLiquid(pos.up())) {
return false; // Don't walk through flowing liquids
}
if (block instanceof BlockDoor) {
return true; // we can just open the door
}
return block.isPassable(mc.world, pos);
}
static boolean isDoorPassable(BlockPos doorPos, BlockPos playerPos) {
IBlockState door = BlockStateInterface.get(doorPos);
if (!(door.getBlock() instanceof BlockDoor)) {
return true;
}
String facing = door.getValue(BlockDoor.FACING).getName();
boolean open = door.getValue(BlockDoor.OPEN).booleanValue();
/**
* yes this is dumb
* change it if you want
*/
String playerFacing = "";
if (playerPos.equals(doorPos)) {
return false;
}
if (playerPos.north().equals(doorPos) || playerPos.south().equals(doorPos)) {
playerFacing = "northsouth";
} else if (playerPos.east().equals(doorPos) || playerPos.west().equals(doorPos)) {
playerFacing = "eastwest";
} else {
return true;
}
if (facing == "north" || facing == "south") {
if (open) {
return playerFacing == "northsouth";
} else {
return playerFacing == "eastwest";
}
} else {
if (open) {
return playerFacing == "eastwest";
} else {
return playerFacing == "northsouth";
}
}
}
static boolean avoidWalkingInto(Block block) {
return BlockStateInterface.isLava(block)
|| block instanceof BlockCactus
|| block instanceof BlockFire
|| block instanceof BlockEndPortal
|| block instanceof BlockWeb;
}
/**
* Can I walk on this block without anything weird happening like me falling
* through? Includes water because we know that we automatically jump on
* water
*
* @return
*/
static boolean canWalkOn(BlockPos pos, IBlockState state) {
Block block = state.getBlock();
if (block instanceof BlockLadder || block instanceof BlockVine) { // TODO reconsider this
return true;
}
if (block instanceof BlockAir) {
return false;
}
if (BlockStateInterface.isWater(block)) {
return BlockStateInterface.isWater(pos.up()); // You can only walk on water if there is water above it
}
if (Blocks.MAGMA.equals(block)) {
return false;
}
return state.isBlockNormalCube() && !BlockStateInterface.isLava(block);
}
static boolean canWalkOn(BlockPos pos) {
return canWalkOn(pos, BlockStateInterface.get(pos));
}
static boolean canFall(BlockPos pos) {
return BlockStateInterface.get(pos).getBlock() instanceof BlockFalling;
}
static double getMiningDurationTicks(CalculationContext context, BlockPos position) {
IBlockState state = BlockStateInterface.get(position);
return getMiningDurationTicks(context, position, state);
}
static double getMiningDurationTicks(CalculationContext context, BlockPos position, IBlockState state) {
Block block = state.getBlock();
if (!block.equals(Blocks.AIR) && !canWalkThrough(position, state)) { // TODO is the air check really necessary? Isn't air canWalkThrough?
if (!context.allowBreak()) {
return COST_INF;
}
if (avoidBreaking(position, state)) {
return COST_INF;
}
double m = Blocks.CRAFTING_TABLE.equals(block) ? 10 : 1; // TODO see if this is still necessary. it's from MineBot when we wanted to penalize breaking its crafting table
return m / context.getToolSet().getStrVsBlock(state, position);
}
return 0;
}
/**
* The entity the player is currently looking at
*
* @return the entity object
*/
static Optional<Entity> whatEntityAmILookingAt() {
if (mc.objectMouseOver != null && mc.objectMouseOver.typeOfHit == RayTraceResult.Type.ENTITY) {
return Optional.of(mc.objectMouseOver.entityHit);
}
return Optional.empty();
}
/**
* AutoTool
*/
static void switchToBestTool() {
LookBehaviorUtils.getSelectedBlock().ifPresent(pos -> {
IBlockState state = BlockStateInterface.get(pos);
if (state.getBlock().equals(Blocks.AIR)) {
return;
}
switchToBestToolFor(state);
});
}
/**
* AutoTool for a specific block
*
* @param b the blockstate to mine
*/
static void switchToBestToolFor(IBlockState b) {
switchToBestToolFor(b, new ToolSet());
}
/**
* AutoTool for a specific block with precomputed ToolSet data
*
* @param b the blockstate to mine
* @param ts previously calculated ToolSet
*/
static void switchToBestToolFor(IBlockState b, ToolSet ts) {
mc.player.inventory.currentItem = ts.getBestSlot(b);
}
static boolean throwaway(boolean select) {
EntityPlayerSP p = Minecraft.getMinecraft().player;
NonNullList<ItemStack> inv = p.inventory.mainInventory;
for (byte i = 0; i < 9; i++) {
ItemStack item = inv.get(i);
// this usage of settings() is okay because it's only called once during pathing
// (while creating the CalculationContext at the very beginning)
// and then it's called during execution
// since this function is never called during cost calculation, we don't need to migrate
// acceptableThrowawayItems to the CalculationContext
if (Baritone.settings().acceptableThrowawayItems.get().contains(item.getItem())) {
if (select) {
p.inventory.currentItem = i;
}
return true;
}
}
return false;
}
static void moveTowards(MovementState state, BlockPos pos) {
state.setTarget(new MovementTarget(new Rotation(Utils.calcRotationFromVec3d(mc.player.getPositionEyes(1.0F),
Utils.getBlockPosCenter(pos),
new Rotation(mc.player.rotationYaw, mc.player.rotationPitch)).getFirst(), mc.player.rotationPitch))
).setInput(InputOverrideHandler.Input.MOVE_FORWARD, true);
}
static Movement generateMovementFallOrDescend(BlockPos pos, BlockPos dest, CalculationContext calcContext) {
// A
//SA
// B
// B
// C
// D
//if S is where you start, both of B need to be air for a movementfall
//A is plausibly breakable by either descend or fall
//C, D, etc determine the length of the fall
for (int i = 1; i < 3; i++) {
if (!canWalkThrough(dest.down(i))) {
//if any of these two (B in the diagram) aren't air
//have to do a descend, because fall is impossible
//this doesn't guarantee descend is possible, it just guarantees fall is impossible
return new MovementDescend(pos, dest.down()); // standard move out by 1 and descend by 1
}
}
// we're clear for a fall 2
// let's see how far we can fall
for (int fallHeight = 3; true; fallHeight++) {
BlockPos onto = dest.down(fallHeight);
if (onto.getY() < 0) {
break;
}
IBlockState ontoBlock = BlockStateInterface.get(onto);
if (BlockStateInterface.isWater(ontoBlock.getBlock())) {
return new MovementFall(pos, onto);
}
if (canWalkThrough(onto, ontoBlock)) {
continue;
}
if (canWalkOn(onto, ontoBlock)) {
if (calcContext.hasWaterBucket() || fallHeight <= 4) {
// fallHeight = 4 means onto.up() is 3 blocks down, which is the max
return new MovementFall(pos, onto.up());
} else {
return null;
}
}
break;
}
return null;
}
}

View File

@@ -15,10 +15,10 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.movement;
package baritone.bot.pathing.movement;
import baritone.utils.InputOverrideHandler.Input;
import baritone.utils.Rotation;
import baritone.bot.utils.InputOverrideHandler.Input;
import baritone.bot.utils.Rotation;
import net.minecraft.util.math.Vec3d;
import java.util.HashMap;
@@ -93,29 +93,21 @@ public class MovementState {
*/
public Rotation rotation;
/**
* Whether or not this target must force rotations.
* <p>
* {@code true} if we're trying to place or break blocks, {@code false} if we're trying to look at the movement location
*/
private boolean forceRotations;
public MovementTarget() {
this(null, null, false);
this(null, null);
}
public MovementTarget(Vec3d position) {
this(position, null, false);
this(position, null);
}
public MovementTarget(Rotation rotation, boolean forceRotations) {
this(null, rotation, forceRotations);
public MovementTarget(Rotation rotation) {
this(null, rotation);
}
public MovementTarget(Vec3d position, Rotation rotation, boolean forceRotations) {
public MovementTarget(Vec3d position, Rotation rotation) {
this.position = position;
this.rotation = rotation;
this.forceRotations = forceRotations;
}
public final Optional<Vec3d> getPosition() {
@@ -125,9 +117,5 @@ public class MovementState {
public final Optional<Rotation> getRotation() {
return Optional.ofNullable(this.rotation);
}
public boolean hasToForceRotations() {
return this.forceRotations;
}
}
}

View File

@@ -0,0 +1,173 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package baritone.bot.pathing.movement.movements;
import baritone.bot.behavior.impl.LookBehaviorUtils;
import baritone.bot.pathing.movement.CalculationContext;
import baritone.bot.pathing.movement.Movement;
import baritone.bot.pathing.movement.MovementHelper;
import baritone.bot.pathing.movement.MovementState;
import baritone.bot.pathing.movement.MovementState.MovementStatus;
import baritone.bot.utils.BlockStateInterface;
import baritone.bot.utils.InputOverrideHandler;
import baritone.bot.utils.Utils;
import net.minecraft.block.Block;
import net.minecraft.block.BlockFalling;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.init.Blocks;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import java.util.Objects;
public class MovementAscend extends Movement {
private BlockPos[] against = new BlockPos[3];
private int ticksWithoutPlacement = 0;
public MovementAscend(BlockPos src, BlockPos dest) {
super(src, dest, new BlockPos[]{dest, src.up(2), dest.up()}, new BlockPos[]{dest.down()});
BlockPos placementLocation = positionsToPlace[0]; // dest.down()
int i = 0;
if (!placementLocation.north().equals(src))
against[i++] = placementLocation.north();
if (!placementLocation.south().equals(src))
against[i++] = placementLocation.south();
if (!placementLocation.east().equals(src))
against[i++] = placementLocation.east();
if (!placementLocation.west().equals(src))
against[i] = placementLocation.west();
// TODO: add ability to place against .down() as well as the cardinal directions
// useful for when you are starting a staircase without anything to place against
// Counterpoint to the above TODO ^ you should move then pillar instead of ascend
}
@Override
protected double calculateCost(CalculationContext context) {
IBlockState toPlace = BlockStateInterface.get(positionsToPlace[0]);
if (!MovementHelper.canWalkOn(positionsToPlace[0], toPlace)) {
if (!BlockStateInterface.isAir(toPlace) && !BlockStateInterface.isWater(toPlace.getBlock())) {
// TODO replace this check with isReplacable or similar
return COST_INF;
}
if (!context.hasThrowaway()) {
return COST_INF;
}
for (BlockPos against1 : against) {
if (BlockStateInterface.get(against1).isBlockNormalCube()) {
return JUMP_ONE_BLOCK_COST + WALK_ONE_BLOCK_COST + context.placeBlockCost() + getTotalHardnessOfBlocksToBreak(context);
}
}
return COST_INF;
}
if (BlockStateInterface.get(src.up(3)).getBlock() instanceof BlockFalling) {//it would fall on us and possibly suffocate us
// HOWEVER, we assume that we're standing in the start position
// that means that src and src.up(1) are both air
// maybe they aren't now, but they will be by the time this starts
Block srcUp = BlockStateInterface.get(src.up(1)).getBlock();
Block srcUp2 = BlockStateInterface.get(src.up(2)).getBlock();
if (!(srcUp instanceof BlockFalling) || !(srcUp2 instanceof BlockFalling)) {
// if both of those are BlockFalling, that means that by standing on src
// (the presupposition of this Movement)
// we have necessarily already cleared the entire BlockFalling stack
// on top of our head
// but if either of them aren't BlockFalling, that means we're still in suffocation danger
// so don't do it
return COST_INF;
}
// you may think we only need to check srcUp2, not srcUp
// however, in the scenario where glitchy world gen where unsupported sand / gravel generates
// it's possible srcUp is AIR from the start, and srcUp2 is falling
// 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)) {
walk *= WALK_ONE_OVER_SOUL_SAND_COST / WALK_ONE_BLOCK_COST;
}
// we hit space immediately on entering this action
return Math.max(JUMP_ONE_BLOCK_COST, walk) + getTotalHardnessOfBlocksToBreak(context);
}
@Override
public MovementState updateState(MovementState state) {
super.updateState(state);
// TODO incorporate some behavior from ActionClimb (specifically how it waited until it was at most 1.2 blocks away before starting to jump
// for efficiency in ascending minimal height staircases, which is just repeated MovementAscend, so that it doesn't bonk its head on the ceiling repeatedly)
switch (state.getStatus()) {
case WAITING:
case RUNNING:
break;
default:
return state;
}
if (playerFeet().equals(dest)) {
state.setStatus(MovementStatus.SUCCESS);
return state;
}
if (!MovementHelper.canWalkOn(positionsToPlace[0])) {
for (BlockPos anAgainst : against) {
if (BlockStateInterface.get(anAgainst).isBlockNormalCube()) {
if (!MovementHelper.throwaway(true)) {//get ready to place a throwaway block
return state.setStatus(MovementStatus.UNREACHABLE);
}
double faceX = (dest.getX() + anAgainst.getX() + 1.0D) * 0.5D;
double faceY = (dest.getY() + anAgainst.getY()) * 0.5D;
double faceZ = (dest.getZ() + anAgainst.getZ() + 1.0D) * 0.5D;
state.setTarget(new MovementState.MovementTarget(Utils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations())));
EnumFacing side = Minecraft.getMinecraft().objectMouseOver.sideHit;
if (Objects.equals(LookBehaviorUtils.getSelectedBlock().orElse(null), anAgainst) && LookBehaviorUtils.getSelectedBlock().get().offset(side).equals(positionsToPlace[0])) {
ticksWithoutPlacement++;
state.setInput(InputOverrideHandler.Input.SNEAK, true);
if (player().isSneaking()) {
state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true);
}
if (ticksWithoutPlacement > 20) {
state.setInput(InputOverrideHandler.Input.MOVE_BACK, true);//we might be standing in the way, move back
}
}
System.out.println("Trying to look at " + anAgainst + ", actually looking at" + LookBehaviorUtils.getSelectedBlock());
return state;
}
}
return state.setStatus(MovementStatus.UNREACHABLE);
}
MovementHelper.moveTowards(state, dest);
state.setInput(InputOverrideHandler.Input.JUMP, true);
// TODO check if the below actually helps or hurts, it's weird
//double flatDistToNext = Math.abs(to.getX() - from.getX()) * Math.abs((to.getX() + 0.5D) - thePlayer.posX) + Math.abs(to.getZ() - from.getZ()) * Math.abs((to.getZ() + 0.5D) - thePlayer.posZ);
//boolean pointingInCorrectDirection = MovementManager.moveTowardsBlock(to);
//MovementManager.jumping = flatDistToNext < 1.2 && pointingInCorrectDirection;
//once we are pointing the right way and moving, start jumping
//this is slightly more efficient because otherwise we might start jumping before moving, and fall down without moving onto the block we want to jump onto
//also wait until we are close enough, because we might jump and hit our head on an adjacent block
//return Baritone.playerFeet.equals(to);
return state;
}
}

View File

@@ -15,50 +15,41 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.movement.movements;
package baritone.bot.pathing.movement.movements;
import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.Movement;
import baritone.pathing.movement.MovementHelper;
import baritone.pathing.movement.MovementState;
import baritone.pathing.movement.MovementState.MovementStatus;
import baritone.utils.BlockStateInterface;
import baritone.utils.InputOverrideHandler;
import net.minecraft.util.math.BlockPos;
import baritone.bot.pathing.movement.CalculationContext;
import baritone.bot.pathing.movement.Movement;
import baritone.bot.pathing.movement.MovementHelper;
import baritone.bot.pathing.movement.MovementState;
import baritone.bot.pathing.movement.MovementState.MovementStatus;
import baritone.bot.utils.BlockStateInterface;
import baritone.bot.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;
public class MovementDescend extends Movement {
public MovementDescend(BlockPos start, BlockPos end) {
super(start, end, new BlockPos[]{end.up(2), end.up(), end}, end.down());
}
@Override
public void reset() {
super.reset();
numTicks = 0;
super(start, end, new BlockPos[]{end.up(2), end.up(), end}, new BlockPos[]{end.down()});
}
@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)) {
if (!MovementHelper.canWalkOn(positionsToPlace[0])) {
return COST_INF;
}
Block tmp1 = BlockStateInterface.get(dest).getBlock();
if (tmp1 == Blocks.LADDER || tmp1 == Blocks.VINE) {
if (tmp1 instanceof BlockLadder || tmp1 instanceof BlockVine) {
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 (fromDown == Blocks.SOUL_SAND) {
if (BlockStateInterface.get(src.down()).getBlock().equals(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 *= WALK_ONE_OVER_SOUL_SAND_COST / WALK_ONE_BLOCK_COST;
}
return walk + Math.max(FALL_N_BLOCKS_COST[1], CENTER_AFTER_FALL_COST) + getTotalHardnessOfBlocksToBreak(context);
}
@@ -68,13 +59,17 @@ public class MovementDescend extends Movement {
@Override
public MovementState updateState(MovementState state) {
super.updateState(state);
if (state.getStatus() != MovementStatus.RUNNING) {
return state;
switch (state.getStatus()) {
case WAITING:
state.setStatus(MovementStatus.RUNNING);
case RUNNING:
break;
default:
return state;
}
BlockPos playerFeet = playerFeet();
if (playerFeet.equals(dest)) {
if (BlockStateInterface.isLiquid(dest) || player().posY - playerFeet.getY() < 0.094) { // lilypads
if (BlockStateInterface.isLiquid(dest) || player().posY - playerFeet.getY() < 0.01) {
// Wait until we're actually on the ground before saying we're done because sometimes we continue to fall if the next action starts immediately
state.setStatus(MovementStatus.SUCCESS);
return state;
@@ -90,6 +85,9 @@ public class MovementDescend extends Movement {
double fromStart = Math.sqrt(x * x + z * z);
if (!playerFeet.equals(dest) || ab > 0.25) {
BlockPos fakeDest = new BlockPos(dest.getX() * 2 - src.getX(), dest.getY(), dest.getZ() * 2 - src.getZ());
double diffX2 = player().posX - (fakeDest.getX() + 0.5);
double diffZ2 = player().posZ - (fakeDest.getZ() + 0.5);
double d = Math.sqrt(diffX2 * diffX2 + diffZ2 * diffZ2);
if (numTicks++ < 20) {
MovementHelper.moveTowards(state, fakeDest);
if (fromStart > 1.25) {

View File

@@ -15,16 +15,13 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.movement.movements;
package baritone.bot.pathing.movement.movements;
import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.Movement;
import baritone.pathing.movement.MovementHelper;
import baritone.pathing.movement.MovementState;
import baritone.utils.BlockStateInterface;
import baritone.utils.InputOverrideHandler;
import net.minecraft.util.math.BlockPos;
import net.minecraft.block.Block;
import baritone.bot.pathing.movement.CalculationContext;
import baritone.bot.pathing.movement.Movement;
import baritone.bot.pathing.movement.MovementHelper;
import baritone.bot.pathing.movement.MovementState;
import baritone.bot.utils.BlockStateInterface;
import net.minecraft.block.BlockMagma;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
@@ -32,7 +29,6 @@ import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import java.util.ArrayList;
import java.util.List;
public class MovementDiagonal extends Movement {
@@ -43,109 +39,109 @@ public class MovementDiagonal extends Movement {
// super(start, start.offset(dir1).offset(dir2), new BlockPos[]{start.offset(dir1), start.offset(dir1).up(), start.offset(dir2), start.offset(dir2).up(), start.offset(dir1).offset(dir2), start.offset(dir1).offset(dir2).up()}, new BlockPos[]{start.offset(dir1).offset(dir2).down()});
}
private MovementDiagonal(BlockPos start, BlockPos dir1, BlockPos dir2, EnumFacing drr2) {
public MovementDiagonal(BlockPos start, BlockPos dir1, BlockPos dir2, EnumFacing drr2) {
this(start, dir1.offset(drr2), dir1, dir2);
}
private MovementDiagonal(BlockPos start, BlockPos end, BlockPos dir1, BlockPos dir2) {
super(start, end, new BlockPos[]{dir1, dir1.up(), dir2, dir2.up(), end, end.up()});
public MovementDiagonal(BlockPos start, BlockPos end, BlockPos dir1, BlockPos dir2) {
super(start, end, new BlockPos[]{dir1, dir1.up(), dir2, dir2.up(), end, end.up()}, new BlockPos[]{end.down()});
}
@Override
public MovementState updateState(MovementState state) {
super.updateState(state);
switch (state.getStatus()) {
case WAITING:
case RUNNING:
break;
default:
return state;
}
if (playerFeet().equals(dest)) {
state.setStatus(MovementState.MovementStatus.SUCCESS);
return state;
}
if (!BlockStateInterface.isLiquid(playerFeet())) {
player().setSprinting(true);
}
MovementHelper.moveTowards(state, dest);
return state;
}
@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;
}
BlockPos destDown = dest.down();
IBlockState destWalkOn = BlockStateInterface.get(destDown);
if (!MovementHelper.canWalkOn(destDown, destWalkOn)) {
IBlockState destWalkOn = BlockStateInterface.get(positionsToPlace[0]);
if (!MovementHelper.canWalkOn(positionsToPlace[0], destWalkOn)) {
return COST_INF;
}
double multiplier = WALK_ONE_BLOCK_COST;
// For either possible soul sand, that affects half of our walking
// for either possible soul sand, that affects half of our walking
if (destWalkOn.getBlock().equals(Blocks.SOUL_SAND)) {
multiplier += (WALK_ONE_OVER_SOUL_SAND_COST - WALK_ONE_BLOCK_COST) / 2;
}
if (fromDown == Blocks.SOUL_SAND) {
if (BlockStateInterface.get(src.down()).getBlock().equals(Blocks.SOUL_SAND)) {
multiplier += (WALK_ONE_OVER_SOUL_SAND_COST - WALK_ONE_BLOCK_COST) / 2;
}
Block cuttingOver1 = BlockStateInterface.get(positionsToBreak[2].down()).getBlock();
if (cuttingOver1 instanceof BlockMagma || BlockStateInterface.isLava(cuttingOver1)) {
if (BlockStateInterface.get(positionsToBreak[2].down()).getBlock() instanceof BlockMagma) {
return COST_INF;
}
Block cuttingOver2 = BlockStateInterface.get(positionsToBreak[4].down()).getBlock();
if (cuttingOver2 instanceof BlockMagma || BlockStateInterface.isLava(cuttingOver2)) {
if (BlockStateInterface.get(positionsToBreak[4].down()).getBlock() instanceof BlockMagma) {
return COST_INF;
}
IBlockState pb0 = BlockStateInterface.get(positionsToBreak[0]);
IBlockState pb1 = BlockStateInterface.get(positionsToBreak[1]);
IBlockState pb2 = BlockStateInterface.get(positionsToBreak[2]);
IBlockState pb3 = BlockStateInterface.get(positionsToBreak[3]);
double optionA = MovementHelper.getMiningDurationTicks(context, positionsToBreak[0], pb0, false) + MovementHelper.getMiningDurationTicks(context, positionsToBreak[1], pb1, true);
double optionB = MovementHelper.getMiningDurationTicks(context, positionsToBreak[2], pb2, false) + MovementHelper.getMiningDurationTicks(context, positionsToBreak[3], pb3, true);
double optionA = MovementHelper.getMiningDurationTicks(context, positionsToBreak[0]) + MovementHelper.getMiningDurationTicks(context, positionsToBreak[1]);
double optionB = MovementHelper.getMiningDurationTicks(context, positionsToBreak[2]) + MovementHelper.getMiningDurationTicks(context, positionsToBreak[3]);
if (optionA != 0 && optionB != 0) {
return COST_INF;
}
if (optionA == 0) {
if (MovementHelper.avoidWalkingInto(pb2.getBlock()) || MovementHelper.avoidWalkingInto(pb3.getBlock())) {
if (MovementHelper.avoidWalkingInto(BlockStateInterface.getBlock(positionsToBreak[2]))) {
return COST_INF;
}
if (MovementHelper.avoidWalkingInto(BlockStateInterface.getBlock(positionsToBreak[3]))) {
return COST_INF;
}
}
if (optionB == 0) {
if (MovementHelper.avoidWalkingInto(pb0.getBlock()) || MovementHelper.avoidWalkingInto(pb1.getBlock())) {
if (MovementHelper.avoidWalkingInto(BlockStateInterface.getBlock(positionsToBreak[0]))) {
return COST_INF;
}
if (MovementHelper.avoidWalkingInto(BlockStateInterface.getBlock(positionsToBreak[1]))) {
return COST_INF;
}
}
if (BlockStateInterface.isWater(src) || BlockStateInterface.isWater(dest)) {
// Ignore previous multiplier
// Whatever we were walking on (possibly soul sand) doesn't matter as we're actually floating on water
// Not even touching the blocks below
// ignore previous multiplier
// whatever we were walking on (possibly soul sand) doesn't matter as we're actually floating on water
// not even touching the blocks below
multiplier = WALK_ONE_IN_WATER_COST;
}
if (optionA != 0 || optionB != 0) {
multiplier *= SQRT_2 - 0.001; // TODO tune
}
if (multiplier == WALK_ONE_BLOCK_COST && context.canSprint()) {
// If we aren't edging around anything, and we aren't in water or soul sand
// We can sprint =D
// if we aren't edging around anything, and we aren't in water or soul sand
// we can sprint =D
multiplier = SPRINT_ONE_BLOCK_COST;
}
return multiplier * SQRT_2;
}
@Override
public MovementState updateState(MovementState state) {
super.updateState(state);
if (state.getStatus() != MovementState.MovementStatus.RUNNING) {
return state;
}
if (playerFeet().equals(dest)) {
state.setStatus(MovementState.MovementStatus.SUCCESS);
return state;
}
if (!BlockStateInterface.isLiquid(playerFeet())) {
state.setInput(InputOverrideHandler.Input.SPRINT, true);
}
MovementHelper.moveTowards(state, dest);
return state;
}
@Override
protected boolean prepared(MovementState state) {
return true;
}
@Override
public List<BlockPos> toBreak() {
public ArrayList<BlockPos> toBreak() {
if (toBreakCached != null) {
return toBreakCached;
}
List<BlockPos> result = new ArrayList<>();
ArrayList<BlockPos> result = new ArrayList<>();
for (int i = 4; i < 6; i++) {
if (!MovementHelper.canWalkThrough(positionsToBreak[i])) {
result.add(positionsToBreak[i]);
@@ -156,11 +152,11 @@ public class MovementDiagonal extends Movement {
}
@Override
public List<BlockPos> toWalkInto() {
public ArrayList<BlockPos> toWalkInto() {
if (toWalkIntoCached == null) {
toWalkIntoCached = new ArrayList<>();
}
List<BlockPos> result = new ArrayList<>();
ArrayList<BlockPos> result = new ArrayList<>();
for (int i = 0; i < 4; i++) {
if (!MovementHelper.canWalkThrough(positionsToBreak[i])) {
result.add(positionsToBreak[i]);

View File

@@ -15,17 +15,17 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.movement.movements;
package baritone.bot.pathing.movement.movements;
import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.Movement;
import baritone.pathing.movement.MovementHelper;
import baritone.pathing.movement.MovementState;
import baritone.utils.BlockStateInterface;
import net.minecraft.util.math.BlockPos;
import baritone.bot.pathing.movement.CalculationContext;
import baritone.bot.pathing.movement.Movement;
import baritone.bot.pathing.movement.MovementHelper;
import baritone.bot.pathing.movement.MovementState;
import baritone.bot.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 {
@@ -33,13 +33,7 @@ public class MovementDownward extends Movement {
private int numTicks = 0;
public MovementDownward(BlockPos start, BlockPos end) {
super(start, end, new BlockPos[]{end});
}
@Override
public void reset() {
super.reset();
numTicks = 0;
super(start, end, new BlockPos[]{end}, new BlockPos[0]);
}
@Override
@@ -49,22 +43,24 @@ public class MovementDownward extends Movement {
}
IBlockState d = BlockStateInterface.get(dest);
Block td = d.getBlock();
boolean ladder = td == Blocks.LADDER || td == Blocks.VINE;
boolean ladder = td instanceof BlockLadder || td instanceof BlockVine;
if (ladder) {
return LADDER_DOWN_ONE_COST;
} else {
// we're standing on it, while it might be block falling, it'll be air by the time we get here in the movement
return FALL_N_BLOCKS_COST[1] + MovementHelper.getMiningDurationTicks(context, dest, d, false);
return FALL_N_BLOCKS_COST[1] + MovementHelper.getMiningDurationTicks(context, dest, d);
}
}
@Override
public MovementState updateState(MovementState state) {
super.updateState(state);
if (state.getStatus() != MovementState.MovementStatus.RUNNING) {
return state;
switch (state.getStatus()) {
case WAITING:
case RUNNING:
break;
default:
return state;
}
if (playerFeet().equals(dest)) {
state.setStatus(MovementState.MovementStatus.SUCCESS);
return state;

View File

@@ -15,118 +15,98 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.movement.movements;
package baritone.bot.pathing.movement.movements;
import baritone.Baritone;
import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.Movement;
import baritone.pathing.movement.MovementHelper;
import baritone.pathing.movement.MovementState;
import baritone.pathing.movement.MovementState.MovementStatus;
import baritone.pathing.movement.MovementState.MovementTarget;
import baritone.utils.*;
import net.minecraft.util.math.BlockPos;
import baritone.bot.behavior.impl.LookBehaviorUtils;
import baritone.bot.pathing.movement.CalculationContext;
import baritone.bot.pathing.movement.Movement;
import baritone.bot.pathing.movement.MovementHelper;
import baritone.bot.pathing.movement.MovementState;
import baritone.bot.pathing.movement.MovementState.MovementStatus;
import baritone.bot.pathing.movement.MovementState.MovementTarget;
import baritone.bot.utils.BlockStateInterface;
import baritone.bot.utils.InputOverrideHandler;
import baritone.bot.utils.Rotation;
import baritone.bot.utils.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;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import java.util.Optional;
public class MovementFall extends Movement {
private static final ItemStack STACK_BUCKET_WATER = new ItemStack(Items.WATER_BUCKET);
private static final ItemStack STACK_BUCKET_EMPTY = new ItemStack(Items.BUCKET);
public MovementFall(BlockPos src, BlockPos dest) {
super(src, dest, MovementFall.buildPositionsToBreak(src, dest));
super(src, dest, MovementFall.buildPositionsToBreak(src, dest), new BlockPos[]{dest.down()});
}
@Override
protected double calculateCost(CalculationContext context) {
Block fromDown = BlockStateInterface.get(src.down()).getBlock();
if (fromDown == Blocks.LADDER || fromDown == Blocks.VINE) {
if (!MovementHelper.canWalkOn(positionsToPlace[0])) {
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 (!BlockStateInterface.isWater(dest) && src.getY() - dest.getY() > 3) {
if (!context.hasWaterBucket()) {
return COST_INF;
}
if (src.getY() - dest.getY() > context.maxFallHeightBucket()) {
return COST_INF;
}
placeBucketCost = context.placeBlockCost();
}
double frontThree = 0;
for (int i = 0; i < 3; i++) {
frontThree += MovementHelper.getMiningDurationTicks(context, positionsToBreak[i], false);
// don't include falling because we will check falling right after this, and if it's there it's COST_INF
if (frontThree >= COST_INF) {
return COST_INF;
}
}
if (BlockStateInterface.get(positionsToBreak[0].up()).getBlock() instanceof BlockFalling) {
double frontTwo = MovementHelper.getMiningDurationTicks(context, positionsToBreak[0]) + MovementHelper.getMiningDurationTicks(context, positionsToBreak[1]);
if (frontTwo >= COST_INF) {
return COST_INF;
}
for (int i = 3; i < positionsToBreak.length; i++) {
for (int i = 2; i < positionsToBreak.length; i++) {
// TODO is this the right check here?
// MiningDurationTicks is all right, but shouldn't it be canWalkThrough instead?
// Lilypads (i think?) are 0 ticks to mine, but they definitely cause fall damage
// Same thing for falling through water... we can't actually do that
// And falling through signs is possible, but they do have a mining duration, right?
if (MovementHelper.getMiningDurationTicks(context, positionsToBreak[i], false) > 0) {
// miningDurationTicks is all right, but shouldn't it be canWalkThrough instead?
// lilypads (i think?) are 0 ticks to mine, but they definitely cause fall damage
// same thing for falling through water... we can't actually do that
// and falling through signs is possible, but they do have a mining duration, right?
if (MovementHelper.getMiningDurationTicks(context, positionsToBreak[i]) > 0) {
//can't break while falling
return COST_INF;
}
}
return WALK_OFF_BLOCK_COST + FALL_N_BLOCKS_COST[positionsToBreak.length - 1] + placeBucketCost + frontThree;
return WALK_OFF_BLOCK_COST + FALL_N_BLOCKS_COST[positionsToBreak.length - 1] + placeBucketCost + frontTwo;
}
@Override
public MovementState updateState(MovementState state) {
super.updateState(state);
if (state.getStatus() != MovementStatus.RUNNING) {
return state;
switch (state.getStatus()) {
case WAITING:
state.setStatus(MovementStatus.RUNNING);
case RUNNING:
break;
default:
return state;
}
BlockPos playerFeet = playerFeet();
Rotation targetRotation = null;
if (!BlockStateInterface.isWater(dest) && src.getY() - dest.getY() > Baritone.settings().maxFallHeightNoWater.get() && !playerFeet.equals(dest)) {
if (!InventoryPlayer.isHotbar(player().inventory.getSlotFor(STACK_BUCKET_WATER)) || world().provider.isNether()) {
Optional<Rotation> targetRotation = Optional.empty();
if (!BlockStateInterface.isWater(dest) && src.getY() - dest.getY() > 3 && !playerFeet.equals(dest)) {
if (!player().inventory.hasItemStack(STACK_BUCKET_WATER) || world().provider.isNether()) { // TODO check if water bucket is on hotbar or main inventory
state.setStatus(MovementStatus.UNREACHABLE);
return state;
}
if (player().posY - dest.getY() < mc.playerController.getBlockReachDistance()) {
player().inventory.currentItem = player().inventory.getSlotFor(STACK_BUCKET_WATER);
targetRotation = new Rotation(player().rotationYaw, 90.0F);
RayTraceResult trace = RayTraceUtils.simulateRayTrace(player().rotationYaw, 90.0F);
if (trace != null && trace.typeOfHit == RayTraceResult.Type.BLOCK) {
state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true);
}
targetRotation = LookBehaviorUtils.reachable((BlockStateInterface.get(dest).getCollisionBoundingBox(mc.world, dest) == Block.NULL_AABB) ? dest : dest.down());
}
}
if (targetRotation != null) {
state.setTarget(new MovementTarget(targetRotation, true));
if (targetRotation.isPresent()) {
state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true)
.setTarget(new MovementTarget(targetRotation.get()));
} else {
state.setTarget(new MovementTarget(Utils.calcRotationFromVec3d(playerHead(), Utils.getBlockPosCenter(dest)), false));
state.setTarget(new MovementTarget(Utils.calcRotationFromVec3d(playerHead(), Utils.getBlockPosCenter(dest))));
}
if (playerFeet.equals(dest) && (player().posY - playerFeet.getY() < 0.094 || BlockStateInterface.isWater(dest))) { // 0.094 because lilypads
if (BlockStateInterface.isWater(dest) && InventoryPlayer.isHotbar(player().inventory.getSlotFor(STACK_BUCKET_EMPTY))) {
if (playerFeet.equals(dest) && (player().posY - playerFeet.getY() < 0.01
|| BlockStateInterface.isWater(dest))) {
if (BlockStateInterface.isWater(dest) && player().inventory.hasItemStack(STACK_BUCKET_EMPTY)) {
player().inventory.currentItem = player().inventory.getSlotFor(STACK_BUCKET_EMPTY);
if (player().motionY >= 0) {
return state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true);

View File

@@ -15,49 +15,38 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.movement.movements;
package baritone.bot.pathing.movement.movements;
import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.Movement;
import baritone.pathing.movement.MovementHelper;
import baritone.pathing.movement.MovementState;
import baritone.utils.BlockStateInterface;
import baritone.utils.InputOverrideHandler;
import baritone.utils.Rotation;
import baritone.utils.Utils;
import net.minecraft.util.math.BlockPos;
import baritone.bot.pathing.movement.CalculationContext;
import baritone.bot.pathing.movement.Movement;
import baritone.bot.pathing.movement.MovementHelper;
import baritone.bot.pathing.movement.MovementState;
import baritone.bot.utils.BlockStateInterface;
import baritone.bot.utils.InputOverrideHandler;
import baritone.bot.utils.Rotation;
import baritone.bot.utils.Utils;
import net.minecraft.block.*;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.util.math.BlockPos;
public class MovementPillar extends Movement {
private int numTicks = 0;
public MovementPillar(BlockPos start, BlockPos end) {
super(start, end, new BlockPos[]{start.up(2)}, start);
}
@Override
public void reset() {
super.reset();
numTicks = 0;
super(start, end, new BlockPos[]{start.up(2)}, new BlockPos[]{start});
}
@Override
protected double calculateCost(CalculationContext context) {
Block fromDown = BlockStateInterface.get(src).getBlock();
boolean ladder = fromDown instanceof BlockLadder || fromDown instanceof BlockVine;
IBlockState fromDownDown = BlockStateInterface.get(src.down());
Block fromDownDown = BlockStateInterface.get(src.down()).getBlock();
if (!ladder) {
if (fromDownDown.getBlock() instanceof BlockLadder || fromDownDown.getBlock() instanceof BlockVine) {
if (fromDownDown instanceof BlockLadder || fromDownDown 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;
@@ -68,9 +57,6 @@ public class MovementPillar extends Movement {
}
}
double hardness = getTotalHardnessOfBlocksToBreak(context);
if (hardness >= COST_INF) {
return COST_INF;
}
if (hardness != 0) {
Block tmp = BlockStateInterface.get(src.up(2)).getBlock();
if (tmp instanceof BlockLadder || tmp instanceof BlockVine) {
@@ -78,22 +64,15 @@ public class MovementPillar extends Movement {
} else {
BlockPos chkPos = src.up(3);
IBlockState check = BlockStateInterface.get(chkPos);
if (check.getBlock() instanceof BlockFalling) {
// see MovementAscend's identical check for breaking a falling block above our head
if (!(tmp instanceof BlockFalling) || !(BlockStateInterface.get(src.up(1)).getBlock() instanceof BlockFalling)) {
return COST_INF;
}
if (!MovementHelper.canWalkOn(chkPos, check) || MovementHelper.canWalkThrough(chkPos, check) || check.getBlock() instanceof BlockFalling) {//if the block above where we want to break is not a full block, don't do it
// TODO why does canWalkThrough mean this action is COST_INF?
// BlockFalling makes sense, and !canWalkOn deals with weird cases like if it were lava
// but I don't understand why canWalkThrough makes it impossible
return COST_INF;
}
// this is commented because it may have had a purpose, but it's very unclear what it was. it's from the minebot era.
//if (!MovementHelper.canWalkOn(chkPos, check) || MovementHelper.canWalkThrough(chkPos, check)) {//if the block above where we want to break is not a full block, don't do it
// TODO why does canWalkThrough mean this action is COST_INF?
// BlockFalling makes sense, and !canWalkOn deals with weird cases like if it were lava
// but I don't understand why canWalkThrough makes it impossible
// return COST_INF;
//}
}
}
if (fromDown instanceof BlockLiquid || fromDownDown.getBlock() instanceof BlockLiquid) {//can't pillar on water or in water
if (fromDown instanceof BlockLiquid || fromDownDown instanceof BlockLiquid) {//can't pillar on water or in water
return COST_INF;
}
if (ladder) {
@@ -108,13 +87,13 @@ public class MovementPillar extends Movement {
return vine.north();
}
if (BlockStateInterface.get(vine.south()).isBlockNormalCube()) {
return vine.south();
return vine.north();
}
if (BlockStateInterface.get(vine.east()).isBlockNormalCube()) {
return vine.east();
return vine.north();
}
if (BlockStateInterface.get(vine.west()).isBlockNormalCube()) {
return vine.west();
return vine.north();
}
return null;
}
@@ -122,83 +101,72 @@ public class MovementPillar extends Movement {
@Override
public MovementState updateState(MovementState state) {
super.updateState(state);
if (state.getStatus() != MovementState.MovementStatus.RUNNING) {
return state;
switch (state.getStatus()) {
case WAITING:
case RUNNING:
break;
default:
return state;
}
IBlockState fromDown = BlockStateInterface.get(src);
boolean ladder = fromDown.getBlock() instanceof BlockLadder || fromDown.getBlock() instanceof BlockVine;
boolean vine = fromDown.getBlock() instanceof BlockVine;
if (!ladder) {
state.setTarget(new MovementState.MovementTarget(Utils.calcRotationFromVec3d(mc.player.getPositionEyes(1.0F),
Utils.getBlockPosCenter(positionToPlace),
new Rotation(mc.player.rotationYaw, mc.player.rotationPitch)), true));
Utils.getBlockPosCenter(positionsToPlace[0]),
new Rotation(mc.player.rotationYaw, mc.player.rotationPitch))));
}
EntityPlayerSP thePlayer = Minecraft.getMinecraft().player;
boolean blockIsThere = MovementHelper.canWalkOn(src) || ladder;
if (ladder) {
BlockPos against = vine ? getAgainst(src) : src.offset(fromDown.getValue(BlockLadder.FACING).getOpposite());
if (against == null) {
displayChatMessageRaw("Unable to climb vines");
return state.setStatus(MovementState.MovementStatus.UNREACHABLE);
}
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);
}
*/
MovementHelper.moveTowards(state, against);
return state;
} else {
// Get ready to place a throwaway block
if (!MovementHelper.throwaway(true)) {
state.setStatus(MovementState.MovementStatus.UNREACHABLE);
return state;
}
if (playerFeet().equals(against.up()) || playerFeet().equals(dest)) {
state.setStatus(MovementState.MovementStatus.SUCCESS);
return state;
}
/*if (thePlayer.getPosition0().getX() != from.getX() || thePlayer.getPosition0().getZ() != from.getZ()) {
Baritone.moveTowardsBlock(from);
}*/
MovementHelper.moveTowards(state, against);
return state;
} else {
if (!MovementHelper.throwaway(true)) {//get ready to place a throwaway block
state.setStatus(MovementState.MovementStatus.UNREACHABLE);
return state;
}
numTicks++;
// If our Y coordinate is above our goal, stop jumping
state.setInput(InputOverrideHandler.Input.JUMP, player().posY < dest.getY());
state.setInput(InputOverrideHandler.Input.JUMP, thePlayer.posY < dest.getY()); //if our Y coordinate is above our goal, stop jumping
state.setInput(InputOverrideHandler.Input.SNEAK, true);
// Otherwise jump
if (numTicks > 20) {
double diffX = player().posX - (dest.getX() + 0.5);
double diffZ = player().posZ - (dest.getZ() + 0.5);
//otherwise jump
if (numTicks > 40) {
double diffX = thePlayer.posX - (dest.getX() + 0.5);
double diffZ = thePlayer.posZ - (dest.getZ() + 0.5);
double dist = Math.sqrt(diffX * diffX + diffZ * diffZ);
if (dist > 0.17) {//why 0.17? because it seemed like a good number, that's why
//[explanation added after baritone port lol] also because it needs to be less than 0.2 because of the 0.3 sneak limit
//and 0.17 is reasonably less than 0.2
// If it's been more than forty ticks of trying to jump and we aren't done yet, go forward, maybe we are stuck
state.setInput(InputOverrideHandler.Input.MOVE_FORWARD, true);
state.setInput(InputOverrideHandler.Input.MOVE_FORWARD, true);//if it's been more than forty ticks of trying to jump and we aren't done yet, go forward, maybe we are stuck
}
}
if (!blockIsThere) {
Block fr = BlockStateInterface.get(src).getBlock();
if (!(fr instanceof BlockAir || fr.isReplaceable(Minecraft.getMinecraft().world, src))) {
state.setInput(InputOverrideHandler.Input.CLICK_LEFT, true);
blockIsThere = false;
} else if (Minecraft.getMinecraft().player.isSneaking()) {
state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true);
state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true);//constantly right click
}
}
}
// If we are at our goal and the block below us is placed
if (playerFeet().equals(dest) && blockIsThere) {
return state.setStatus(MovementState.MovementStatus.SUCCESS);
if (playerFeet().equals(dest) && blockIsThere) {//if we are at our goal and the block below us is placed
state.setStatus(MovementState.MovementStatus.SUCCESS);
return state;//we are done
}
return state;
}
}
}

View File

@@ -15,18 +15,20 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.movement.movements;
package baritone.bot.pathing.movement.movements;
import baritone.behavior.impl.LookBehaviorUtils;
import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.Movement;
import baritone.pathing.movement.MovementHelper;
import baritone.pathing.movement.MovementState;
import baritone.utils.BlockStateInterface;
import baritone.utils.InputOverrideHandler;
import baritone.utils.Utils;
import net.minecraft.util.math.BlockPos;
import net.minecraft.block.*;
import baritone.bot.behavior.impl.LookBehaviorUtils;
import baritone.bot.pathing.movement.CalculationContext;
import baritone.bot.pathing.movement.Movement;
import baritone.bot.pathing.movement.MovementHelper;
import baritone.bot.pathing.movement.MovementState;
import baritone.bot.utils.BlockStateInterface;
import baritone.bot.utils.InputOverrideHandler;
import baritone.bot.utils.Utils;
import net.minecraft.block.Block;
import net.minecraft.block.BlockDoor;
import net.minecraft.block.BlockLadder;
import net.minecraft.block.BlockVine;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.init.Blocks;
@@ -38,206 +40,165 @@ import java.util.Objects;
public class MovementTraverse extends Movement {
private BlockPos[] against = new BlockPos[3];
/**
* Did we have to place a bridge block or was it always there
*/
private boolean wasTheBridgeBlockAlwaysThere = true;
public MovementTraverse(BlockPos from, BlockPos to) {
super(from, to, new BlockPos[]{to.up(), to}, to.down());
}
super(from, to, new BlockPos[]{to.up(), to}, new BlockPos[]{to.down()});
int i = 0;
@Override
public void reset() {
super.reset();
wasTheBridgeBlockAlwaysThere = true;
if (!to.north().equals(from))
against[i++] = to.north().down();
if (!to.south().equals(from))
against[i++] = to.south().down();
if (!to.east().equals(from))
against[i++] = to.east().down();
if (!to.west().equals(from))
against[i] = to.west().down();
//note: do NOT add ability to place against .down().down()
}
@Override
protected double calculateCost(CalculationContext context) {
IBlockState pb0 = BlockStateInterface.get(positionsToBreak[0]);
IBlockState pb1 = BlockStateInterface.get(positionsToBreak[1]);
IBlockState destOn = BlockStateInterface.get(positionToPlace);
Block srcDown = BlockStateInterface.getBlock(src.down());
if (MovementHelper.canWalkOn(positionToPlace, destOn)) {//this is a walk, not a bridge
IBlockState destOn = BlockStateInterface.get(positionsToPlace[0]);
if (MovementHelper.canWalkOn(positionsToPlace[0], destOn)) {//this is a walk, not a bridge
double WC = WALK_ONE_BLOCK_COST;
if (BlockStateInterface.isWater(pb0.getBlock()) || BlockStateInterface.isWater(pb1.getBlock())) {
WC = WALK_ONE_IN_WATER_COST;
} else {
if (destOn.getBlock() == Blocks.SOUL_SAND) {
if (Blocks.SOUL_SAND.equals(destOn.getBlock())) {
WC += (WALK_ONE_OVER_SOUL_SAND_COST - WALK_ONE_BLOCK_COST) / 2;
}
if (srcDown == Blocks.SOUL_SAND) {
if (Blocks.SOUL_SAND.equals(BlockStateInterface.get(src.down()).getBlock())) {
WC += (WALK_ONE_OVER_SOUL_SAND_COST - WALK_ONE_BLOCK_COST) / 2;
}
}
double hardness1 = MovementHelper.getMiningDurationTicks(context, positionsToBreak[0], pb0, true);
if (hardness1 >= COST_INF) {
return COST_INF;
}
double hardness2 = MovementHelper.getMiningDurationTicks(context, positionsToBreak[1], pb1, false);
if (hardness1 == 0 && hardness2 == 0) {
if (MovementHelper.canWalkThrough(positionsToBreak[0]) && MovementHelper.canWalkThrough(positionsToBreak[1])) {
if (WC == WALK_ONE_BLOCK_COST && context.canSprint()) {
// If there's nothing in the way, and this isn't water or soul sand, and we aren't sneak placing
// We can sprint =D
// if there's nothing in the way, and this isn't water or soul sand, and we aren't sneak placing
// we can sprint =D
WC = SPRINT_ONE_BLOCK_COST;
}
return WC;
}
if (srcDown == Blocks.LADDER || srcDown == Blocks.VINE) {
hardness1 *= 5;
hardness2 *= 5;
}
return WC + hardness1 + hardness2;
//double hardness1 = blocksToBreak[0].getBlockHardness(Minecraft.getMinecraft().world, positionsToBreak[0]);
//double hardness2 = blocksToBreak[1].getBlockHardness(Minecraft.getMinecraft().world, positionsToBreak[1]);
//Out.log("Can't walk through " + blocksToBreak[0] + " (hardness" + hardness1 + ") or " + blocksToBreak[1] + " (hardness " + hardness2 + ")");
return WC + getTotalHardnessOfBlocksToBreak(context);
} else {//this is a bridge, so we need to place a block
if (srcDown == Blocks.LADDER || srcDown == Blocks.VINE) {
Block srcDown = BlockStateInterface.get(src.down()).getBlock();
if (srcDown instanceof BlockLadder || srcDown instanceof BlockVine) {
return COST_INF;
}
if (destOn.getBlock().equals(Blocks.AIR) || MovementHelper.isReplacable(positionToPlace, destOn)) {
boolean throughWater = BlockStateInterface.isWater(pb0.getBlock()) || BlockStateInterface.isWater(pb1.getBlock());
if (BlockStateInterface.isWater(destOn.getBlock()) && throughWater) {
return COST_INF;
}
IBlockState pp0 = BlockStateInterface.get(positionsToPlace[0]);
if (pp0.getBlock().equals(Blocks.AIR) || (!BlockStateInterface.isWater(pp0.getBlock()) && pp0.getBlock().isReplaceable(Minecraft.getMinecraft().world, positionsToPlace[0]))) {
if (!context.hasThrowaway()) {
return COST_INF;
}
double WC = throughWater ? WALK_ONE_IN_WATER_COST : WALK_ONE_BLOCK_COST;
for (int i = 0; i < 4; i++) {
BlockPos against1 = dest.offset(HORIZONTALS[i]);
if (against1.equals(src)) {
continue;
}
against1 = against1.down();
if (MovementHelper.canPlaceAgainst(against1)) {
double WC = BlockStateInterface.isWater(pb0.getBlock()) || BlockStateInterface.isWater(pb1.getBlock()) ? WALK_ONE_IN_WATER_COST : WALK_ONE_BLOCK_COST;
for (BlockPos against1 : against) {
if (BlockStateInterface.get(against1).isBlockNormalCube()) {
return WC + context.placeBlockCost() + getTotalHardnessOfBlocksToBreak(context);
}
}
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 =/
if (BlockStateInterface.get(src).getBlock().equals(Blocks.SOUL_SAND)) {
return COST_INF; // can't sneak and backplace against soul sand =/
}
WC = WC * SNEAK_ONE_BLOCK_COST / WALK_ONE_BLOCK_COST;//since we are placing, we are sneaking
return WC + context.placeBlockCost() + getTotalHardnessOfBlocksToBreak(context);
}
return COST_INF;
// Out.log("Can't walk on " + Baritone.get(positionsToPlace[0]).getBlock());
//Out.log("Can't walk on " + Baritone.get(positionsToPlace[0]).getBlock());
}
}
@Override
public MovementState updateState(MovementState state) {
super.updateState(state);
if (state.getStatus() != MovementState.MovementStatus.RUNNING) {
return state;
switch (state.getStatus()) {
case WAITING:
case RUNNING:
break;
default:
return state;
}
state.setInput(InputOverrideHandler.Input.SNEAK, false);
Block fd = BlockStateInterface.get(src.down()).getBlock();
boolean ladder = fd instanceof BlockLadder || fd instanceof BlockVine;
IBlockState pb0 = BlockStateInterface.get(positionsToBreak[0]);
IBlockState pb1 = BlockStateInterface.get(positionsToBreak[1]);
boolean door = pb0.getBlock() instanceof BlockDoor || pb1.getBlock() instanceof BlockDoor;
boolean door = BlockStateInterface.get(src).getBlock() instanceof BlockDoor || pb0.getBlock() instanceof BlockDoor || pb1.getBlock() instanceof BlockDoor;
if (door) {
boolean isDoorActuallyBlockingUs = false;
if (pb0.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(src, dest)) {
Block srcBlock = BlockStateInterface.get(src).getBlock();
if (srcBlock instanceof BlockDoor && !MovementHelper.isDoorPassable(src, dest)) {
isDoorActuallyBlockingUs = true;
} else if (pb1.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(dest, src)) {
isDoorActuallyBlockingUs = true;
}
if (isDoorActuallyBlockingUs) {
if (!(Blocks.IRON_DOOR.equals(pb0.getBlock()) || Blocks.IRON_DOOR.equals(pb1.getBlock()))) {
state.setTarget(new MovementState.MovementTarget(Utils.calcRotationFromVec3d(playerHead(), Utils.calcCenterFromCoords(positionsToBreak[0], world())), true));
state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true);
return state;
}
}
}
if (pb0.getBlock() instanceof BlockFenceGate || pb1.getBlock() instanceof BlockFenceGate) {
BlockPos blocked = null;
if (!MovementHelper.isGatePassable(positionsToBreak[0], src.up())) {
blocked = positionsToBreak[0];
} else if (!MovementHelper.isGatePassable(positionsToBreak[1], src)) {
blocked = positionsToBreak[1];
}
if (blocked != null) {
state.setTarget(new MovementState.MovementTarget(Utils.calcRotationFromVec3d(playerHead(), Utils.calcCenterFromCoords(blocked, world())), true));
state.setTarget(new MovementState.MovementTarget(Utils.calcRotationFromVec3d(playerHead(), Utils.calcCenterFromCoords(positionsToBreak[0], world()))));
state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true);
return state;
}
}
boolean isTheBridgeBlockThere = MovementHelper.canWalkOn(positionToPlace) || ladder;
boolean isTheBridgeBlockThere = MovementHelper.canWalkOn(positionsToPlace[0]) || ladder;
BlockPos whereAmI = playerFeet();
if (whereAmI.getY() != dest.getY() && !ladder) {
displayChatMessageRaw("Wrong Y coordinate");
System.out.println("Wrong Y coordinate");
if (whereAmI.getY() < dest.getY()) {
state.setInput(InputOverrideHandler.Input.JUMP, true);
}
return state;
}
if (isTheBridgeBlockThere) {
if (playerFeet().equals(dest)) {
state.setStatus(MovementState.MovementStatus.SUCCESS);
return state;
}
if (wasTheBridgeBlockAlwaysThere && !BlockStateInterface.isLiquid(playerFeet())) {
state.setInput(InputOverrideHandler.Input.SPRINT, true);
}
Block destDown = BlockStateInterface.get(dest.down()).getBlock();
if (whereAmI.getY() != dest.getY() && ladder && (destDown instanceof BlockVine || destDown instanceof BlockLadder)) {
new MovementPillar(dest.down(), dest).updateState(state); // i'm sorry
return state;
player().setSprinting(true);
}
MovementHelper.moveTowards(state, positionsToBreak[0]);
return state;
} else {
wasTheBridgeBlockAlwaysThere = false;
for (int i = 0; i < 4; i++) {
BlockPos against1 = dest.offset(HORIZONTALS[i]);
if (against1.equals(src)) {
continue;
}
against1 = against1.down();
if (MovementHelper.canPlaceAgainst(against1)) {
for (BlockPos against1 : against) {
if (BlockStateInterface.get(against1).isBlockNormalCube()) {
if (!MovementHelper.throwaway(true)) { // get ready to place a throwaway block
displayChatMessageRaw("bb pls get me some blocks. dirt or cobble");
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;
state.setTarget(new MovementState.MovementTarget(Utils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations()), true));
state.setTarget(new MovementState.MovementTarget(Utils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations())));
EnumFacing side = Minecraft.getMinecraft().objectMouseOver.sideHit;
if (Objects.equals(LookBehaviorUtils.getSelectedBlock().orElse(null), against1) && Minecraft.getMinecraft().player.isSneaking()) {
if (LookBehaviorUtils.getSelectedBlock().get().offset(side).equals(positionToPlace)) {
return state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true);
if (LookBehaviorUtils.getSelectedBlock().get().offset(side).equals(positionsToPlace[0])) {
state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true);
} else {
// Out.gui("Wrong. " + side + " " + LookBehaviorUtils.getSelectedBlock().get().offset(side) + " " + positionsToPlace[0], Out.Mode.Debug);
}
}
System.out.println("Trying to look at " + against1 + ", actually looking at" + LookBehaviorUtils.getSelectedBlock());
return state.setInput(InputOverrideHandler.Input.CLICK_LEFT, true);
return state;
}
}
state.setInput(InputOverrideHandler.Input.SNEAK, true);
if (whereAmI.equals(dest)) {
// If we are in the block that we are trying to get to, we are sneaking over air and we need to place a block beneath us against the one we just walked off of
// if we are in the block that we are trying to get to, we are sneaking over air and we need to place a block beneath us against the one we just walked off of
// Out.log(from + " " + to + " " + faceX + "," + faceY + "," + faceZ + " " + whereAmI);
if (!MovementHelper.throwaway(true)) {// get ready to place a throwaway block
displayChatMessageRaw("bb pls get me some blocks. dirt or cobble");
@@ -248,7 +209,7 @@ public class MovementTraverse extends Movement {
double faceZ = (dest.getZ() + src.getZ() + 1.0D) * 0.5D;
// faceX, faceY, faceZ is the middle of the face between from and to
BlockPos goalLook = src.down(); // this is the block we were just standing on, and the one we want to place against
state.setTarget(new MovementState.MovementTarget(Utils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations()), true));
state.setTarget(new MovementState.MovementTarget(Utils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations())));
state.setInput(InputOverrideHandler.Input.MOVE_BACK, true);
state.setInput(InputOverrideHandler.Input.SNEAK, true);
@@ -257,7 +218,7 @@ public class MovementTraverse extends Movement {
return state;
}
// Out.log("Trying to look at " + goalLook + ", actually looking at" + Baritone.whatAreYouLookingAt());
return state.setInput(InputOverrideHandler.Input.CLICK_LEFT, true);
return state;
} else {
MovementHelper.moveTowards(state, positionsToBreak[0]);
return state;
@@ -265,15 +226,4 @@ public class MovementTraverse extends Movement {
}
}
}
@Override
protected boolean prepared(MovementState state) {
if (playerFeet().equals(src) || playerFeet().equals(src.down())) {
Block block = BlockStateInterface.getBlock(src.down());
if (block == Blocks.LADDER || block == Blocks.VINE) {
state.setInput(InputOverrideHandler.Input.SNEAK, true);
}
}
return super.prepared(state);
}
}

View File

@@ -15,17 +15,17 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.path;
package baritone.bot.pathing.path;
import baritone.pathing.movement.Movement;
import net.minecraft.util.math.BlockPos;
import baritone.bot.pathing.movement.Movement;
import baritone.bot.utils.pathing.BetterBlockPos;
import java.util.Collections;
import java.util.List;
public class CutoffPath implements IPath {
final List<BlockPos> path;
final List<BetterBlockPos> path;
final List<Movement> movements;
@@ -43,7 +43,7 @@ public class CutoffPath implements IPath {
}
@Override
public List<BlockPos> positions() {
public List<BetterBlockPos> positions() {
return Collections.unmodifiableList(path);
}

View File

@@ -15,14 +15,12 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.path;
package baritone.bot.pathing.path;
import baritone.Baritone;
import baritone.pathing.goals.Goal;
import baritone.pathing.movement.Movement;
import baritone.utils.Helper;
import baritone.utils.Utils;
import net.minecraft.util.math.BlockPos;
import baritone.bot.pathing.movement.Movement;
import baritone.bot.utils.Helper;
import baritone.bot.utils.Utils;
import baritone.bot.utils.pathing.BetterBlockPos;
import net.minecraft.client.Minecraft;
import net.minecraft.util.Tuple;
import net.minecraft.util.math.BlockPos;
@@ -47,7 +45,7 @@ public interface IPath extends Helper {
* All positions along the way.
* Should begin with the same as getSrc and end with the same as getDest
*/
List<BlockPos> positions();
List<BetterBlockPos> positions();
/**
* Number of positions in this path
@@ -65,7 +63,7 @@ public interface IPath extends Helper {
* @return
*/
default Movement subsequentMovement(BlockPos currentPosition) {
List<BlockPos> pos = positions();
List<BetterBlockPos> pos = positions();
List<Movement> movements = movements();
for (int i = 0; i < pos.size(); i++) {
if (currentPosition.equals(pos.get(i))) {
@@ -101,15 +99,15 @@ public interface IPath extends Helper {
/**
* Where does this path start
*/
default BlockPos getSrc() {
default BetterBlockPos getSrc() {
return positions().get(0);
}
/**
* Where does this path end
*/
default BlockPos getDest() {
List<BlockPos> pos = positions();
default BetterBlockPos getDest() {
List<BetterBlockPos> pos = positions();
return pos.get(pos.size() - 1);
}
@@ -137,16 +135,4 @@ public interface IPath extends Helper {
return this;
}
default IPath staticCutoff(Goal destination) {
if (length() < Baritone.settings().pathCutoffMinimumLength.get()) {
return this;
}
if (destination == null || destination.isInGoal(getDest())) {
return this;
}
double factor = Baritone.settings().pathCutoffFactor.get();
int newLength = (int) (length() * factor);
//displayChatMessageRaw("Static cutoff " + length() + " to " + newLength);
return new CutoffPath(this, newLength);
}
}

View File

@@ -15,17 +15,15 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.path;
package baritone.bot.pathing.path;
import baritone.Baritone;
import baritone.api.event.events.TickEvent;
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;
import baritone.bot.Baritone;
import baritone.bot.event.events.TickEvent;
import baritone.bot.pathing.movement.ActionCosts;
import baritone.bot.pathing.movement.Movement;
import baritone.bot.pathing.movement.MovementState;
import baritone.bot.utils.BlockStateInterface;
import baritone.bot.utils.Helper;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.init.Blocks;
import net.minecraft.util.Tuple;
@@ -35,7 +33,7 @@ import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import static baritone.pathing.movement.MovementState.MovementStatus.*;
import static baritone.bot.pathing.movement.MovementState.MovementStatus.*;
/**
* Behavior to execute a precomputed path. Does not (yet) deal with path segmentation or stitching
@@ -44,9 +42,8 @@ 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 static final double MAX_TICKS_AWAY = 200; // ten seconds
private final IPath path;
private int pathPosition;
private int ticksAway;
@@ -88,16 +85,12 @@ public class PathExecutor implements Helper {
return true;
}
if (!whereShouldIBe.equals(whereAmI)) {
//System.out.println("Should be at " + whereShouldIBe + " actually am at " + whereAmI);
System.out.println("Should be at " + whereShouldIBe + " actually am at " + whereAmI);
if (!Blocks.AIR.equals(BlockStateInterface.getBlock(whereAmI.down()))) {//do not skip if standing on air, because our position isn't stable to skip
for (int i = 0; i < pathPosition - 1 && i < path.length(); i++) {//this happens for example when you lag out and get teleported back a couple blocks
for (int i = 0; i < pathPosition - 2 && i < path.length(); i++) {//this happens for example when you lag out and get teleported back a couple blocks
if (whereAmI.equals(path.positions().get(i))) {
displayChatMessageRaw("Skipping back " + (pathPosition - i) + " steps, to " + i);
int previousPos = pathPosition;
pathPosition = Math.max(i - 1, 0); // previous step might not actually be done
for (int j = pathPosition; j <= previousPos; j++) {
path.movements().get(j).reset();
}
Baritone.INSTANCE.getInputOverrideHandler().clearAllKeys();
return false;
}
@@ -107,7 +100,6 @@ public class PathExecutor implements Helper {
if (i - pathPosition > 2) {
displayChatMessageRaw("Skipping forward " + (i - pathPosition) + " steps, to " + i);
}
System.out.println("Double skip sundae");
pathPosition = i - 1;
Baritone.INSTANCE.getInputOverrideHandler().clearAllKeys();
return false;
@@ -131,17 +123,6 @@ 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
@@ -174,7 +155,7 @@ public class PathExecutor implements Helper {
}
}
}*/
long start = System.nanoTime() / 1000000L;
long start = System.currentTimeMillis();
for (int i = pathPosition - 10; i < pathPosition + 10; i++) {
if (i >= 0 && i < path.movements().size()) {
Movement m = path.movements().get(i);
@@ -209,25 +190,11 @@ public class PathExecutor implements Helper {
toWalkInto = newWalkInto;
recalcBP = false;
}
long end = System.nanoTime() / 1000000L;
long end = System.currentTimeMillis();
if (end - start > 0) {
//displayChatMessageRaw("Recalculating break and place took " + (end - start) + "ms");
}
Movement movement = path.movements().get(pathPosition);
if (costEstimateIndex == null || costEstimateIndex != pathPosition) {
costEstimateIndex = pathPosition;
// 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).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;
Baritone.INSTANCE.getInputOverrideHandler().clearAllKeys();
return true;
}
}
}
double currentCost = movement.recalculateCost();
if (currentCost >= ActionCosts.COST_INF) {
displayChatMessageRaw("Something has changed in the world and this movement has become impossible. Cancelling.");
@@ -236,6 +203,10 @@ public class PathExecutor implements Helper {
Baritone.INSTANCE.getInputOverrideHandler().clearAllKeys();
return true;
}
if (costEstimateIndex == null || costEstimateIndex != pathPosition) {
costEstimateIndex = pathPosition;
currentMovementInitialCostEstimate = currentCost; // do this only once, when the movement starts
}
MovementState.MovementStatus movementStatus = movement.update();
if (movementStatus == UNREACHABLE || movementStatus == FAILED) {
displayChatMessageRaw("Movement returns status " + movementStatus);
@@ -245,21 +216,20 @@ public class PathExecutor implements Helper {
return true;
}
if (movementStatus == SUCCESS) {
//System.out.println("Movement done, next path");
System.out.println("Movement done, next path");
pathPosition++;
ticksOnCurrent = 0;
Baritone.INSTANCE.getInputOverrideHandler().clearAllKeys();
onTick(event);
return true;
} else {
sprintIfRequested();
ticksOnCurrent++;
if (ticksOnCurrent > currentMovementInitialCostEstimate + Baritone.settings().movementTimeoutTicks.get()) {
if (ticksOnCurrent > currentMovementInitialCostEstimate + 100) {
// only fail if the total time has exceeded the initial estimate
// as you break the blocks required, the remaining cost goes down, to the point where
// ticksOnCurrent is greater than recalculateCost + 100
// ticksOnCurrent is greater than recalculateCost + 1000
// this is why we cache cost at the beginning, and don't recalculate for this comparison every tick
displayChatMessageRaw("This movement has taken too long (" + ticksOnCurrent + " ticks, expected " + currentMovementInitialCostEstimate + "). Cancelling.");
displayChatMessageRaw("This movement has taken too long (" + ticksOnCurrent + " ticks, expected " + movement.getCost(null) + "). Cancelling.");
movement.cancel();
Baritone.INSTANCE.getInputOverrideHandler().clearAllKeys();
pathPosition = path.length() + 3;
@@ -270,59 +240,6 @@ public class PathExecutor implements Helper {
return false; // movement is in progress
}
private void sprintIfRequested() {
if (!new CalculationContext().canSprint()) {
player().setSprinting(false);
return;
}
if (Baritone.INSTANCE.getInputOverrideHandler().isInputForcedDown(mc.gameSettings.keyBindSprint)) {
if (!player().isSprinting()) {
player().setSprinting(true);
}
return;
}
Movement movement = path.movements().get(pathPosition);
if (movement instanceof MovementDescend && pathPosition < path.length() - 2) {
Movement next = path.movements().get(pathPosition + 1);
if (next instanceof MovementDescend) {
if (next.getDirection().equals(movement.getDirection())) {
if (playerFeet().equals(movement.getDest())) {
pathPosition++;
Baritone.INSTANCE.getInputOverrideHandler().clearAllKeys();
}
if (!player().isSprinting()) {
player().setSprinting(true);
}
return;
}
}
if (next instanceof MovementTraverse) {
if (next.getDirection().down().equals(movement.getDirection()) && MovementHelper.canWalkOn(next.getDest().down())) {
if (playerFeet().equals(movement.getDest())) {
pathPosition++;
Baritone.INSTANCE.getInputOverrideHandler().clearAllKeys();
}
if (!player().isSprinting()) {
player().setSprinting(true);
}
return;
}
}
if (next instanceof MovementDiagonal && Baritone.settings().allowOvershootDiagonalDescend.get()) {
if (playerFeet().equals(movement.getDest())) {
pathPosition++;
Baritone.INSTANCE.getInputOverrideHandler().clearAllKeys();
}
if (!player().isSprinting()) {
player().setSprinting(true);
}
return;
}
//displayChatMessageRaw("Turning off sprinting " + movement + " " + next + " " + movement.getDirection() + " " + next.getDirection().down() + " " + next.getDirection().down().equals(movement.getDirection()));
}
player().setSprinting(false);
}
public int getPosition() {
return pathPosition;
}

View File

@@ -15,95 +15,62 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.utils;
package baritone.bot.utils;
import baritone.Baritone;
import baritone.chunk.CachedRegion;
import baritone.chunk.WorldData;
import baritone.chunk.WorldProvider;
import baritone.bot.Baritone;
import baritone.bot.chunk.CachedWorld;
import baritone.bot.chunk.CachedWorldProvider;
import baritone.bot.utils.pathing.PathingBlockType;
import net.minecraft.block.Block;
import net.minecraft.block.BlockFalling;
import net.minecraft.block.BlockLiquid;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.chunk.Chunk;
/**
* Wraps get for chuck caching capability
*
* @author leijurv
*/
public class BlockStateInterface implements Helper {
private static Chunk prev = null;
private static CachedRegion prevCached = null;
private static IBlockState AIR = Blocks.AIR.getDefaultState();
public static final Block waterFlowing = Blocks.FLOWING_WATER;
public static final Block waterStill = Blocks.WATER;
public static final Block lavaFlowing = Blocks.FLOWING_LAVA;
public static final Block lavaStill = Blocks.LAVA;
public static IBlockState get(BlockPos pos) {
return get(pos.getX(), pos.getY(), pos.getZ());
}
public static IBlockState get(int x, int y, int z) {
public static IBlockState get(BlockPos pos) { // wrappers for future chunk caching capability
// Invalid vertical position
if (y < 0 || y >= 256) {
return AIR;
}
if (pos.getY() < 0 || pos.getY() >= 256)
return Blocks.AIR.getDefaultState();
if (!Baritone.settings().pathThroughCachedOnly.get()) {
Chunk cached = prev;
// there's great cache locality in block state lookups
// generally it's within each movement
// if it's the same chunk as last time
// we can just skip the mc.world.getChunk lookup
// which is a Long2ObjectOpenHashMap.get
if (cached != null && cached.x == x >> 4 && cached.z == z >> 4) {
return cached.getBlockState(x, y, z);
}
Chunk chunk = mc.world.getChunk(x >> 4, z >> 4);
if (chunk.isLoaded()) {
prev = chunk;
return chunk.getBlockState(x, y, z);
}
Chunk chunk = mc.world.getChunk(pos);
if (chunk.isLoaded()) {
return chunk.getBlockState(pos);
}
// same idea here, skip the Long2ObjectOpenHashMap.get if at all possible
// except here, it's 512x512 tiles instead of 16x16, so even better repetition
CachedRegion cached = prevCached;
if (cached != null && cached.getX() == x >> 9 && cached.getZ() == z >> 9) {
IBlockState type = cached.getBlock(x & 511, y, z & 511);
if (type == null) {
return AIR;
}
return type;
}
WorldData world = WorldProvider.INSTANCE.getCurrentWorld();
if (world != null) {
CachedRegion region = world.cache.getRegion(x >> 9, z >> 9);
if (region != null) {
prevCached = region;
IBlockState type = region.getBlock(x & 511, y, z & 511);
if (Baritone.settings().chuckCaching.get()) {
CachedWorld world = CachedWorldProvider.INSTANCE.getCurrentWorld();
if (world != null) {
PathingBlockType type = world.getBlockType(pos);
if (type != null) {
return type;
switch (type) {
case AIR:
return Blocks.AIR.getDefaultState();
case WATER:
return Blocks.WATER.getDefaultState();
case AVOID:
return Blocks.LAVA.getDefaultState();
case SOLID:
return Blocks.OBSIDIAN.getDefaultState();
}
}
}
}
return AIR;
}
public static void clearCachedChunk() {
prev = null;
prevCached = null;
return Blocks.AIR.getDefaultState();
}
public static Block getBlock(BlockPos pos) {
return get(pos).getBlock();
}
public static final Block waterFlowing = Blocks.FLOWING_WATER;
public static final Block waterStill = Blocks.WATER;
public static final Block lavaFlowing = Blocks.FLOWING_LAVA;
public static final Block lavaStill = Blocks.LAVA;
/**
* Returns whether or not the specified block is
@@ -113,7 +80,7 @@ public class BlockStateInterface implements Helper {
* @return Whether or not the block is water
*/
public static boolean isWater(Block b) {
return b == waterFlowing || b == waterStill;
return waterFlowing.equals(b) || waterStill.equals(b);
}
/**
@@ -128,7 +95,7 @@ public class BlockStateInterface implements Helper {
}
public static boolean isLava(Block b) {
return b == lavaFlowing || b == lavaStill;
return lavaFlowing.equals(b) || lavaStill.equals(b);
}
/**
@@ -147,4 +114,18 @@ public class BlockStateInterface implements Helper {
&& state.getPropertyKeys().contains(BlockLiquid.LEVEL)
&& state.getValue(BlockLiquid.LEVEL) != 0;
}
public static boolean isAir(BlockPos pos) {
return BlockStateInterface.getBlock(pos).equals(Blocks.AIR);
}
public static boolean isAir(IBlockState state) {
return state.getBlock().equals(Blocks.AIR);
}
static boolean canFall(BlockPos pos) {
return BlockStateInterface.get(pos).getBlock() instanceof BlockFalling;
}
}

View File

@@ -0,0 +1,115 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package baritone.bot.utils;
import baritone.bot.Baritone;
import baritone.bot.Settings;
import baritone.bot.behavior.Behavior;
import baritone.bot.behavior.impl.PathingBehavior;
import baritone.bot.event.events.ChatEvent;
import baritone.bot.pathing.goals.Goal;
import baritone.bot.pathing.goals.GoalBlock;
import baritone.bot.pathing.goals.GoalXZ;
import baritone.bot.pathing.goals.GoalYLevel;
import net.minecraft.util.math.BlockPos;
import java.util.List;
public class ExampleBaritoneControl extends Behavior {
public static ExampleBaritoneControl INSTANCE = new ExampleBaritoneControl();
private ExampleBaritoneControl() {
}
public void initAndRegister() {
Baritone.INSTANCE.registerBehavior(this);
}
@Override
public void onSendChatMessage(ChatEvent event) {
if (!Baritone.settings().chatControl.get()) {
return;
}
String msg = event.getMessage();
if (msg.toLowerCase().startsWith("goal")) {
event.cancel();
String[] params = msg.toLowerCase().substring(4).trim().split(" ");
if (params[0].equals("")) {
params = new String[]{};
}
Goal goal;
try {
switch (params.length) {
case 0:
goal = new GoalBlock(playerFeet());
break;
case 1:
if (params[0].equals("clear") || params[0].equals("none")) {
goal = null;
} else {
goal = new GoalYLevel(Integer.parseInt(params[0]));
}
break;
case 2:
goal = new GoalXZ(Integer.parseInt(params[0]), Integer.parseInt(params[1]));
break;
case 3:
goal = new GoalBlock(new BlockPos(Integer.parseInt(params[0]), Integer.parseInt(params[1]), Integer.parseInt(params[2])));
break;
default:
displayChatMessageRaw("unable to understand lol");
return;
}
} catch (NumberFormatException ex) {
displayChatMessageRaw("unable to parse integer " + ex);
return;
}
PathingBehavior.INSTANCE.setGoal(goal);
displayChatMessageRaw("Goal: " + goal);
return;
}
if (msg.equals("path")) {
PathingBehavior.INSTANCE.path();
event.cancel();
return;
}
if (msg.toLowerCase().equals("cancel")) {
PathingBehavior.INSTANCE.cancel();
event.cancel();
displayChatMessageRaw("ok canceled");
return;
}
if (msg.toLowerCase().startsWith("thisway")) {
Goal goal = GoalXZ.fromDirection(playerFeetAsVec(), player().rotationYaw, Double.parseDouble(msg.substring(7).trim()));
PathingBehavior.INSTANCE.setGoal(goal);
displayChatMessageRaw("Goal: " + goal);
event.cancel();
return;
}
List<Settings.Setting<Boolean>> toggleable = Baritone.settings().getByValueType(Boolean.class);
for (Settings.Setting<Boolean> setting : toggleable) {
if (msg.toLowerCase().equals(setting.getName().toLowerCase())) {
setting.value ^= true;
event.cancel();
displayChatMessageRaw("Toggled " + setting.getName() + " to " + setting.value);
return;
}
}
}
}

View File

@@ -0,0 +1,56 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package baritone.bot.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* @author Brady
* @since 8/3/2018 10:18 PM
*/
public final class GZIPUtils {
private GZIPUtils() {
}
public static byte[] compress(byte[] in) throws IOException {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream(in.length);
try (GZIPOutputStream gzipStream = new GZIPOutputStream(byteStream)) {
gzipStream.write(in);
}
return byteStream.toByteArray();
}
public static byte[] decompress(InputStream in) throws IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
try (GZIPInputStream gzipStream = new GZIPInputStream(in)) {
byte[] buffer = new byte[1024];
int len;
while ((len = gzipStream.read(buffer)) > 0) {
outStream.write(buffer, 0, len);
}
}
return outStream.toByteArray();
}
}

View File

@@ -15,18 +15,21 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.utils;
package baritone.bot.utils;
import baritone.Baritone;
import net.minecraft.block.BlockSlab;
import baritone.bot.Baritone;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.gui.GuiNewChat;
import net.minecraft.client.gui.GuiUtilRenderComponents;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextFormatting;
import java.util.List;
/**
* @author Brady
@@ -34,14 +37,6 @@ import net.minecraft.util.text.TextFormatting;
*/
public interface Helper {
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();
default EntityPlayerSP player() {
@@ -54,11 +49,10 @@ public interface Helper {
default BlockPos playerFeet() {
// TODO find a better way to deal with soul sand!!!!!
BlockPos feet = new BlockPos(player().posX, player().posY + 0.1251, player().posZ);
if (BlockStateInterface.get(feet).getBlock() instanceof BlockSlab) {
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) {
return feet.up();
}
return feet;
}*/
}
default Vec3d playerFeetAsVec() {
@@ -79,10 +73,14 @@ public interface Helper {
System.out.println(message);
return;
}
GuiNewChat gui = mc.ingameGUI.getChatGUI();
int normalMaxWidth = MathHelper.floor((float) gui.getChatWidth() / gui.getChatScale());
int widthWithStyleFormat = normalMaxWidth - 2;
List<ITextComponent> list = GuiUtilRenderComponents.splitText(new TextComponentString("§5[§dBaritone§5]§7 " + message), widthWithStyleFormat,
this.mc.fontRenderer, false, true);
for (ITextComponent component : list) {
ITextComponent component = MESSAGE_PREFIX.createCopy();
component.getStyle().setColor(TextFormatting.GRAY);
component.appendSibling(new TextComponentString(" " + message));
mc.ingameGUI.getChatGUI().printChatMessage(component);
gui.printChatMessage(new TextComponentString("§7" + component.getUnformattedText()));
}
}
}

View File

@@ -32,7 +32,7 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.utils;
package baritone.bot.utils;
import net.minecraft.client.settings.KeyBinding;
import org.lwjgl.input.Keyboard;
@@ -84,6 +84,8 @@ public final class InputOverrideHandler implements Helper {
* @param forced Whether or not the state is being forced
*/
public final void setInputForceState(Input input, boolean forced) {
if (!forced)
System.out.println(input);
inputForceStateMap.put(input.getKeyBinding(), forced);
}

View File

@@ -15,16 +15,14 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.utils;
package baritone.bot.utils;
import baritone.Baritone;
import baritone.pathing.goals.Goal;
import baritone.pathing.goals.GoalComposite;
import baritone.pathing.goals.GoalTwoBlocks;
import baritone.pathing.goals.GoalXZ;
import baritone.pathing.path.IPath;
import baritone.utils.interfaces.IGoalRenderPos;
import net.minecraft.util.math.BlockPos;
import baritone.bot.Baritone;
import baritone.bot.pathing.goals.Goal;
import baritone.bot.pathing.goals.GoalBlock;
import baritone.bot.pathing.goals.GoalXZ;
import baritone.bot.pathing.path.IPath;
import baritone.bot.utils.pathing.BetterBlockPos;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
@@ -36,7 +34,6 @@ import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import java.awt.*;
import java.util.Collection;
@@ -60,10 +57,10 @@ public final class PathRenderer implements Helper {
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO);
GlStateManager.color(color.getColorComponents(null)[0], color.getColorComponents(null)[1], color.getColorComponents(null)[2], 0.4F);
GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.get());
GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidth.get());
GlStateManager.disableTexture2D();
GlStateManager.depthMask(false);
List<BlockPos> positions = path.positions();
List<BetterBlockPos> positions = path.positions();
int next;
Tessellator tessellator = Tessellator.getInstance();
fadeStart += startIndex;
@@ -123,7 +120,7 @@ public final class PathRenderer implements Helper {
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0);
GlStateManager.color(color.getColorComponents(null)[0], color.getColorComponents(null)[1], color.getColorComponents(null)[2], 0.4F);
GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.get());
GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidth.get());
GlStateManager.disableTexture2D();
GlStateManager.depthMask(false);
float expand = 0.002F;
@@ -173,6 +170,13 @@ public final class PathRenderer implements Helper {
}
public static void drawLitDankGoalBox(EntityPlayer player, Goal goal, float partialTicks, Color color) {
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0);
GlStateManager.color(color.getColorComponents(null)[0], color.getColorComponents(null)[1], color.getColorComponents(null)[2], 0.6F);
GlStateManager.glLineWidth(Baritone.settings().goalRenderLineWidth.get());
GlStateManager.disableTexture2D();
GlStateManager.depthMask(false);
float expand = 0.002F;
double renderPosX = player.lastTickPosX + (player.posX - player.lastTickPosX) * (double) partialTicks;
double renderPosY = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double) partialTicks;
double renderPosZ = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double) partialTicks;
@@ -185,25 +189,17 @@ public final class PathRenderer implements Helper {
double maxY;
double y1;
double y2;
if (goal instanceof IGoalRenderPos) {
BlockPos goalPos = ((IGoalRenderPos) goal).getGoalPos();
if (goal instanceof GoalBlock) {
BlockPos goalPos = ((GoalBlock) goal).getGoalPos();
minX = goalPos.getX() + 0.002 - renderPosX;
maxX = goalPos.getX() + 1 - 0.002 - renderPosX;
minZ = goalPos.getZ() + 0.002 - renderPosZ;
maxZ = goalPos.getZ() + 1 - 0.002 - renderPosZ;
double y = MathHelper.cos((float) (((float) ((System.nanoTime() / 100000L) % 20000L)) / 20000F * Math.PI * 2));
if (goal instanceof GoalTwoBlocks) {
y /= 2;
}
double y = Math.sin((System.currentTimeMillis() % 2000L) / 2000F * Math.PI * 2);
y1 = 1 + y + goalPos.getY() - renderPosY;
y2 = 1 - y + goalPos.getY() - renderPosY;
minY = goalPos.getY() - renderPosY;
maxY = minY + 2;
if (goal instanceof GoalTwoBlocks) {
y1 -= 0.5;
y2 -= 0.5;
maxY--;
}
} else if (goal instanceof GoalXZ) {
GoalXZ goalPos = (GoalXZ) goal;
@@ -216,22 +212,11 @@ public final class PathRenderer implements Helper {
y2 = 0;
minY = 0 - renderPosY;
maxY = 256 - renderPosY;
} else if (goal instanceof GoalComposite) {
for (Goal g : ((GoalComposite) goal).goals()) {
drawLitDankGoalBox(player, g, partialTicks, color);
}
return;
} else {
// TODO GoalComposite
return;
}
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0);
GlStateManager.color(color.getColorComponents(null)[0], color.getColorComponents(null)[1], color.getColorComponents(null)[2], 0.6F);
GlStateManager.glLineWidth(Baritone.settings().goalRenderLineWidthPixels.get());
GlStateManager.disableTexture2D();
GlStateManager.depthMask(false);
if (y1 != 0) {
BUFFER.begin(GL_LINE_STRIP, DefaultVertexFormats.POSITION);
BUFFER.pos(minX, y1, minZ).endVertex();

View File

@@ -15,7 +15,7 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.utils;
package baritone.bot.utils;
import net.minecraft.util.Tuple;

View File

@@ -0,0 +1,148 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package baritone.bot.utils;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.item.Item;
import net.minecraft.item.ItemAir;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemTool;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A cached list of the best tools on the hotbar for any block
*
* @author avecowa
*/
public class ToolSet implements Helper {
/**
* A list of tools on the hotbar that should be considered.
* Note that if there are no tools on the hotbar this list will still have one (null) entry.
*/
private List<ItemTool> tools;
/**
* A mapping from the tools array to what hotbar slots the tool is actually in.
* tools.get(i) will be on your hotbar in slot slots.get(i)
*/
private List<Byte> slots;
/**
* A mapping from a block to which tool index is best for it.
* The values in this map are *not* hotbar slots indexes, they need to be looked up in slots
* in order to be converted into hotbar slots.
*/
private Map<Block, Byte> cache = new HashMap<>();
/**
* Create a toolset from the current player's inventory (but don't calculate any hardness values just yet)
*/
public ToolSet() {
EntityPlayerSP p = Minecraft.getMinecraft().player;
NonNullList<ItemStack> inv = p.inventory.mainInventory;
tools = new ArrayList<>();
slots = new ArrayList<>();
boolean fnull = false;
for (byte i = 0; i < 9; i++) {
if (!fnull || ((!(inv.get(i).getItem() instanceof ItemAir)) && inv.get(i).getItem() instanceof ItemTool)) {
tools.add(inv.get(i).getItem() instanceof ItemTool ? (ItemTool) inv.get(i).getItem() : null);
slots.add(i);
fnull |= (inv.get(i).getItem() instanceof ItemAir) || (!inv.get(i).getItem().isDamageable());
}
}
}
/**
* A caching wrapper around getBestToolIndex
*
* @param state the blockstate to be mined
* @return get which tool on the hotbar is best for mining it
*/
public Item getBestTool(IBlockState state) {
return tools.get(cache.computeIfAbsent(state.getBlock(), block -> getBestToolIndex(state)));
}
/**
* Calculate which tool on the hotbar is best for mining
*
* @param b the blockstate to be mined
* @return a byte indicating the index in the tools array that worked best
*/
private byte getBestToolIndex(IBlockState b) {
byte best = 0;
float value = -1;
for (byte i = 0; i < tools.size(); i++) {
Item item = tools.get(i);
if (item == null)
continue;
float v = item.getDestroySpeed(new ItemStack(item), b);
if (v > value || value == -1) {
value = v;
best = i;
}
}
return best;
}
/**
* Get which hotbar slot should be selected for fastest mining
*
* @param state the blockstate to be mined
* @return a byte indicating which hotbar slot worked best
*/
public byte getBestSlot(IBlockState state) {
return slots.get(cache.computeIfAbsent(state.getBlock(), block -> getBestToolIndex(state)));
}
/**
* Using the best tool on the hotbar, how long would it take to mine this block
*
* @param state the blockstate to be mined
* @param pos the blockpos to be mined
* @return how long it would take in ticks
*/
public double getStrVsBlock(IBlockState state, BlockPos pos) {
// Calculate the slot with the best item
byte slot = this.getBestSlot(state);
// Save the old current slot
int oldSlot = player().inventory.currentItem;
// Set the best slot
player().inventory.currentItem = slot;
// Calculate the relative hardness of the block to the player
float hardness = state.getPlayerRelativeBlockHardness(player(), world(), pos);
// Restore the old slot
player().inventory.currentItem = oldSlot;
return hardness;
}
}

View File

@@ -15,7 +15,7 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.utils;
package baritone.bot.utils;
import net.minecraft.block.BlockFire;
import net.minecraft.block.state.IBlockState;
@@ -54,9 +54,9 @@ public final class Utils {
*/
public static Rotation calcRotationFromVec3d(Vec3d orig, Vec3d dest) {
double[] delta = {orig.x - dest.x, orig.y - dest.y, orig.z - dest.z};
double yaw = MathHelper.atan2(delta[0], -delta[2]);
double yaw = Math.atan2(delta[0], -delta[2]);
double dist = Math.sqrt(delta[0] * delta[0] + delta[2] * delta[2]);
double pitch = MathHelper.atan2(delta[1], dist);
double pitch = Math.atan2(delta[1], dist);
return new Rotation(
(float) radToDeg(yaw),
(float) radToDeg(pitch)

View File

@@ -0,0 +1,118 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package baritone.bot.utils.pathing;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3i;
/**
* A better BlockPos that has fewer hash collisions (and slightly more performant offsets)
*
* @author leijurv
*/
public class BetterBlockPos extends BlockPos {
private final int x;
private final int y;
private final int z;
private final int hashCode;
public BetterBlockPos(int x, int y, int z) {
super(x, y, z);
this.x = x;
this.y = y;
this.z = z;
/*
* This is the hashcode implementation of Vec3i, the superclass of BlockPos
*
* public int hashCode() {
* return (this.getY() + this.getZ() * 31) * 31 + this.getX();
* }
*
* That is terrible and has tons of collisions and makes the HashMap terribly inefficient.
*
* That's why we grab out the X, Y, Z and calculate our own hashcode
*/
int hash = 3241;
hash = 3457689 * hash + x;
hash = 8734625 * hash + y;
hash = 2873465 * hash + z;
this.hashCode = hash;
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (o instanceof BetterBlockPos) {
BetterBlockPos oth = (BetterBlockPos) o;
if (oth.hashCode != hashCode) {
return false;
}
return oth.x == x && oth.y == y && oth.z == z;
}
// during path execution, like "if (whereShouldIBe.equals(whereAmI)) {"
// sometimes we compare a BlockPos to a BetterBlockPos
BlockPos oth = (BlockPos) o;
return oth.getX() == x && oth.getY() == y && oth.getZ() == z;
}
@Override
public BlockPos up() {
// this is unimaginably faster than blockpos.up
// that literally calls
// this.up(1)
// which calls this.offset(EnumFacing.UP, 1)
// which does return n == 0 ? this : new BlockPos(this.getX() + facing.getXOffset() * n, this.getY() + facing.getYOffset() * n, this.getZ() + facing.getZOffset() * n);
// how many function calls is that? up(), up(int), offset(EnumFacing, int), new BlockPos, getX, getXOffset, getY, getYOffset, getZ, getZOffset
// that's ten.
// this is one function call.
return new BetterBlockPos(x, y + 1, z);
}
@Override
public BlockPos up(int amt) {
// see comment in up()
return amt == 0 ? this : new BetterBlockPos(x, y + amt, z);
}
@Override
public BlockPos down() {
// see comment in up()
return new BetterBlockPos(x, y - 1, z);
}
@Override
public BlockPos down(int amt) {
// see comment in up()
return new BetterBlockPos(x, y - amt, z);
}
@Override
public BlockPos offset(EnumFacing dir) {
Vec3i vec = dir.getDirectionVec();
return new BetterBlockPos(x + vec.getX(), y + vec.getY(), z + vec.getZ());
}
}

View File

@@ -15,10 +15,9 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.utils.pathing;
package baritone.bot.utils.pathing;
import baritone.utils.Helper;
import net.minecraft.block.state.IBlockState;
import baritone.bot.utils.Helper;
import net.minecraft.util.math.BlockPos;
/**
@@ -27,9 +26,9 @@ import net.minecraft.util.math.BlockPos;
*/
public interface IBlockTypeAccess extends Helper {
IBlockState getBlock(int x, int y, int z);
PathingBlockType getBlockType(int x, int y, int z);
default IBlockState getBlock(BlockPos pos) {
return getBlock(pos.getX(), pos.getY(), pos.getZ());
default PathingBlockType getBlockType(BlockPos pos) {
return getBlockType(pos.getX(), pos.getY(), pos.getZ());
}
}

View File

@@ -15,7 +15,7 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.utils.pathing;
package baritone.bot.utils.pathing;
/**
* @author Brady
@@ -23,7 +23,7 @@ package baritone.utils.pathing;
*/
public enum PathingBlockType {
AIR(0b00),
AIR (0b00),
WATER(0b01),
AVOID(0b10),
SOLID(0b11);
@@ -31,7 +31,7 @@ public enum PathingBlockType {
private final boolean[] bits;
PathingBlockType(int bits) {
this.bits = new boolean[]{
this.bits = new boolean[] {
(bits & 0b10) != 0,
(bits & 0b01) != 0
};
@@ -42,18 +42,11 @@ public enum PathingBlockType {
}
public static PathingBlockType fromBits(boolean b1, boolean b2) {
if (b1) {
if (b2) {
return PathingBlockType.SOLID;
} else {
return PathingBlockType.AVOID;
}
} else {
if (b2) {
return PathingBlockType.WATER;
} else {
return PathingBlockType.AIR;
}
}
for (PathingBlockType type : values())
if (type.bits[0] == b1 && type.bits[1] == b2)
return type;
// This will never happen, but if it does, assume it's just AIR
return PathingBlockType.AIR;
}
}

View File

@@ -1,206 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 <https://www.gnu.org/licenses/>.
*/
package baritone.chunk;
import baritone.utils.pathing.IBlockTypeAccess;
import baritone.utils.pathing.PathingBlockType;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.util.math.BlockPos;
import java.util.*;
/**
* @author Brady
* @since 8/3/2018 1:04 AM
*/
public final class CachedChunk implements IBlockTypeAccess {
public static final Set<Block> BLOCKS_TO_KEEP_TRACK_OF = Collections.unmodifiableSet(new HashSet<Block>() {{
add(Blocks.DIAMOND_ORE);
add(Blocks.DIAMOND_BLOCK);
//add(Blocks.COAL_ORE);
add(Blocks.COAL_BLOCK);
//add(Blocks.IRON_ORE);
add(Blocks.IRON_BLOCK);
//add(Blocks.GOLD_ORE);
add(Blocks.GOLD_BLOCK);
add(Blocks.EMERALD_ORE);
add(Blocks.EMERALD_BLOCK);
add(Blocks.ENDER_CHEST);
add(Blocks.FURNACE);
add(Blocks.CHEST);
add(Blocks.END_PORTAL);
add(Blocks.END_PORTAL_FRAME);
add(Blocks.MOB_SPAWNER);
// TODO add all shulker colors
add(Blocks.PORTAL);
add(Blocks.HOPPER);
add(Blocks.BEACON);
add(Blocks.BREWING_STAND);
add(Blocks.SKULL);
add(Blocks.ENCHANTING_TABLE);
add(Blocks.ANVIL);
add(Blocks.LIT_FURNACE);
add(Blocks.BED);
add(Blocks.DRAGON_EGG);
add(Blocks.JUKEBOX);
add(Blocks.END_GATEWAY);
}});
/**
* The size of the chunk data in bits. Equal to 16 KiB.
* <p>
* Chunks are 16x16x256, each block requires 2 bits.
*/
public static final int SIZE = 2 * 16 * 16 * 256;
/**
* The size of the chunk data in bytes. Equal to 16 KiB.
*/
public static final int SIZE_IN_BYTES = SIZE / 8;
/**
* The chunk x coordinate
*/
public final int x;
/**
* The chunk z coordinate
*/
public final int z;
/**
* The actual raw data of this packed chunk.
* <p>
* Each block is expressed as 2 bits giving a total of 16 KiB
*/
private final BitSet data;
/**
* The block names of each surface level block for generating an overview
*/
private final String[] overview;
private final int[] heightMap;
private final Map<String, List<BlockPos>> specialBlockLocations;
CachedChunk(int x, int z, BitSet data, String[] overview, Map<String, List<BlockPos>> specialBlockLocations) {
validateSize(data);
this.x = x;
this.z = z;
this.data = data;
this.overview = overview;
this.heightMap = new int[256];
this.specialBlockLocations = specialBlockLocations;
calculateHeightMap();
}
@Override
public final IBlockState getBlock(int x, int y, int z) {
int internalPos = z << 4 | x;
if (heightMap[internalPos] == y) {
// we have this exact block, it's a surface block
IBlockState state = ChunkPacker.stringToBlock(overview[internalPos]).getDefaultState();
/*System.out.println("Saying that " + x + "," + y + "," + z + " is " + state);
if (!Minecraft.getMinecraft().world.getBlockState(new BlockPos(x + this.x * 16, y, z + this.z * 16)).getBlock().equals(state.getBlock())) {
throw new IllegalStateException("failed " + Minecraft.getMinecraft().world.getBlockState(new BlockPos(x + this.x * 16, y, z + this.z * 16)).getBlock() + " " + state.getBlock() + " " + (x + this.x * 16) + " " + y + " " + (z + this.z * 16));
}*/
return state;
}
PathingBlockType type = getType(x, y, z);
return ChunkPacker.pathingTypeToBlock(type);
}
private PathingBlockType getType(int x, int y, int z) {
int index = getPositionIndex(x, y, z);
return PathingBlockType.fromBits(data.get(index), data.get(index + 1));
}
private void calculateHeightMap() {
for (int z = 0; z < 16; z++) {
for (int x = 0; x < 16; x++) {
int index = z << 4 | x;
heightMap[index] = 0;
for (int y = 256; y >= 0; y--) {
int i = getPositionIndex(x, y, z);
if (data.get(i) || data.get(i + 1)) {
heightMap[index] = y;
break;
}
}
}
}
}
public final String[] getOverview() {
return overview;
}
public final Map<String, List<BlockPos>> getRelativeBlocks() {
return specialBlockLocations;
}
public final LinkedList<BlockPos> getAbsoluteBlocks(String blockType) {
if (specialBlockLocations.get(blockType) == null) {
return null;
}
LinkedList<BlockPos> res = new LinkedList<>();
for (BlockPos pos : specialBlockLocations.get(blockType)) {
res.add(new BlockPos(pos.getX() + x * 16, pos.getY(), pos.getZ() + z * 16));
}
return res;
}
/**
* @return Returns the raw packed chunk data as a byte array
*/
public final byte[] toByteArray() {
return this.data.toByteArray();
}
/**
* Returns the raw bit index of the specified position
*
* @param x The x position
* @param y The y position
* @param z The z position
* @return The bit index
*/
public static int getPositionIndex(int x, int y, int z) {
return (x << 1) | (z << 5) | (y << 9);
}
/**
* Validates the size of an input {@link BitSet} containing the raw
* packed chunk data. Sizes that exceed {@link CachedChunk#SIZE} are
* considered invalid, and thus, an exception will be thrown.
*
* @param data The raw data
* @throws IllegalArgumentException if the bitset size exceeds the maximum size
*/
private static void validateSize(BitSet data) {
if (data.size() > SIZE) {
throw new IllegalArgumentException("BitSet of invalid length provided");
}
}
}

View File

@@ -1,297 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 <https://www.gnu.org/licenses/>.
*/
package baritone.chunk;
import baritone.utils.pathing.IBlockTypeAccess;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.BlockPos;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* @author Brady
* @since 8/3/2018 9:35 PM
*/
public final class CachedRegion implements IBlockTypeAccess {
private static final byte CHUNK_NOT_PRESENT = 0;
private static final byte CHUNK_PRESENT = 1;
/**
* Magic value to detect invalid cache files, or incompatible cache files saved in an old version of Baritone
*/
private static final int CACHED_REGION_MAGIC = 456022910;
/**
* All of the chunks in this region: A 32x32 array of them.
*/
private final CachedChunk[][] chunks = new CachedChunk[32][32];
/**
* The region x coordinate
*/
private final int x;
/**
* The region z coordinate
*/
private final int z;
/**
* Has this region been modified since its most recent load or save
*/
private boolean hasUnsavedChanges;
CachedRegion(int x, int z) {
this.x = x;
this.z = z;
this.hasUnsavedChanges = false;
}
@Override
public final IBlockState getBlock(int x, int y, int z) {
CachedChunk chunk = chunks[x >> 4][z >> 4];
if (chunk != null) {
return chunk.getBlock(x & 15, y, z & 15);
}
return null;
}
public final boolean isCached(int x, int z) {
return chunks[x >> 4][z >> 4] != null;
}
public final LinkedList<BlockPos> getLocationsOf(String block) {
LinkedList<BlockPos> res = new LinkedList<>();
for (int chunkX = 0; chunkX < 32; chunkX++) {
for (int chunkZ = 0; chunkZ < 32; chunkZ++) {
if (chunks[chunkX][chunkZ] == null) {
continue;
}
List<BlockPos> locs = chunks[chunkX][chunkZ].getAbsoluteBlocks(block);
if (locs == null) {
continue;
}
for (BlockPos pos : locs) {
res.add(pos);
}
}
}
return res;
}
final synchronized void updateCachedChunk(int chunkX, int chunkZ, CachedChunk chunk) {
this.chunks[chunkX][chunkZ] = chunk;
hasUnsavedChanges = true;
}
public synchronized final void save(String directory) {
if (!hasUnsavedChanges) {
return;
}
try {
Path path = Paths.get(directory);
if (!Files.exists(path)) {
Files.createDirectories(path);
}
System.out.println("Saving region " + x + "," + z + " to disk " + path);
Path regionFile = getRegionFile(path, this.x, this.z);
if (!Files.exists(regionFile)) {
Files.createFile(regionFile);
}
try (
FileOutputStream fileOut = new FileOutputStream(regionFile.toFile());
GZIPOutputStream gzipOut = new GZIPOutputStream(fileOut, 16384);
DataOutputStream out = new DataOutputStream(gzipOut)
) {
out.writeInt(CACHED_REGION_MAGIC);
for (int z = 0; z < 32; z++) {
for (int x = 0; x < 32; x++) {
CachedChunk chunk = this.chunks[x][z];
if (chunk == null) {
out.write(CHUNK_NOT_PRESENT);
} else {
out.write(CHUNK_PRESENT);
byte[] chunkBytes = chunk.toByteArray();
out.write(chunkBytes);
// Messy, but fills the empty 0s that should be trailing to fill up the space.
out.write(new byte[CachedChunk.SIZE_IN_BYTES - chunkBytes.length]);
}
}
}
for (int z = 0; z < 32; z++) {
for (int x = 0; x < 32; x++) {
if (chunks[x][z] != null) {
for (int i = 0; i < 256; i++) {
out.writeUTF(chunks[x][z].getOverview()[i]);
}
}
}
}
for (int z = 0; z < 32; z++) {
for (int x = 0; x < 32; x++) {
if (chunks[x][z] != null) {
Map<String, List<BlockPos>> locs = chunks[x][z].getRelativeBlocks();
out.writeShort(locs.entrySet().size());
for (Map.Entry<String, List<BlockPos>> entry : locs.entrySet()) {
out.writeUTF(entry.getKey());
out.writeShort(entry.getValue().size());
for (BlockPos pos : entry.getValue()) {
out.writeByte((byte) (pos.getZ() << 4 | pos.getX()));
out.writeByte((byte) (pos.getY()));
}
}
}
}
}
}
hasUnsavedChanges = false;
System.out.println("Saved region successfully");
} catch (IOException ex) {
ex.printStackTrace();
}
}
public synchronized void load(String directory) {
try {
Path path = Paths.get(directory);
if (!Files.exists(path)) {
Files.createDirectories(path);
}
Path regionFile = getRegionFile(path, this.x, this.z);
if (!Files.exists(regionFile)) {
return;
}
System.out.println("Loading region " + x + "," + z + " from disk " + path);
long start = System.nanoTime() / 1000000L;
try (
FileInputStream fileIn = new FileInputStream(regionFile.toFile());
GZIPInputStream gzipIn = new GZIPInputStream(fileIn, 32768);
DataInputStream in = new DataInputStream(gzipIn)
) {
int magic = in.readInt();
if (magic != CACHED_REGION_MAGIC) {
// in the future, if we change the format on disk
// we can keep converters for the old format
// by switching on the magic value, and either loading it normally, or loading through a converter.
throw new IOException("Bad magic value " + magic);
}
CachedChunk[][] tmpCached = new CachedChunk[32][32];
Map<String, List<BlockPos>>[][] location = new Map[32][32];
for (int z = 0; z < 32; z++) {
for (int x = 0; x < 32; x++) {
int isChunkPresent = in.read();
switch (isChunkPresent) {
case CHUNK_PRESENT:
byte[] bytes = new byte[CachedChunk.SIZE_IN_BYTES];
in.readFully(bytes);
location[x][z] = new HashMap<>();
int regionX = this.x;
int regionZ = this.z;
int chunkX = x + 32 * regionX;
int chunkZ = z + 32 * regionZ;
tmpCached[x][z] = new CachedChunk(chunkX, chunkZ, BitSet.valueOf(bytes), new String[256], location[x][z]);
break;
case CHUNK_NOT_PRESENT:
tmpCached[x][z] = null;
break;
default:
throw new IOException("Malformed stream");
}
}
}
for (int z = 0; z < 32; z++) {
for (int x = 0; x < 32; x++) {
if (tmpCached[x][z] != null) {
for (int i = 0; i < 256; i++) {
tmpCached[x][z].getOverview()[i] = in.readUTF();
}
}
}
}
for (int z = 0; z < 32; z++) {
for (int x = 0; x < 32; x++) {
if (tmpCached[x][z] != null) {
// 16 * 16 * 256 = 65536 so a short is enough
// ^ haha jokes on leijurv, java doesn't have unsigned types so that isn't correct
// also why would you have more than 32767 special blocks in a chunk
// haha double jokes on you now it works for 65535 not just 32767
int numSpecialBlockTypes = in.readShort() & 0xffff;
for (int i = 0; i < numSpecialBlockTypes; i++) {
String blockName = in.readUTF();
List<BlockPos> locs = new ArrayList<>();
location[x][z].put(blockName, locs);
int numLocations = in.readShort() & 0xffff;
if (numLocations == 0) {
// an entire chunk full of air can happen in the end
numLocations = 65536;
}
for (int j = 0; j < numLocations; j++) {
byte xz = in.readByte();
int X = xz & 0x0f;
int Z = (xz >>> 4) & 0x0f;
int Y = in.readByte() & 0xff;
locs.add(new BlockPos(X, Y, Z));
}
}
}
}
}
// only if the entire file was uncorrupted do we actually set the chunks
for (int x = 0; x < 32; x++) {
for (int z = 0; z < 32; z++) {
this.chunks[x][z] = tmpCached[x][z];
}
}
}
hasUnsavedChanges = false;
long end = System.nanoTime() / 1000000L;
System.out.println("Loaded region successfully in " + (end - start) + "ms");
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* @return The region x coordinate
*/
public final int getX() {
return this.x;
}
/**
* @return The region z coordinate
*/
public final int getZ() {
return this.z;
}
private static Path getRegionFile(Path cacheDir, int regionX, int regionZ) {
return Paths.get(cacheDir.toString(), "r." + regionX + "." + regionZ + ".bcr");
}
}

View File

@@ -1,255 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 <https://www.gnu.org/licenses/>.
*/
package baritone.chunk;
import baritone.Baritone;
import baritone.utils.pathing.IBlockTypeAccess;
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.chunk.Chunk;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
/**
* @author Brady
* @since 8/4/2018 12:02 AM
*/
public final class CachedWorld implements IBlockTypeAccess {
/**
* The maximum number of regions in any direction from (0,0)
*/
private static final int REGION_MAX = 58594;
/**
* A map of all of the cached regions.
*/
private Long2ObjectMap<CachedRegion> cachedRegions = new Long2ObjectOpenHashMap<>();
/**
* The directory that the cached region files are saved to
*/
private final String directory;
private final LinkedBlockingQueue<Chunk> toPack = new LinkedBlockingQueue<>();
CachedWorld(Path directory) {
if (!Files.exists(directory)) {
try {
Files.createDirectories(directory);
} catch (IOException ignored) {
}
}
this.directory = directory.toString();
System.out.println("Cached world directory: " + directory);
// Insert an invalid region element
cachedRegions.put(0, null);
new PackerThread().start();
new Thread(() -> {
try {
Thread.sleep(30000);
while (true) {
// since a region only saves if it's been modified since its last save
// saving every 10 minutes means that once it's time to exit
// we'll only have a couple regions to save
save();
Thread.sleep(600000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
public final void queueForPacking(Chunk chunk) {
try {
toPack.put(chunk);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public final IBlockState getBlock(int x, int y, int z) {
// no point in doing getOrCreate region, if we don't have it we don't have it
CachedRegion region = getRegion(x >> 9, z >> 9);
if (region == null) {
return null;
}
return region.getBlock(x & 511, y, z & 511);
}
public final boolean isCached(BlockPos pos) {
int x = pos.getX();
int z = pos.getZ();
CachedRegion region = getRegion(x >> 9, z >> 9);
if (region == null) {
return false;
}
return region.isCached(x & 511, z & 511);
}
public final LinkedList<BlockPos> getLocationsOf(String block, int minimum, int maxRegionDistanceSq) {
LinkedList<BlockPos> res = new LinkedList<>();
int playerRegionX = playerFeet().getX() >> 9;
int playerRegionZ = playerFeet().getZ() >> 9;
int searchRadius = 0;
while (searchRadius <= maxRegionDistanceSq) {
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 regionX = xoff + playerRegionX;
int regionZ = zoff + playerRegionZ;
CachedRegion region = getOrCreateRegion(regionX, regionZ);
if (region != null) {
for (BlockPos pos : region.getLocationsOf(block)) {
res.add(pos);
}
}
}
}
if (res.size() >= minimum) {
return res;
}
searchRadius++;
}
return res;
}
private void updateCachedChunk(CachedChunk chunk) {
CachedRegion region = getOrCreateRegion(chunk.x >> 5, chunk.z >> 5);
region.updateCachedChunk(chunk.x & 31, chunk.z & 31, chunk);
}
public final void save() {
if (!Baritone.settings().chunkCaching.get()) {
System.out.println("Not saving to disk; chunk caching is disabled.");
return;
}
long start = System.nanoTime() / 1000000L;
allRegions().parallelStream().forEach(region -> {
if (region != null) {
region.save(this.directory);
}
});
long now = System.nanoTime() / 1000000L;
System.out.println("World save took " + (now - start) + "ms");
}
private synchronized List<CachedRegion> allRegions() {
return new ArrayList<>(this.cachedRegions.values());
}
public final void reloadAllFromDisk() {
long start = System.nanoTime() / 1000000L;
allRegions().forEach(region -> {
if (region != null) {
region.load(this.directory);
}
});
long now = System.nanoTime() / 1000000L;
System.out.println("World load took " + (now - start) + "ms");
}
/**
* Returns the region at the specified region coordinates
*
* @param regionX The region X coordinate
* @param regionZ The region Z coordinate
* @return The region located at the specified coordinates
*/
public final synchronized CachedRegion getRegion(int regionX, int regionZ) {
return cachedRegions.get(getRegionID(regionX, regionZ));
}
/**
* Returns the region at the specified region coordinates. If a
* region is not found, then a new one is created.
*
* @param regionX The region X coordinate
* @param regionZ The region Z coordinate
* @return The region located at the specified coordinates
*/
private synchronized CachedRegion getOrCreateRegion(int regionX, int regionZ) {
return cachedRegions.computeIfAbsent(getRegionID(regionX, regionZ), id -> {
CachedRegion newRegion = new CachedRegion(regionX, regionZ);
newRegion.load(this.directory);
return newRegion;
});
}
/**
* Returns the region ID based on the region coordinates. 0 will be
* returned if the specified region coordinates are out of bounds.
*
* @param regionX The region X coordinate
* @param regionZ The region Z coordinate
* @return The region ID
*/
private long getRegionID(int regionX, int regionZ) {
if (!isRegionInWorld(regionX, regionZ)) {
return 0;
}
return (long) regionX & 0xFFFFFFFFL | ((long) regionZ & 0xFFFFFFFFL) << 32;
}
/**
* Returns whether or not the specified region coordinates is within the world bounds.
*
* @param regionX The region X coordinate
* @param regionZ The region Z coordinate
* @return Whether or not the region is in world bounds
*/
private boolean isRegionInWorld(int regionX, int regionZ) {
return regionX <= REGION_MAX && regionX >= -REGION_MAX && regionZ <= REGION_MAX && regionZ >= -REGION_MAX;
}
private class PackerThread extends Thread {
public void run() {
while (true) {
LinkedBlockingQueue<Chunk> queue = toPack;
if (queue == null) {
break;
}
try {
Chunk chunk = queue.take();
CachedChunk cached = ChunkPacker.pack(chunk);
CachedWorld.this.updateCachedChunk(cached);
//System.out.println("Processed chunk at " + chunk.x + "," + chunk.z);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
}
}
}

View File

@@ -1,195 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 <https://www.gnu.org/licenses/>.
*/
package baritone.chunk;
import baritone.pathing.movement.MovementHelper;
import baritone.utils.Helper;
import baritone.utils.pathing.PathingBlockType;
import net.minecraft.block.Block;
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.*;
/**
* @author Brady
* @since 8/3/2018 1:09 AM
*/
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<String, List<BlockPos>> specialBlocks = new HashMap<>();
BitSet bitSet = new BitSet(CachedChunk.SIZE);
try {
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();
}
//System.out.println("Packed special blocks: " + specialBlocks);
long end = System.nanoTime() / 1000000L;
//System.out.println("Chunk packing took " + (end - start) + "ms for " + chunk.x + "," + chunk.z);
String[] blockNames = new String[256];
for (int z = 0; z < 16; z++) {
outerLoop:
for (int x = 0; x < 16; x++) {
for (int y = 255; y >= 0; y--) {
int index = CachedChunk.getPositionIndex(x, y, z);
if (bitSet.get(index) || bitSet.get(index + 1)) {
String name = blockToString(chunk.getBlockState(x, y, z).getBlock());
blockNames[z << 4 | x] = name;
continue outerLoop;
}
}
blockNames[z << 4 | x] = "air";
}
}
CachedChunk cached = new CachedChunk(chunk.x, chunk.z, bitSet, blockNames, specialBlocks);
return cached;
}
public static String blockToString(Block block) {
ResourceLocation loc = Block.REGISTRY.getNameForObject(block);
String name = loc.getPath(); // normally, only write the part after the minecraft:
if (!loc.getNamespace().equals("minecraft")) {
// Baritone is running on top of forge with mods installed, perhaps?
name = loc.toString(); // include the namespace with the colon
}
return name;
}
public static Block stringToBlock(String name) {
if (!name.contains(":")) {
name = "minecraft:" + name;
}
return Block.getBlockFromName(name);
}
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) || 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 == Blocks.AIR || block instanceof BlockTallGrass || block instanceof BlockDoublePlant || block instanceof BlockFlower) {
return PathingBlockType.AIR;
}
return PathingBlockType.SOLID;
}
static IBlockState pathingTypeToBlock(PathingBlockType type) {
if (type != null) {
switch (type) {
case AIR:
return Blocks.AIR.getDefaultState();
case WATER:
return Blocks.WATER.getDefaultState();
case AVOID:
return Blocks.LAVA.getDefaultState();
case SOLID:
// Dimension solid types
switch (mc.player.dimension) {
case -1:
return Blocks.NETHERRACK.getDefaultState();
case 0:
return Blocks.STONE.getDefaultState();
case 1:
return Blocks.END_STONE.getDefaultState();
}
// The fallback solid type
return Blocks.STONE.getDefaultState();
}
}
return null;
}
}

View File

@@ -1,92 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 <https://www.gnu.org/licenses/>.
*/
package baritone.chunk;
import com.google.common.collect.ImmutableList;
import net.minecraft.util.math.BlockPos;
import org.apache.commons.lang3.ArrayUtils;
import java.util.*;
/**
* A single waypoint
*
* @author leijurv
*/
public class Waypoint {
public final String name;
public final Tag tag;
private final long creationTimestamp;
public final BlockPos location;
public Waypoint(String name, Tag tag, BlockPos location) {
this(name, tag, location, System.currentTimeMillis());
}
Waypoint(String name, Tag tag, BlockPos location, long creationTimestamp) { // read from disk
this.name = name;
this.tag = tag;
this.location = location;
this.creationTimestamp = creationTimestamp;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (!(o instanceof Waypoint)) {
return false;
}
Waypoint w = (Waypoint) o;
return name.equals(w.name) && tag == w.tag && location.equals(w.location);
}
@Override
public int hashCode() {
return name.hashCode() + tag.hashCode() + location.hashCode(); //lol
}
public long creationTimestamp() {
return creationTimestamp;
}
public String toString() {
return name + " " + location.toString() + " " + new Date(creationTimestamp).toString();
}
public enum Tag {
HOME("home", "base"),
DEATH("death"),
BED("bed", "spawn"),
USER();
private static final List<Tag> TAG_LIST = ImmutableList.<Tag>builder().add(Tag.values()).build();
private final String[] names;
Tag(String... names) {
this.names = names;
}
public static Tag fromString(String name) {
return TAG_LIST.stream().filter(tag -> ArrayUtils.contains(tag.names, name.toLowerCase())).findFirst().orElse(null);
}
}
}

View File

@@ -1,125 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 <https://www.gnu.org/licenses/>.
*/
package baritone.chunk;
import net.minecraft.util.math.BlockPos;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
/**
* Waypoints for a world
*
* @author leijurv
*/
public class Waypoints {
/**
* Magic value to detect invalid waypoint files
*/
private static final long WAYPOINT_MAGIC_VALUE = 121977993584L; // good value
private final Path directory;
private final Map<Waypoint.Tag, Set<Waypoint>> waypoints;
Waypoints(Path directory) {
this.directory = directory;
if (!Files.exists(directory)) {
try {
Files.createDirectories(directory);
} catch (IOException ignored) {}
}
System.out.println("Would save waypoints to " + directory);
this.waypoints = new HashMap<>();
load();
}
private void load() {
for (Waypoint.Tag tag : Waypoint.Tag.values()) {
load(tag);
}
}
private synchronized void load(Waypoint.Tag tag) {
waypoints.put(tag, new HashSet<>());
Path fileName = directory.resolve(tag.name().toLowerCase() + ".mp4");
if (!Files.exists(fileName)) {
return;
}
try (
FileInputStream fileIn = new FileInputStream(fileName.toFile());
BufferedInputStream bufIn = new BufferedInputStream(fileIn);
DataInputStream in = new DataInputStream(bufIn)
) {
long magic = in.readLong();
if (magic != WAYPOINT_MAGIC_VALUE) {
throw new IOException("Bad magic value " + magic);
}
long length = in.readLong(); // Yes I want 9,223,372,036,854,775,807 waypoints, do you not?
while (length-- > 0) {
String name = in.readUTF();
long creationTimestamp = in.readLong();
int x = in.readInt();
int y = in.readInt();
int z = in.readInt();
waypoints.get(tag).add(new Waypoint(name, tag, new BlockPos(x, y, z), creationTimestamp));
}
} catch (IOException ignored) {}
}
private synchronized void save(Waypoint.Tag tag) {
Path fileName = directory.resolve(tag.name().toLowerCase() + ".mp4");
try (
FileOutputStream fileOut = new FileOutputStream(fileName.toFile());
BufferedOutputStream bufOut = new BufferedOutputStream(fileOut);
DataOutputStream out = new DataOutputStream(bufOut)
) {
out.writeLong(WAYPOINT_MAGIC_VALUE);
out.writeLong(waypoints.get(tag).size());
for (Waypoint waypoint : waypoints.get(tag)) {
out.writeUTF(waypoint.name);
out.writeLong(waypoint.creationTimestamp());
out.writeInt(waypoint.location.getX());
out.writeInt(waypoint.location.getY());
out.writeInt(waypoint.location.getZ());
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
public Set<Waypoint> getByTag(Waypoint.Tag tag) {
return Collections.unmodifiableSet(waypoints.get(tag));
}
public Waypoint getMostRecentByTag(Waypoint.Tag tag) {
// Find a waypoint of the given tag which has the greatest timestamp value, indicating the most recent
return this.waypoints.get(tag).stream().min(Comparator.comparingLong(w -> -w.creationTimestamp())).orElse(null);
}
public void addWaypoint(Waypoint waypoint) {
// no need to check for duplicate, because it's a Set not a List
waypoints.get(waypoint.tag).add(waypoint);
save(waypoint.tag);
}
}

View File

@@ -1,47 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 <https://www.gnu.org/licenses/>.
*/
package baritone.chunk;
import java.nio.file.Path;
/**
* Data about a world, from baritone's point of view. Includes cached chunks, waypoints, and map data.
*
* @author leijurv
*/
public class WorldData {
public final CachedWorld cache;
public final Waypoints waypoints;
//public final MapData map;
public final Path directory;
WorldData(Path directory) {
this.directory = directory;
this.cache = new CachedWorld(directory.resolve("cache"));
this.waypoints = new Waypoints(directory.resolve("waypoints"));
}
void onClose() {
new Thread() {
public void run() {
System.out.println("Started saving the world in a new thread");
cache.save();
}
}.start();
}
}

View File

@@ -1,109 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 <https://www.gnu.org/licenses/>.
*/
package baritone.chunk;
import baritone.Baritone;
import baritone.utils.Helper;
import baritone.utils.accessor.IAnvilChunkLoader;
import baritone.utils.accessor.IChunkProviderServer;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.server.integrated.IntegratedServer;
import net.minecraft.world.WorldServer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
/**
* @author Brady
* @since 8/4/2018 11:06 AM
*/
public enum WorldProvider implements Helper {
INSTANCE;
private final Map<Path, WorldData> worldCache = new HashMap<>();
private WorldData currentWorld;
public final WorldData getCurrentWorld() {
return this.currentWorld;
}
public final void initWorld(WorldClient world) {
int dimensionID = world.provider.getDimensionType().getId();
File directory;
File readme;
IntegratedServer integratedServer = mc.getIntegratedServer();
if (integratedServer != null) {
WorldServer localServerWorld = integratedServer.getWorld(dimensionID);
IChunkProviderServer provider = (IChunkProviderServer) localServerWorld.getChunkProvider();
IAnvilChunkLoader loader = (IAnvilChunkLoader) provider.getChunkLoader();
directory = loader.getChunkSaveLocation();
// Gets the "depth" of this directory relative the the game's run directory, 2 is the location of the world
if (directory.toPath().relativize(mc.gameDir.toPath()).getNameCount() != 2) {
// subdirectory of the main save directory for this world
directory = directory.getParentFile();
}
directory = new File(directory, "baritone");
readme = directory;
} else {
//remote
directory = new File(Baritone.INSTANCE.getDir(), mc.getCurrentServerData().serverIP);
readme = Baritone.INSTANCE.getDir();
}
// lol wtf is this baritone folder in my minecraft save?
try (FileOutputStream out = new FileOutputStream(new File(readme, "readme.txt"))) {
// good thing we have a readme
out.write("https://github.com/cabaletta/baritone\n".getBytes());
} catch (IOException ignored) {}
directory = new File(directory, "DIM" + dimensionID);
Path dir = directory.toPath();
if (!Files.exists(dir)) {
try {
Files.createDirectories(dir);
} catch (IOException ignored) {}
}
System.out.println("Baritone world data dir: " + dir);
this.currentWorld = this.worldCache.computeIfAbsent(dir, WorldData::new);
}
public final void closeWorld() {
WorldData world = this.currentWorld;
this.currentWorld = null;
if (world == null) {
return;
}
world.onClose();
}
public final void ifWorldLoaded(Consumer<WorldData> currentWorldConsumer) {
if (this.currentWorld != null) {
currentWorldConsumer.accept(this.currentWorld);
}
}
}

View File

@@ -1,100 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 <https://www.gnu.org/licenses/>.
*/
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<BlockPos> scanLoadedChunks(List<String> blockTypes, int max) {
List<Block> 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<BlockPos> res = new LinkedList<>();
if (asBlocks.isEmpty()) {
return res;
}
ChunkProviderClient chunkProvider = world().getChunkProvider();
int playerChunkX = playerFeet().getX() >> 4;
int playerChunkZ = playerFeet().getZ() >> 4;
int searchRadiusSq = 0;
while (true) {
boolean allUnloaded = true;
for (int xoff = -searchRadiusSq; xoff <= searchRadiusSq; xoff++) {
for (int zoff = -searchRadiusSq; zoff <= searchRadiusSq; zoff++) {
int distance = xoff * xoff + zoff * zoff;
if (distance != searchRadiusSq) {
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 && searchRadiusSq > 26) {
return res;
}
searchRadiusSq++;
}
}
}

View File

@@ -1,77 +1,71 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package baritone.launch;
import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.LaunchClassLoader;
import org.spongepowered.asm.launch.MixinBootstrap;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.Mixins;
import org.spongepowered.tools.obfuscation.mcp.ObfuscationServiceMCP;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* @author Brady
* @since 7/31/2018 9:59 PM
*/
public class BaritoneTweaker implements ITweaker {
List<String> args;
@Override
public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) {
this.args = new ArrayList<>(args);
if (gameDir != null) {
addArg("gameDir", gameDir.getAbsolutePath());
}
if (assetsDir != null) {
addArg("assetsDir", assetsDir.getAbsolutePath());
}
if (profile != null) {
addArg("version", profile);
}
}
@Override
public void injectIntoClassLoader(LaunchClassLoader classLoader) {
MixinBootstrap.init();
MixinEnvironment.getDefaultEnvironment().setSide(MixinEnvironment.Side.CLIENT);
MixinEnvironment.getDefaultEnvironment().setObfuscationContext(ObfuscationServiceMCP.NOTCH);
Mixins.addConfiguration("mixins.baritone.json");
}
@Override
public final String getLaunchTarget() {
return "net.minecraft.client.main.Main";
}
@Override
public final String[] getLaunchArguments() {
return this.args.toArray(new String[0]);
}
private void addArg(String label, String value) {
if (!args.contains("--" + label) && value != null) {
this.args.add("--" + label);
this.args.add(value);
}
}
}
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package baritone.launch;
import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.LaunchClassLoader;
import org.spongepowered.asm.launch.MixinBootstrap;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.Mixins;
import org.spongepowered.tools.obfuscation.mcp.ObfuscationServiceMCP;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* @author Brady
* @since 7/31/2018 9:59 PM
*/
public class BaritoneTweaker implements ITweaker {
List<String> args;
@Override
public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) {
this.args = new ArrayList<>(args);
if (gameDir != null) addArg("gameDir", gameDir.getAbsolutePath());
if (assetsDir != null) addArg("assetsDir", assetsDir.getAbsolutePath());
if (profile != null) addArg("version", profile);
}
@Override
public void injectIntoClassLoader(LaunchClassLoader classLoader) {
MixinBootstrap.init();
MixinEnvironment.getDefaultEnvironment().setSide(MixinEnvironment.Side.CLIENT);
MixinEnvironment.getDefaultEnvironment().setObfuscationContext(ObfuscationServiceMCP.NOTCH);
Mixins.addConfiguration("mixins.baritone.json");
}
@Override
public final String getLaunchTarget() {
return "net.minecraft.client.main.Main";
}
@Override
public final String[] getLaunchArguments() {
return this.args.toArray(new String[0]);
}
private void addArg(String label, String value) {
if (!args.contains("--" + label) && value != null) {
this.args.add("--" + label);
this.args.add(value);
}
}
}

View File

@@ -1,44 +1,44 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package baritone.launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.tools.obfuscation.mcp.ObfuscationServiceMCP;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* @author Brady
* @since 7/31/2018 10:09 PM
*/
public class BaritoneTweakerForge extends BaritoneTweaker {
@Override
public final void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) {
this.args = new ArrayList<>();
}
@Override
public final void injectIntoClassLoader(LaunchClassLoader classLoader) {
super.injectIntoClassLoader(classLoader);
MixinEnvironment.getDefaultEnvironment().setObfuscationContext(ObfuscationServiceMCP.SEARGE);
}
}
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package baritone.launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.tools.obfuscation.mcp.ObfuscationServiceMCP;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* @author Brady
* @since 7/31/2018 10:09 PM
*/
public class BaritoneTweakerForge extends BaritoneTweaker {
@Override
public final void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) {
this.args = new ArrayList<>();
}
@Override
public final void injectIntoClassLoader(LaunchClassLoader classLoader) {
super.injectIntoClassLoader(classLoader);
MixinEnvironment.getDefaultEnvironment().setObfuscationContext(ObfuscationServiceMCP.SEARGE);
}
}

View File

@@ -1,34 +1,34 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package baritone.launch;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* @author Brady
* @since 7/31/2018 10:10 PM
*/
public class BaritoneTweakerOptifine extends BaritoneTweaker {
@Override
public final void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) {
this.args = new ArrayList<>();
}
}
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package baritone.launch;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* @author Brady
* @since 7/31/2018 10:10 PM
*/
public class BaritoneTweakerOptifine extends BaritoneTweaker {
@Override
public final void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) {
this.args = new ArrayList<>();
}
}

Some files were not shown because too many files have changed in this diff Show More